以下是一個簡單的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類中包含了蘋果的生成和繪制方法。
這只是一個簡單的示例,你可以根據需要進行修改和擴展。