基础java8写一个贪吃蛇游戏
时间: 2023-08-04 13:19:03 浏览: 58
贪吃蛇游戏是一个比较经典的小游戏,下面是一个基于 Java 8 的简单实现,使用 JavaFX 图形界面库进行界面展示。
SnakeGame.java
```java
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.LinkedList;
import java.util.Random;
public class SnakeGame extends Application {
private static final int ROWS = 20;
private static final int COLS = 20;
private static final int BLOCK_SIZE = 20;
private static final int INITIAL_SNAKE_LENGTH = 3;
private Random random = new Random();
private int score = 0;
private LinkedList<Position> snake = new LinkedList<>();
private Direction direction = Direction.RIGHT;
private Position food;
private boolean isGameOver = false;
private GridPane gridPane;
private Label scoreLabel;
private Timeline timeline;
@Override
public void start(Stage primaryStage) {
gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
scoreLabel = new Label("Score: 0");
scoreLabel.setAlignment(Pos.CENTER);
gridPane.add(scoreLabel, 0, 0, COLS, 1);
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
Rectangle block = new Rectangle(BLOCK_SIZE, BLOCK_SIZE);
block.setFill(Color.WHITE);
block.setStroke(Color.BLACK);
gridPane.add(block, col, row + 1);
}
}
// 初始化蛇
int initialRow = ROWS / 2;
int initialCol = COLS / 2;
for (int i = 0; i < INITIAL_SNAKE_LENGTH; i++) {
snake.add(new Position(initialRow, initialCol - i));
gridPane.add(createBlock(Color.GREEN), initialCol - i, initialRow + 1);
}
// 随机生成食物
generateFood();
// 处理按键事件
gridPane.setOnKeyPressed(event -> {
if (isGameOver) {
return;
}
KeyCode keyCode = event.getCode();
switch (keyCode) {
case UP:
if (direction != Direction.DOWN) {
direction = Direction.UP;
}
break;
case DOWN:
if (direction != Direction.UP) {
direction = Direction.DOWN;
}
break;
case LEFT:
if (direction != Direction.RIGHT) {
direction = Direction.LEFT;
}
break;
case RIGHT:
if (direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
break;
}
});
Scene scene = new Scene(gridPane, COLS * BLOCK_SIZE, (ROWS + 1) * BLOCK_SIZE);
primaryStage.setScene(scene);
primaryStage.setTitle("Snake Game");
primaryStage.show();
// 启动游戏循环
timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
if (isGameOver) {
timeline.stop();
return;
}
boolean isEaten = updateSnake();
if (isEaten) {
generateFood();
}
updateScore();
updateBlocks();
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
private Rectangle createBlock(Color color) {
Rectangle block = new Rectangle(BLOCK_SIZE, BLOCK_SIZE);
block.setFill(color);
block.setStroke(Color.BLACK);
return block;
}
private void generateFood() {
int row, col;
do {
row = random.nextInt(ROWS);
col = random.nextInt(COLS);
} while (isOccupiedBySnake(row, col));
food = new Position(row, col);
gridPane.add(createBlock(Color.RED), col, row + 1);
}
private boolean isOccupiedBySnake(int row, int col) {
for (Position position : snake) {
if (position.row == row && position.col == col) {
return true;
}
}
return false;
}
private boolean updateSnake() {
Position head = snake.getFirst();
switch (direction) {
case UP:
head = new Position(head.row - 1, head.col);
break;
case DOWN:
head = new Position(head.row + 1, head.col);
break;
case LEFT:
head = new Position(head.row, head.col - 1);
break;
case RIGHT:
head = new Position(head.row, head.col + 1);
break;
}
if (head.row < 0 || head.row >= ROWS || head.col < 0 || head.col >= COLS || isOccupiedBySnake(head.row, head.col)) {
isGameOver = true;
return false;
}
snake.addFirst(head);
if (head.row == food.row && head.col == food.col) {
score++;
return true;
} else {
snake.removeLast();
return false;
}
}
private void updateScore() {
scoreLabel.setText("Score: " + score);
}
private void updateBlocks() {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
Rectangle block = (Rectangle) gridPane.getChildren().get((row + 1) * COLS + col);
block.setFill(Color.WHITE);
}
}
for (Position position : snake) {
Rectangle block = (Rectangle) gridPane.getChildren().get((position.row + 1) * COLS + position.col);
block.setFill(Color.GREEN);
}
Rectangle foodBlock = (Rectangle) gridPane.getChildren().get((food.row + 1) * COLS + food.col);
foodBlock.setFill(Color.RED);
}
private static class Position {
int row;
int col;
Position(int row, int col) {
this.row = row;
this.col = col;
}
}
private enum Direction {
UP, DOWN, LEFT, RIGHT
}
public static void main(String[] args) {
launch(args);
}
}
```
在这个实现中,使用一个二维网格来表示游戏界面,其中每个格子大小为 `BLOCK_SIZE`,在网格中用颜色来表示蛇和食物。使用一个链表来表示蛇的身体,每次更新蛇的位置时,将蛇头添加到链表的头部,并根据移动方向删除链表的尾部。同时,需要处理蛇撞到墙壁或自己时游戏结束的情况,以及蛇吃到食物时的得分和生成新的食物。使用 JavaFX 的 Timeline 来启动游戏循环,定时更新蛇的位置和界面的显示。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)