java 课程设计 贪吃蛇
时间: 2024-01-12 16:22:58 浏览: 169
以下是一个简单的Java贪吃蛇游戏的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
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 int[] x = new int[GAME_UNITS];
private final int[] y = new int[GAME_UNITS];
private int bodyParts = 6;
private int applesEaten;
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;
public SnakeGame() {
setTitle("Snake Game");
setSize(WIDTH, HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
repaint();
}
}
});
timer.start();
}
public void paint(Graphics g) {
// 绘制背景
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 绘制苹果
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);
} else {
g.setColor(new Color(45, 180, 0));
}
g.fillRect(x[i], y[i], 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] >= WIDTH || y[0] < 0 || y[0] >= HEIGHT) {
running = false;
}
if (!running) {
timer.stop();
}
}
public void newApple() {
Random random = new Random();
appleX = random.nextInt((WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = random.nextInt((HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (direction != 'D') {
direction = 'U'; }
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') {
direction = 'D';
}
break;
case KeyEvent.VK_LEFT:
if (direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L') {
direction = 'R';
}
break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new SnakeGame();
}
}
```
阅读全文