用java写一段贪吃蛇代码
时间: 2023-05-20 10:04:59 浏览: 164
好的,以下是一段简单的贪吃蛇代码,使用Java语言编写:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Snake extends JFrame implements KeyListener {
private int width = 300;
private int height = 300;
private int x = 150;
private int y = 150;
private int size = 10;
private int dx = 0;
private int dy = 0;
private Timer timer;
private boolean gameOver = false;
public Snake() {
setTitle("Snake");
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
move();
repaint();
}
});
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
if (!gameOver) {
g.setColor(Color.GREEN);
g.fillRect(x, y, size, size);
} else {
g.setColor(Color.RED);
g.drawString("Game Over", 100, 150);
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -size;
dy = 0;
} else if (key == KeyEvent.VK_RIGHT) {
dx = size;
dy = 0;
} else if (key == KeyEvent.VK_UP) {
dx = 0;
dy = -size;
} else if (key == KeyEvent.VK_DOWN) {
dx = 0;
dy = size;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void move() {
x += dx;
y += dy;
if (x < 0 || x >= width || y < 0 || y >= height) {
gameOver = true;
timer.stop();
}
}
public static void main(String[] args) {
new Snake();
}
}
```
这段代码实现了一个简单的贪吃蛇游戏,使用了Java的图形界面库Swing。玩家可以通过方向键控制蛇的移动方向,蛇会不断移动并吃掉食物,如果撞到墙壁或自己的身体,则游戏结束。
阅读全文