java写一个贪吃蛇的代码
时间: 2024-01-06 20:05:08 浏览: 219
java写贪吃蛇代码
好的,以下是一个简单的 Java 贪吃蛇代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Snake extends JFrame implements KeyListener {
private static final long serialVersionUID = 1L;
private int x, y, fx, fy, len;
private int[] snakex = new int[400], snakey = new int[400];
private boolean[][] map = new boolean[40][40];
private JPanel panel;
private JLabel[] label = new JLabel[1600];
private boolean start = false, over = false;
public Snake() {
setTitle("贪吃蛇");
setBounds(100, 100, 405, 430);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = getContentPane();
container.setLayout(null);
panel = new JPanel();
panel.setBounds(0, 0, 400, 400);
panel.setBackground(Color.white);
panel.setLayout(null);
container.add(panel);
for (int i = 0; i < 1600; i++) {
label[i] = new JLabel();
label[i].setBounds((i % 40) * 10, (i / 40) * 10, 10, 10);
label[i].setOpaque(true);
label[i].setBackground(Color.white);
panel.add(label[i]);
}
addKeyListener(this);
setVisible(true);
init();
}
public void init() {
x = 20;
y = 20;
fx = (int) (Math.random() * 40);
fy = (int) (Math.random() * 40);
len = 3;
for (int i = 0; i < len; i++) {
snakex[i] = 20 - i;
snakey[i] = 20;
}
start = true;
over = false;
update();
}
public void update() {
if (over)
return;
for (int i = 0; i < 1600; i++) {
label[i].setBackground(Color.white);
}
if (x == fx && y == fy) {
len++;
fx = (int) (Math.random() * 40);
fy = (int) (Math.random() * 40);
}
if (len >= 400) {
JOptionPane.showMessageDialog(null, "恭喜你,你赢了!", "恭喜", JOptionPane.PLAIN_MESSAGE);
over = true;
return;
}
if (x < 0 || x >= 40 || y < 0 || y >= 40) {
JOptionPane.showMessageDialog(null, "游戏结束,你的得分为:" + (len - 3), "游戏结束", JOptionPane.PLAIN_MESSAGE);
over = true;
return;
}
if (map[x][y]) {
JOptionPane.showMessageDialog(null, "游戏结束,你的得分为:" + (len - 3), "游戏结束", JOptionPane.PLAIN_MESSAGE);
over = true;
return;
}
map[x][y] = true;
for (int i = len - 1; i >= 1; i--) {
snakex[i] = snakex[i - 1];
snakey[i] = snakey[i - 1];
}
snakex[0] = x;
snakey[0] = y;
for (int i = 0; i < len; i++) {
label[snakey[i] * 40 + snakex[i]].setBackground(Color.blue);
}
label[fy * 40 + fx].setBackground(Color.red);
}
@Override
public void keyPressed(KeyEvent e) {
if (!start || over)
return;
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
if (len > 1 && snakey[0] == snakey[1])
return;
x--;
update();
} else if (key == KeyEvent.VK_DOWN) {
if (len > 1 && snakey[0] == snakey[1])
return;
x++;
update();
} else if (key == KeyEvent.VK_LEFT) {
if (len > 1 && snakex[0] == snakex[1])
return;
y--;
update();
} else if (key == KeyEvent.VK_RIGHT) {
if (len > 1 && snakex[0] == snakex[1])
return;
y++;
update();
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
public static void main(String[] args) {
new Snake();
}
}
```
这个代码实现了一个简单的贪吃蛇游戏,使用了 Swing 组件和键盘事件监听。如果想要进行更复杂的贪吃蛇游戏开发,可以考虑使用更高级的游戏引擎和图形库。
阅读全文