import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JPanel implements ActionListener {
private final int SCALE = 10; // 定义每个网格的大小
private final int WIDTH = 60; // 游戏区域宽度
private final int HEIGHT = 40; // 游戏区域高度
private int speed = 50; // 贪吃蛇移动速度,可调整
private int score = 0; // 得分
private Timer timer;
private boolean gameOver = false;
private int length = 3; // 初始贪吃蛇长度
private int[] x = new int[WIDTH * HEIGHT]; // 贪吃蛇坐标数组
private int[] y = new int[WIDTH * HEIGHT];
private boolean left = false; // 标记当前方向
private boolean right = true;
private boolean up = false;
private boolean down = false;
private int foodX; // 食物坐标
private int foodY;
public SnakeGame() {
init();
addKeyListener(new Keyboard());
setFocusable(true);
timer = new Timer(speed, this);
timer.start();
}
public void init() {
x[0] = 20;
y[0] = 20;
x[1] = 19;
y[1] = 20;
x[2] = 18;
y[2] = 20;
generateFood();
}
public void generateFood() {
foodX = (int) (Math.random() * WIDTH) * SCALE;
foodY = (int) (Math.random() * HEIGHT) * SCALE;
}
public void paint(Graphics g) {
super.paint(g);
if (!gameOver) {
g.setColor(Color.red);
g.fillRect(foodX, foodY, SCALE, SCALE);
for (int i = 0;