为以下代码写出注释g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE); } } } else { gameOver(g); } } public void gameOver(Graphics g) { String msg = "Game Over"; g.setColor(Color.WHITE); g.drawString(msg, (WIDTH - 56) / 2, HEIGHT / 2); timer.stop(); } public void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } public void move() { for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[0] -= DOT_SIZE; } if (rightDirection) { x[0] += DOT_SIZE; } if (upDirection) { y[0] -= DOT_SIZE; } if (downDirection) { y[0] += DOT_SIZE; } } public void checkCollision() { for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if (!inGame) { timer.stop(); } } public void locateApple() { Random r = new Random(); apple_x = r.nextInt(RAND_POS) * DOT_SIZE; apple_y = r.nextInt(RAND_POS) * DOT_SIZE; } public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); }
时间: 2024-03-29 20:35:59 浏览: 115
// 绘制小方块
g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE);
// 判断游戏是否结束,如果结束则展示 "Game Over" 字符串并停止计时器
public void gameOver(Graphics g) {
String msg = "Game Over";
g.setColor(Color.WHITE);
g.drawString(msg, (WIDTH - 56) / 2, HEIGHT / 2);
timer.stop();
}
// 检查是否吃到苹果,如果吃到则增加小方块的数量并重新生成苹果
public void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
// 移动小方块
public void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
// 检查是否发生碰撞,如果发生碰撞则游戏结束
public void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
// 随机生成苹果的位置
public void locateApple() {
Random r = new Random();
apple_x = r.nextInt(RAND_POS) * DOT_SIZE;
apple_y = r.nextInt(RAND_POS) * DOT_SIZE;
}
// 每次计时器触发时执行的操作,包括检查是否吃到苹果、是否发生碰撞、移动小方块
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
阅读全文