编写贪吃蛇游戏是一个相对复杂的任务,需要使用图形库或者图形用户界面(GUI)库来实现游戏界面和交互。以下是一个简单的贪吃蛇游戏的示例代码,使用 JavaFX 库实现:
```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SnakeGame extends Application {
private static final int TILE_SIZE = 20;
private static final int WIDTH = 20;
private static final int HEIGHT = 15;
private int[][] grid = new int[WIDTH][HEIGHT];
private int snakeX = 10;
private int snakeY = 7;
private int appleX;
private int appleY;
private Direction direction = Direction.RIGHT;
private enum Direction {
UP, DOWN, LEFT, RIGHT
}
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE);
GraphicsContext gc = canvas.getGraphicsContext2D();
Pane root = new Pane(canvas);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Snake Game");
primaryStage.show();
generateApple();
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP:
direction = Direction.UP;
break;
case DOWN:
direction = Direction.DOWN;
break;
case LEFT:
direction = Direction.LEFT;
break;
case RIGHT:
direction = Direction.RIGHT;
break;
}
});
new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
update();
draw(gc);
}
}).start();
}
private void update() {
switch (direction) {
case UP:
snakeY--;
break;
case DOWN:
snakeY++;
break;
case LEFT:
snakeX--;
break;
case RIGHT:
snakeX++;
break;
}
if (snakeX < 0 || snakeX >= WIDTH || snakeY < 0 || snakeY >= HEIGHT) {
// Game over
System.exit(0);
}
if (snakeX == appleX && snakeY == appleY) {
// Eat the apple
generateApple();
}
}
private void generateApple() {
appleX = (int) (Math.random() * WIDTH);
appleY = (int) (Math.random() * HEIGHT);
}
private void draw(GraphicsContext gc) {
// Clear canvas
gc.setFill(Color.BLACK);
gc.fillRect(0, 0, WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE);
// Draw snake
gc.setFill(Color.GREEN);
gc.fillRect(snakeX * TILE_SIZE, snakeY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
// Draw apple
gc.setFill(Color.RED);
gc.fillOval(appleX * TILE_SIZE, appleY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
public static void main(String[] args) {
launch(args);
}
}
```
这个示例中使用了 JavaFX 库来创建游戏窗口和绘制游戏界面。游戏中,使用方向键来控制贪吃蛇的移动,贪吃蛇吃到苹果后长度增加,若撞到墙壁则游戏结束。