使用Java写贪吃蛇小游戏
时间: 2023-07-20 09:12:29 浏览: 121
JAVA贪吃蛇小游戏
好的,下面是一个简单的 Java 代码实现贪吃蛇小游戏的示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements KeyListener, ActionListener {
private int width = 300;
private int height = 300;
private int size = 10;
private int x = width / size / 2 * size;
private int y = height / size / 2 * size;
private int fx = (int)(Math.random() * (width / size)) * size;
private int fy = (int)(Math.random() * (height / size)) * size;
private int score = 0;
private int dir = KeyEvent.VK_RIGHT;
private Timer timer = new Timer(100, this);
private boolean running = true;
private boolean[][] map = new boolean[width / size][height / size];
public SnakeGame() {
setTitle("Snake Game");
setSize(width, height);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addKeyListener(this);
setVisible(true);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(fx, fy, size, size);
g.setColor(Color.BLACK);
for (int i = 0; i < width / size; i++) {
for (int j = 0; j < height / size; j++) {
if (map[i][j]) {
g.fillRect(i * size, j * size, size, size);
}
}
}
g.setColor(Color.BLUE);
g.drawString("Score: " + score, 10, 20);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT && dir != KeyEvent.VK_RIGHT) {
dir = key;
}
if (key == KeyEvent.VK_UP && dir != KeyEvent.VK_DOWN) {
dir = key;
}
if (key == KeyEvent.VK_RIGHT && dir != KeyEvent.VK_LEFT) {
dir = key;
}
if (key == KeyEvent.VK_DOWN && dir != KeyEvent.VK_UP) {
dir = key;
}
}
public void actionPerformed(ActionEvent e) {
if (!running) {
return;
}
switch (dir) {
case KeyEvent.VK_LEFT:
x -= size;
break;
case KeyEvent.VK_UP:
y -= size;
break;
case KeyEvent.VK_RIGHT:
x += size;
break;
case KeyEvent.VK_DOWN:
y += size;
break;
}
if (x < 0 || x >= width || y < 0 || y >= height) {
running = false;
JOptionPane.showMessageDialog(this, "Game Over!");
return;
}
if (x == fx && y == fy) {
score++;
fx = (int)(Math.random() * (width / size)) * size;
fy = (int)(Math.random() * (height / size)) * size;
} else {
map[x / size][y / size] = true;
map[(x - dir % 2 * 2 + dir % 4 - 1) / size][(y - dir % 2 * 2 + dir % 4 - 1) / size] = false;
}
repaint();
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new SnakeGame();
}
}
```
这个示例代码实现了一个基本的贪吃蛇小游戏,玩家可以通过方向键来控制贪吃蛇的移动方向,吃到食物会增加分数,撞到墙壁或自己身体会游戏结束。
阅读全文