开发环境准备
在开始编写贪吃蛇游戏之前,我们需要准备好Java开发环境。推荐使用JDK 8或以上版本,开发工具可以选择Eclipse、IntelliJ IDEA等主流IDE。本项目不需要任何第三方库,完全使用Java标准库实现。
游戏基本架构设计
一个完整的贪吃蛇游戏通常包含以下几个核心组件:
1. 游戏主循环
2. 蛇身移动逻辑
3. 食物生成系统
4. 碰撞检测
5. 计分系统
6. 游戏界面渲染
我们将采用面向对象的方式设计这些组件,确保代码结构清晰、易于扩展。
核心代码实现
1. 游戏主类设计
public class SnakeGame {
public static void main(String[] args) {
new GameFrame();
}
}
2. 游戏窗口类
import javax.swing.*;
public class GameFrame extends JFrame {
GamePanel panel;
public GameFrame() {
panel = new GamePanel();
this.add(panel);
this.setTitle("Java贪吃蛇");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
3. 游戏面板类
游戏面板类是核心逻辑所在,负责处理游戏状态、蛇身移动、食物生成等:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / UNIT_SIZE;
static final int DELAY = 75;
final int[] x = new int[GAME_UNITS];
final int[] y = new int[GAME_UNITS];
int bodyParts = 3;
int applesEaten = 0;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
public GamePanel() {
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
// 绘制网格线
for(int i = 0; i < SCREEN_HEIGHT/UNIT_SIZE; i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
// 绘制食物
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
// 绘制蛇身
for(int i = 0; i < bodyParts; i++) {
if(i == 0) {
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(45, 180, 0));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
// 显示分数
g.setColor(Color.white);
g.setFont(new Font("微软雅黑", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("分数: " + applesEaten,
(SCREEN_WIDTH - metrics.stringWidth("分数: " + applesEaten))/2,
g.getFont().getSize());
} else {
gameOver(g);
}
}
public void newApple() {
appleX = random.nextInt(SCREEN_WIDTH/UNIT_SIZE) * UNIT_SIZE;
appleY = random.nextInt(SCREEN_HEIGHT/UNIT_SIZE) * UNIT_SIZE;
}
public void move() {
for(int i = bodyParts; i > 0; i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
// 检查是否撞到自身
for(int i = bodyParts; i > 0; i--) {
if((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
}
}
// 检查是否撞到边界
if(x[0] < 0 || x[0] >= SCREEN_WIDTH || y[0] < 0 || y[0] >= SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
// 显示游戏结束信息
g.setColor(Color.red);
g.setFont(new Font("微软雅黑", Font.BOLD, 75));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("游戏结束",
(SCREEN_WIDTH - metrics.stringWidth("游戏结束"))/2,
SCREEN_HEIGHT/2);
// 显示最终分数
g.setColor(Color.white);
g.setFont(new Font("微软雅黑", Font.BOLD, 40));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("最终分数: " + applesEaten,
(SCREEN_WIDTH - metrics2.stringWidth("最终分数: " + applesEaten))/2,
SCREEN_HEIGHT/2 + 100);
}
@Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
功能扩展与优化
1. 添加游戏暂停功能
在GamePanel类中添加以下代码实现暂停功能:
boolean paused = false;
// 在MyKeyAdapter类中添加
case KeyEvent.VK_SPACE:
paused = !paused;
if(paused) {
timer.stop();
} else {
timer.start();
}
break;
// 修改actionPerformed方法
@Override
public void actionPerformed(ActionEvent e) {
if(running && !paused) {
move();
checkApple();
checkCollisions();
}
repaint();
}
2. 添加游戏难度选择
可以修改DELAY常量来调整游戏速度,或者添加难度选择菜单:
// 在GamePanel类中添加
int difficulty = 1; // 1-简单, 2-中等, 3-困难
// 修改startGame方法
public void startGame() {
newApple();
running = true;
int delay = switch(difficulty) {
case 1 -> 150; // 简单
case 2 -> 75; // 中等
case 3 -> 40; // 困难
default -> 75;
};
timer = new Timer(delay, this);
timer.start();
}
3. 添加游戏音效
可以使用Java的AudioClip添加简单的音效:
import java.applet.AudioClip;
// 在GamePanel类中添加
AudioClip eatSound, gameOverSound;
// 在构造方法中初始化
public GamePanel() {
// ...其他代码
try {
eatSound = Applet.newAudioClip(getClass().getResource("eat.wav"));
gameOverSound = Applet.newAudioClip(getClass().getResource("gameover.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
// 在checkApple方法中播放音效
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
eatSound.play();
newApple();
}
}
// 在checkCollisions方法中播放音效
public void checkCollisions() {
// ...碰撞检测代码
if(!running) {
gameOverSound.play();
timer.stop();
}
}
进阶功能:AI自动玩贪吃蛇
我们可以为贪吃蛇添加简单的AI功能,让它自动寻找食物:
// 在GamePanel类中添加AI模式
boolean aiMode = false;
// 添加AI移动逻辑
public void aiMove() {
// 简单AI:朝食物方向移动
if(appleX > x[0]) {
if(direction != 'L') direction = 'R';
} else if(appleX < x[0]) {
if(direction != 'R') direction = 'L';
} else if(appleY > y[0]) {
if(direction != 'U') direction = 'D';
} else if(appleY < y[0]) {
if(direction != 'D') direction = 'U';
}
}
// 修改actionPerformed方法
@Override
public void actionPerformed(ActionEvent e) {
if(running && !paused) {
if(aiMode) {
aiMove();
}
move();
checkApple();
checkCollisions();
}
repaint();
}
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。