能不能利用java写一段能运行贪吃蛇的代码
时间: 2023-11-27 08:55:33 浏览: 64
Java编写贪吃蛇代码
4星 · 用户满意度95%
当然可以!以下是一个简单的 Java 贪吃蛇游戏代码示例,希望能帮到你:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JPanel implements ActionListener {
private Timer timer;
private boolean running;
private int size = 20;
private int x[] = new int[400];
private int y[] = new int[400];
private int body = 3;
private int appleX, appleY;
private boolean left, right, up, down;
public SnakeGame() {
setPreferredSize(new Dimension(400, 400));
setBackground(Color.black);
setFocusable(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT && !right) {
left = true;
up = false;
down = false;
}
if (keyCode == KeyEvent.VK_RIGHT && !left) {
right = true;
up = false;
down = false;
}
if (keyCode == KeyEvent.VK_UP && !down) {
up = true;
left = false;
right = false;
}
if (keyCode == KeyEvent.VK_DOWN && !up) {
down = true;
left = false;
right = false;
}
}
});
startGame();
}
public void startGame() {
x[0] = 0;
y[0] = 0;
x[1] = -size;
y[1] = 0;
x[2] = -2 * size;
y[2] = 0;
appleX = (int) (Math.random() * 20) * size;
appleY = (int) (Math.random() * 20) * size;
running = true;
timer = new Timer(100, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (running) {
g.setColor(Color.red);
g.fillOval(appleX, appleY, size, size);
for (int i = 0; i < body; i++) {
if (i == 0) {
g.setColor(Color.green);
} else {
g.setColor(Color.white);
}
g.fillRect(x[i], y[i], size, size);
}
} else {
g.setColor(Color.white);
g.setFont(new Font("Arial", Font.BOLD, 30));
g.drawString("Game Over!", 150, 200);
}
}
public void actionPerformed(ActionEvent e) {
if (running) {
for (int i = body; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
if (left) {
x[0] -= size;
}
if (right) {
x[0] += size;
}
if (up) {
y[0] -= size;
}
if (down) {
y[0] += size;
}
if (x[0] == appleX && y[0] == appleY) {
body++;
appleX = (int) (Math.random() * 20) * size;
appleY = (int) (Math.random() * 20) * size;
}
for (int i = 1; i < body; i++) {
if (x[0] == x[i] && y[0] == y[i] || x[0] < 0 || x[0] > 380 || y[0] < 0 || y[0] > 380) {
running = false;
}
}
repaint();
} else {
timer.stop();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new SnakeGame());
frame.pack();
frame.setVisible(true);
}
}
```
这个代码使用了 Java 的 Swing 库来绘制游戏界面,使用了计时器(Timer)来控制游戏的运行,具体实现可以看代码中的注释。
阅读全文