用java写一个贪吃蛇小游戏
时间: 2023-12-07 09:14:00 浏览: 63
好的,下面是一个简单的贪吃蛇小游戏的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private Timer timer;
private Snake snake;
private Food food;
public SnakeGame() {
setTitle("Snake Game");
setSize(WIDTH, HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 初始化蛇和食物
snake = new Snake();
food = new Food();
// 设置定时器
timer = new Timer(100, this);
timer.start();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// 移动蛇
snake.move();
// 如果蛇吃到了食物,重新生成食物
if (snake.eat(food)) {
food = new Food();
}
// 如果蛇撞到了墙壁或者自己的身体,游戏结束
if (snake.hitWall() || snake.hitBody()) {
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over");
System.exit(0);
}
repaint();
}
public void paint(Graphics g) {
// 绘制背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 绘制蛇和食物
snake.draw(g);
food.draw(g);
}
public static void main(String[] args) {
new SnakeGame();
}
}
class Snake {
private final int SIZE = 10;
private final int WIDTH = 300;
private final int HEIGHT = 300;
private int[] x = new int[WIDTH * HEIGHT / (SIZE * SIZE)];
private int[] y = new int[WIDTH * HEIGHT / (SIZE * SIZE)];
private int length = 3;
private int direction = KeyEvent.VK_RIGHT;
public Snake() {
// 初始化蛇的位置
x[0] = 50;
y[0] = 50;
x[1] = 40;
y[1] = 50;
x[2] = 30;
y[2] = 50;
}
public void move() {
// 移动蛇的身体
for (int i = length - 1; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
// 移动蛇的头部
switch (direction) {
case KeyEvent.VK_UP:
y[0] -= SIZE;
break;
case KeyEvent.VK_DOWN:
y[0] += SIZE;
break;
case KeyEvent.VK_LEFT:
x[0] -= SIZE;
break;
case KeyEvent.VK_RIGHT:
x[0] += SIZE;
break;
}
}
public boolean eat(Food food) {
// 如果蛇的头部和食物位置重合,说明蛇吃到了食物
if (x[0] == food.getX() && y[0] == food.getY()) {
length++;
return true;
} else {
return false;
}
}
public boolean hitWall() {
// 如果蛇撞到了墙壁,返回true
if (x[0] < 0 || x[0] >= WIDTH || y[0] < 0 || y[0] >= HEIGHT) {
return true;
} else {
return false;
}
}
public boolean hitBody() {
// 如果蛇撞到了自己的身体,返回true
for (int i = 1; i < length; i++) {
if (x[0] == x[i] && y[0] == y[i]) {
return true;
}
}
return false;
}
public void draw(Graphics g) {
// 绘制蛇的身体
for (int i = 0; i < length; i++) {
g.setColor(Color.BLACK);
g.fillRect(x[i], y[i], SIZE, SIZE);
}
}
public void setDirection(int direction) {
this.direction = direction;
}
}
class Food {
private final int SIZE = 10;
private final int WIDTH = 300;
private final int HEIGHT = 300;
private int x;
private int y;
public Food() {
// 随机生成食物的位置
x = (int) (Math.random() * (WIDTH - SIZE) / SIZE) * SIZE;
y = (int) (Math.random() * (HEIGHT - SIZE) / SIZE) * SIZE;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void draw(Graphics g) {
// 绘制食物
g.setColor(Color.RED);
g.fillRect(x, y, SIZE, SIZE);
}
}
```
这个代码示例实现了一个简单的贪吃蛇小游戏,包含了蛇的移动、吃食物、撞墙或撞身体时游戏结束等功能。你可以在此基础上进行修改和扩展,实现更丰富的游戏玩法。
阅读全文