java代码写一个贪吃蛇
时间: 2024-01-06 15:03:21 浏览: 168
好的,以下是一个简单的 Java 贪吃蛇游戏的代码:
```
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Snake extends JFrame implements KeyListener, ActionListener {
private JPanel panel;
private JLabel score;
private int delay = 100;
private Timer timer;
private int x[] = new int[100];
private int y[] = new int[100];
private int length = 3;
private int appleX, appleY;
private int direction = KeyEvent.VK_RIGHT;
private ImageIcon imgSnake = new ImageIcon("snake.png");
private ImageIcon imgHead = new ImageIcon("head.png");
private ImageIcon imgApple = new ImageIcon("apple.png");
public Snake() {
setTitle("贪吃蛇");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setResizable(false);
panel = new JPanel();
panel.setBackground(Color.white);
panel.setLayout(null);
setContentPane(panel);
score = new JLabel("得分: 0");
score.setBounds(10, 10, 100, 20);
panel.add(score);
for(int i = 0; i < length; i ++) {
x[i] = 100 - i * 10;
y[i] = 100;
}
newApple();
timer = new Timer(delay, this);
timer.start();
addKeyListener(this);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
imgApple.paintIcon(this, g, appleX, appleY);
for(int i = 0; i < length; i ++) {
if(i == 0) {
imgHead.paintIcon(this, g, x[i], y[i]);
} else {
imgSnake.paintIcon(this, g, x[i], y[i]);
}
}
}
public void actionPerformed(ActionEvent e) {
move();
eat();
checkCrash();
repaint();
}
public void move() {
for(int i = length; i > 0; i --) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
if(direction == KeyEvent.VK_LEFT) {
x[0] -= 10;
} else if(direction == KeyEvent.VK_RIGHT) {
x[0] += 10;
} else if(direction == KeyEvent.VK_UP) {
y[0] -= 10;
} else if(direction == KeyEvent.VK_DOWN) {
y[0] += 10;
}
}
public void eat() {
if(x[0] == appleX && y[0] == appleY) {
length ++;
score.setText("得分: " + (length - 3) * 10);
newApple();
}
}
public void checkCrash() {
if(x[0] < 0 || x[0] > 490 || y[0] < 0 || y[0] > 490) {
gameOver();
}
for(int i = 1; i < length; i ++) {
if(x[0] == x[i] && y[0] == y[i]) {
gameOver();
}
}
}
public void newApple() {
appleX = (int) (Math.random() * 49) * 10;
appleY = (int) (Math.random() * 49) * 10;
}
public void gameOver() {
timer.stop();
JOptionPane.showMessageDialog(this, "游戏结束");
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if((code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN) && Math.abs(code - direction) != 2) {
direction = code;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new Snake();
}
}
```
注意: 上述代码需要三张图片文件作为素材,分别是蛇身、蛇头和苹果图,可以根据实际需要自行调整。
阅读全文