温馨提示×

Java实现贪吃蛇游戏代码怎么写

小亿
107
2023-08-09 12:21:47
栏目: 编程语言

以下是一个简单的Java实现贪吃蛇游戏的代码示例:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame {
private Snake snake;
private Apple apple;
private Timer timer;
public SnakeGame() {
snake = new Snake();
apple = new Apple();
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
snake.move();
if (snake.collidesWith(apple)) {
snake.grow();
apple.generate();
}
if (snake.collidesWithSelf() || snake.outOfBounds()) {
gameOver();
}
repaint();
}
});
}
public void startGame() {
timer.start();
}
public void gameOver() {
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
}
public void paint(Graphics g) {
super.paint(g);
snake.paint(g);
apple.paint(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SnakeGame game = new SnakeGame();
game.setTitle("Snake Game");
game.setSize(500, 500);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setResizable(false);
game.setVisible(true);
game.startGame();
}
});
}
}
class Snake {
private static final int SIZE = 20;
private static final int MAX_SIZE = 1000;
private Point[] body;
private int length;
private int direction;
public Snake() {
body = new Point[MAX_SIZE];
length = 1;
direction = KeyEvent.VK_RIGHT;
body[0] = new Point(0, 0);
}
public void move() {
for (int i = length - 1; i > 0; i--) {
body[i] = new Point(body[i - 1]);
}
switch (direction) {
case KeyEvent.VK_UP:
body[0].y -= SIZE;
break;
case KeyEvent.VK_DOWN:
body[0].y += SIZE;
break;
case KeyEvent.VK_LEFT:
body[0].x -= SIZE;
break;
case KeyEvent.VK_RIGHT:
body[0].x += SIZE;
break;
}
}
public boolean collidesWith(Apple apple) {
return body[0].equals(apple.getPosition());
}
public boolean collidesWithSelf() {
for (int i = 1; i < length; i++) {
if (body[0].equals(body[i])) {
return true;
}
}
return false;
}
public boolean outOfBounds() {
return body[0].x < 0 || body[0].x >= 500 || body[0].y < 0 || body[0].y >= 500;
}
public void grow() {
if (length < MAX_SIZE) {
body[length++] = new Point();
}
}
public void paint(Graphics g) {
g.setColor(Color.GREEN);
for (int i = 0; i < length; i++) {
g.fillRect(body[i].x, body[i].y, SIZE, SIZE);
}
}
}
class Apple {
private static final int SIZE = 20;
private Point position;
public Apple() {
position = new Point();
generate();
}
public void generate() {
int x = (int) (Math.random() * 25) * SIZE;
int y = (int) (Math.random() * 25) * SIZE;
position.setLocation(x, y);
}
public Point getPosition() {
return position;
}
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(position.x, position.y, SIZE, SIZE);
}
}

这段代码包含了SnakeGame类、Snake类和Apple类,SnakeGame类负责处理游戏的逻辑和绘制,Snake类和Apple类分别代表贪吃蛇和苹果。

在SnakeGame类中,使用了JFrame和Timer来进行界面绘制和定时更新。Snake类中包含了贪吃蛇的移动、碰撞检测和绘制等方法。Apple类中包含了苹果的生成和绘制方法。

这只是一个简单的示例,你可以根据需要进行修改和扩展。

0