import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;public class SnakeGame extends JPanel implements KeyListener, ActionListener {
// 游戏区域的宽度和高度
private final int BOARD_WIDTH = 600;
private final int BOARD_HEIGHT = 600;
// 每个单元格的大小
private final int UNIT_SIZE = 25;
// 游戏区域的单元格数
private final int GAME_UNITS = (BOARD_WIDTH * BOARD_HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
// 游戏的延迟时间,决定了游戏的速度
private final int DELAY = 75;
// 蛇的身体部分数量
private int bodyParts = 6;
// 苹果的坐标
private int appleX;
private int appleY;
// 蛇每个部分的坐标
private final int[] x = new int[GAME_UNITS];
private final int[] y = new int[GAME_UNITS];
// 蛇的运动方向
private char direction = 'R'; // 初始方向为右
// 游戏是否正在运行
private boolean running = false;
// 定时器,用于控制游戏速度
private Timer timer;// 构造方法,初始化游戏界面并开始游戏
public SnakeGame() {
this.setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(this);
startGame();
}// 启动游戏
public void startGame() {
newApple(); // 生成苹果
running = true; // 设置游戏状态为运行
timer = new Timer(DELAY, this); // 创建定时器,控制游戏速度
timer.start(); // 启动定时器
}// 绘制游戏界面
public void paintComponent(Graphics g) {
super.paintCompon
04-13
432
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-05
2054
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-02
1147
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-16
3685
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-08
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交