下面是一個簡單的Java實現貪吃蛇游戲的示例代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SnakeGame extends JFrame implements KeyListener {
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private int snakeX;
private int snakeY;
private int appleX;
private int appleY;
private int direction;
public SnakeGame() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
addKeyListener(this);
snakeX = WIDTH / 2;
snakeY = HEIGHT / 2;
appleX = (int) (Math.random() * WIDTH);
appleY = (int) (Math.random() * HEIGHT);
direction = 0;
startGameLoop();
}
private void startGameLoop() {
while (true) {
moveSnake();
checkCollision();
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void moveSnake() {
if (direction == 0) snakeX++;
if (direction == 1) snakeY++;
if (direction == 2) snakeX--;
if (direction == 3) snakeY--;
}
private void checkCollision() {
if (snakeX == appleX && snakeY == appleY) {
appleX = (int) (Math.random() * WIDTH);
appleY = (int) (Math.random() * HEIGHT);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.RED);
g.fillRect(appleX, appleY, 10, 10);
g.setColor(Color.GREEN);
g.fillRect(snakeX, snakeY, 10, 10);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT && direction != 2) direction = 0;
if (key == KeyEvent.VK_DOWN && direction != 3) direction = 1;
if (key == KeyEvent.VK_LEFT && direction != 0) direction = 2;
if (key == KeyEvent.VK_UP && direction != 1) direction = 3;
}
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
new SnakeGame();
}
}
這段代碼是一個簡單的貪吃蛇游戲的實現,使用Java的Swing庫進行繪制。
在構造函數中設置了窗口的大小、位置等屬性,并初始化了貪吃蛇和蘋果的位置以及當前運動方向。
startGameLoop()方法是游戲的主循環,不斷地移動貪吃蛇、檢查碰撞并重繪窗口。
moveSnake()方法根據當前的方向移動貪吃蛇的位置。
checkCollision()方法檢查貪吃蛇是否與蘋果碰撞,如果碰撞則重新生成蘋果的位置。
paint()方法用于繪制窗口的內容,包括背景、蘋果和貪吃蛇。
keyPressed()方法用于處理鍵盤按鍵事件,根據按鍵改變貪吃蛇的方向。
你可以將這段代碼保存為SnakeGame.java文件,并使用Java編譯器進行編譯運行。