请用javafx写一段贪吃蛇代码,要求能存档并记录最高分
时间: 2023-08-10 19:04:54 浏览: 115
以下是基于JavaFX的贪吃蛇代码,包括存档和最高分记录功能:
```java
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.*;
import java.util.*;
public class SnakeGame extends Application {
// 游戏界面大小
private static final int WIDTH = 640;
private static final int HEIGHT = 480;
// 贪吃蛇格子大小
private static final int CELL_SIZE = 10;
// 游戏画布
private Canvas canvas;
private GraphicsContext gc;
// 贪吃蛇
private List<Cell> snake;
private Cell head;
private Cell food;
// 移动方向
private Direction direction = Direction.RIGHT;
// 游戏状态
private boolean gameOver = false;
// 最高分
private int highScore;
@Override
public void start(Stage primaryStage) {
// 加载最高分
loadHighScore();
// 创建游戏界面
BorderPane root = new BorderPane();
HBox topBox = new HBox();
topBox.setAlignment(Pos.CENTER);
topBox.setSpacing(10);
Label scoreLabel = new Label("Score: 0");
Label highScoreLabel = new Label("High Score: " + highScore);
topBox.getChildren().addAll(scoreLabel, highScoreLabel);
root.setTop(topBox);
// 创建游戏画布
canvas = new Canvas(WIDTH, HEIGHT);
gc = canvas.getGraphicsContext2D();
root.setCenter(canvas);
// 初始化贪吃蛇
initSnake();
// 监听键盘事件
canvas.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.UP && direction != Direction.DOWN) {
direction = Direction.UP;
} else if (event.getCode() == KeyCode.DOWN && direction != Direction.UP) {
direction = Direction.DOWN;
} else if (event.getCode() == KeyCode.LEFT && direction != Direction.RIGHT) {
direction = Direction.LEFT;
} else if (event.getCode() == KeyCode.RIGHT && direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
});
// 创建游戏循环
AnimationTimer timer = new AnimationTimer() {
private long lastTime = 0;
@Override
public void handle(long now) {
if (lastTime == 0) {
lastTime = now;
return;
}
if (gameOver) {
stop();
gameOver();
return;
}
if (now - lastTime < 1000000000 / 10) {
return;
}
lastTime = now;
moveSnake();
drawSnake();
checkCollision();
checkFood();
scoreLabel.setText("Score: " + (snake.size() - 1));
}
};
// 创建开始按钮
ButtonType newGameButtonType = new ButtonType("New Game");
ButtonType continueButtonType = new ButtonType("Continue");
Alert alert = new Alert(Alert.AlertType.NONE, "Choose an option:", newGameButtonType, continueButtonType);
alert.setTitle("Snake Game");
alert.setHeaderText("Welcome to Snake Game!");
alert.showAndWait();
if (alert.getResult() == newGameButtonType) {
newGame();
} else {
loadGame();
}
// 显示游戏界面
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Snake Game");
primaryStage.setResizable(false);
primaryStage.show();
// 启动游戏循环
timer.start();
}
// 初始化贪吃蛇
private void initSnake() {
snake = new ArrayList<>();
head = new Cell(WIDTH / 2, HEIGHT / 2);
snake.add(head);
for (int i = 1; i <= 3; i++) {
snake.add(new Cell(head.getX() - i * CELL_SIZE, head.getY()));
}
createFood();
}
// 移动贪吃蛇
private void moveSnake() {
Cell tail = snake.remove(snake.size() - 1);
tail.setX(head.getX() + direction.getX() * CELL_SIZE);
tail.setY(head.getY() + direction.getY() * CELL_SIZE);
snake.add(0, tail);
head = tail;
}
// 绘制贪吃蛇
private void drawSnake() {
gc.clearRect(0, 0, WIDTH, HEIGHT);
gc.setFill(Color.GREEN);
for (Cell cell : snake) {
gc.fillRect(cell.getX(), cell.getY(), CELL_SIZE, CELL_SIZE);
}
gc.setFill(Color.RED);
gc.fillRect(food.getX(), food.getY(), CELL_SIZE, CELL_SIZE);
}
// 检查碰撞
private void checkCollision() {
if (head.getX() < 0 || head.getX() >= WIDTH || head.getY() < 0 || head.getY() >= HEIGHT) {
gameOver = true;
}
for (int i = 1; i < snake.size(); i++) {
if (head.getX() == snake.get(i).getX() && head.getY() == snake.get(i).getY()) {
gameOver = true;
break;
}
}
}
// 检查食物
private void checkFood() {
if (head.getX() == food.getX() && head.getY() == food.getY()) {
snake.add(new Cell(food.getX(), food.getY()));
createFood();
}
}
// 创建食物
private void createFood() {
Random random = new Random();
int x = random.nextInt(WIDTH / CELL_SIZE) * CELL_SIZE;
int y = random.nextInt(HEIGHT / CELL_SIZE) * CELL_SIZE;
for (Cell cell : snake) {
if (cell.getX() == x && cell.getY() == y) {
createFood();
return;
}
}
food = new Cell(x, y);
}
// 保存游戏
private void saveGame() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("snake.dat"))) {
out.writeObject(snake);
out.writeObject(head);
out.writeObject(food);
out.writeObject(direction);
out.writeInt(highScore);
} catch (IOException e) {
e.printStackTrace();
}
}
// 加载游戏
private void loadGame() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("snake.dat"))) {
snake = (List<Cell>) in.readObject();
head = (Cell) in.readObject();
food = (Cell) in.readObject();
direction = (Direction) in.readObject();
highScore = in.readInt();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
newGame();
}
}
// 新游戏
private void newGame() {
initSnake();
highScore = 0;
saveHighScore();
}
// 游戏结束
private void gameOver() {
if (snake.size() - 1 > highScore) {
highScore = snake.size() - 1;
saveHighScore();
}
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Game Over");
alert.setHeaderText("Game Over");
alert.setContentText("Your score is " + (snake.size() - 1));
alert.showAndWait();
newGame();
}
// 保存最高分
private void saveHighScore() {
try (PrintWriter out = new PrintWriter(new FileWriter("highscore.txt"))) {
out.println(highScore);
} catch (IOException e) {
e.printStackTrace();
}
}
// 加载最高分
private void loadHighScore() {
try (Scanner in = new Scanner(new FileInputStream("highscore.txt"))) {
highScore = in.nextInt();
} catch (IOException e) {
e.printStackTrace();
}
}
// 格子
private static class Cell implements Serializable {
private int x;
private int y;
public Cell(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
// 方向
private enum Direction implements Serializable {
UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0);
private int x;
private int y;
Direction(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public static void main(String[] args) {
launch(args);
}
}
```
阅读全文