下面是一个简单的Java实现贪吃蛇游戏的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SnakeGame extends JFrame implements KeyListener {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int UNIT_SIZE = 20;
private static final int GAME_UNITS = (WIDTH * HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
private static final int DELAY = 75;
private final List
private final List
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;
private final Random random;
public SnakeGame() {
random = new Random();
setTitle("Snake Game");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
addKeyListener(this);
startGame();
}
private void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, e -> gameLoop());
timer.start();
snakeX.add(WIDTH / 2);
snakeY.add(HEIGHT / 2);
}
private void gameLoop() {
move();
checkCollision();
repaint();
}
private void move() {
for (int i = snakeX.size() - 1; i > 0; i--) {
snakeX.set(i, snakeX.get(i - 1));
snakeY.set(i, snakeY.get(i - 1));
}
switch (direction) {
case 'U':
snakeY.set(0, snakeY.get(0) - UNIT_SIZE);
break;
case 'D':
snakeY.set(0, snakeY.get(0) + UNIT_SIZE);
break;
case 'L':
snakeX.set(0, snakeX.get(0) - UNIT_SIZE);
break;
case 'R':
snakeX.set(0, snakeX.get(0) + UNIT_SIZE);
break;
}
}
private void checkCollision() {
// 检查是否撞到自己
for (int i = snakeX.size() - 1; i > 0; i--) {
if (snakeX.get(0).equals(snakeX.get(i)) && snakeY.get(0).equals(snakeY.get(i))) {
gameOver();
}
}
// 检查是否撞到边界
if (snakeX.get(0) < 0 || snakeX.get(0) >= WIDTH || snakeY.get(0) < 0 || snakeY.get(0) >= HEIGHT) {
gameOver();
}
// 检查是否吃到苹果
if (snakeX.get(0).equals(appleX) && snakeY.get(0).equals(appleY)) {
snakeX.add(snakeX.get(snakeX.size() - 1));
snakeY.add(snakeY.get(snakeY.size() - 1));
newApple();
}
}
private void gameOver() {
running = false;
timer.stop();
}
private void newApple() {
appleX = random.nextInt((WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = random.nextInt((HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}
@Override
public void paint(Graphics g) {
g.clearRect(0, 0, WIDTH, HEIGHT);
// 画网格
for (int i = 0; i < WIDTH / UNIT_SIZE; i++) {
g.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, HEIGHT);
}
for (int i = 0; i < HEIGHT / UNIT_SIZE; i++) {
g.drawLine(0, i * UNIT_SIZE, WIDTH, i * UNIT_SIZE);
}
// 画蛇
for (int i = 0; i < snakeX.size(); i++) {
g.setColor(Color.GREEN);
g.fillRect(snakeX.get(i), snakeY.get(i), UNIT_SIZE, UNIT_SIZE);
}
// 画苹果
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (direction