首页 > 编程语言 >生命游戏串行代码实现(Java)

生命游戏串行代码实现(Java)

时间:2024-10-20 19:20:13浏览次数:3  
标签:Java 游戏 int private GRID 细胞 串行 new SIZE

目录

生命游戏介绍

一、效果展示

1.初始界面

2.启动游戏

二、代码实现

三、代码解释

1.常量设置

2.图形化

3.计算“生死”情况与统计邻居细胞数量

结语


生命游戏介绍

        生命游戏,是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。

        一个方格游戏棋盘上,每个方格中都可放置一个生命细胞,每个生命细胞只有两种状态:“生”或“死”(状态往往随机决定)。然后细胞根据某些规则,计算出下一代每个细胞的状态,并且不停迭代。

        在游戏的进行中,杂乱无序的细胞会逐渐演化出各种精致、有形的结构;这些结构往往有很好的对称性,而且每一代都在变化形状。一些形状已经锁定,不会逐代变化。有时,一些已经成形的结构会因为一些无序细胞的“入侵”而被破坏。但是形状和秩序经常能从杂乱中产生出来。

        现设定其规则是:

  • 如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生(即该细胞若原先为死,则转为生,若原先为生,则保持不变) 。
  •  如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;
  •  在其它情况下,该细胞为死(即该细胞若原先为生,则转为死,若原先为死,则保持不变)

下面就此规则,使用java来编写100*100的棋盘,并使用简单的JavaFX来实现简易图形化来观察游戏的迭代过程。


一、效果展示

1.初始界面

          100*100的棋盘上随机生成“生”和“死”细胞(黑为生,白为死)。底部有“运行”和“暂停”按钮。

2.启动游戏

二、代码实现

package com.itheima.gameOfLife;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.util.Random;

public class GameOfLife extends Application {
    private static final int GRID_SIZE = 100; 
    private static final int CELL_SIZE = 10; // 每个细胞的像素大小
    private static final int GENERATIONS = 1000; // 演化代数
    private int[][] grid = new int[GRID_SIZE][GRID_SIZE]; // 当前代棋盘
    private int[][] nextGrid = new int[GRID_SIZE][GRID_SIZE]; // 下一代棋盘
    private Pane pane = new Pane();
    private AnimationTimer timer;
    private boolean isRunning = false; // 运行状态标志

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        initializeGrid(); // 随机初始化棋盘

        // 创建JavaFX界面
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, GRID_SIZE * CELL_SIZE, GRID_SIZE * CELL_SIZE + 50);
        primaryStage.setTitle("生命游戏");
        primaryStage.setScene(scene);

        // 创建按钮,便于停止观察当前棋盘状态 
        Button startButton = new Button("运行");
        Button pauseButton = new Button("暂停");

        startButton.setOnAction(e -> startGame());
        pauseButton.setOnAction(e -> pauseGame());

        // 设置按钮位置
        root.setBottom(new Pane(startButton, pauseButton));
        Pane buttonPane = new Pane();
        buttonPane.getChildren().addAll(startButton, pauseButton);
        buttonPane.setPrefSize(GRID_SIZE * CELL_SIZE, 50);
        buttonPane.setLayoutY(GRID_SIZE * CELL_SIZE);
        startButton.setLayoutX(20);
        pauseButton.setLayoutX(80);
        root.setCenter(pane);
        root.setBottom(buttonPane);

        primaryStage.show();

        drawGrid(); // 绘制初始棋盘

        // 使用AnimationTimer更新棋盘
        timer = new AnimationTimer() {
            private int generationCount = 0;

            @Override
            public void handle(long now) {
                if (isRunning && generationCount < GENERATIONS) {
                    runGeneration(); // 运行一代
                    drawGrid(); // 更新绘制
                    generationCount++;
                } else if (generationCount >= GENERATIONS) {
                    stop(); // 结束动画
                }
            }
        };
    }

    // 随机初始化棋盘
    private void initializeGrid() {
        Random random = new Random();
        for (int i = 0; i < GRID_SIZE; i++) {
            for (int j = 0; j < GRID_SIZE; j++) {
                grid[i][j] = random.nextInt(2); // 随机生成0或1
            }
        }
    }

    // 启动
    private void startGame() {
        if (!isRunning) {
            isRunning = true; // 设置为运行状态
            timer.start(); // 启动计时器
        }
    }

    // 暂停
    private void pauseGame() {
        isRunning = false; // 设置为暂停状态
        timer.stop(); // 停止计时器
    }

    // 运行一代
    private void runGeneration() {
        for (int i = 0; i < GRID_SIZE; i++) {
            for (int j = 0; j < GRID_SIZE; j++) {
                int liveNeighbors = countLiveNeighbors(i, j);
                if (grid[i][j] == 1) { // 当前细胞是活的
                    nextGrid[i][j] = (liveNeighbors == 2 || liveNeighbors == 3) ? 1 : 0;
                } else { // 当前细胞是死的
                    nextGrid[i][j] = (liveNeighbors == 3) ? 1 : 0;
                }
            }
        }
        copyNextGridToCurrent();
    }

    // 计算邻居活细胞数量
    private int countLiveNeighbors(int row, int col) {
        int liveNeighbors = 0;
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) continue; // 跳过自身
                int newRow = (row + i + GRID_SIZE) % GRID_SIZE; // 考虑边界
                int newCol = (col + j + GRID_SIZE) % GRID_SIZE;
                liveNeighbors += grid[newRow][newCol];
            }
        }
        return liveNeighbors;
    }

    // 将nextGrid复制到grid
    private void copyNextGridToCurrent() {
        for (int i = 0; i < GRID_SIZE; i++) {
            System.arraycopy(nextGrid[i], 0, grid[i], 0, GRID_SIZE);
        }
    }

    // 绘制当前棋盘状态
    private void drawGrid() {
        pane.getChildren().clear(); // 清除旧的图形
        for (int i = 0; i < GRID_SIZE; i++) {
            for (int j = 0; j < GRID_SIZE; j++) {
                Rectangle cell = new Rectangle(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
                cell.setFill(grid[i][j] == 1 ? Color.BLACK : Color.WHITE); // 黑色表示活细胞,白色表示死细胞
                cell.setStroke(Color.GRAY); //细胞之间的边框
                pane.getChildren().add(cell); // 将细胞添加到面板
            }
        }
    }
}

三、代码解释

1.常量设置

private static final int GRID_SIZE = 100; 
private static final int CELL_SIZE = 10; // 每个细胞的像素大小
private static final int GENERATIONS = 1000; // 演化代数
private int[][] grid = new int[GRID_SIZE][GRID_SIZE]; // 当前代棋盘
private int[][] nextGrid = new int[GRID_SIZE][GRID_SIZE]; // 下一代棋盘
private Pane pane = new Pane();
private AnimationTimer timer;
private boolean isRunning = false; // 运行状态标志

GRID_SIZE: 定义了棋盘的大小,当前设置为 100。即棋盘是一个 100 x 100 的格子。

CELL_SIZE: 定义了每个细胞的像素大小,当前设置为 10。因此,每个细胞在界面上将显示为一个 10 x 10 像素的正方形。

棋盘总大小: 因此,整个棋盘的实际像素大小为:

  • 宽度: GRID_SIZE * CELL_SIZE = 100 * 10 = 1000 像素
  • 高度: GRID_SIZE * CELL_SIZE = 100 * 10 = 1000 像素

2.图形化

// 创建JavaFX界面
    BorderPane root = new BorderPane();
    Scene scene = new Scene(root, GRID_SIZE * CELL_SIZE, GRID_SIZE * CELL_SIZE + 50);
    primaryStage.setTitle("生命游戏");
    primaryStage.setScene(scene);

    // 创建按钮
    Button startButton = new Button("运行");
    Button pauseButton = new Button("暂停");

    startButton.setOnAction(e -> startGame());
    pauseButton.setOnAction(e -> pauseGame());

    // 将按钮放置在界面底部
    root.setBottom(new Pane(startButton, pauseButton));
    Pane buttonPane = new Pane();
    buttonPane.getChildren().addAll(startButton, pauseButton);
    buttonPane.setPrefSize(GRID_SIZE * CELL_SIZE, 50);
    buttonPane.setLayoutY(GRID_SIZE * CELL_SIZE);
    startButton.setLayoutX(20);
    pauseButton.setLayoutX(80);
    root.setCenter(pane);
    root.setBottom(buttonPane);

    primaryStage.show();

    drawGrid(); // 绘制初始棋盘

    // 使用AnimationTimer更新棋盘
    timer = new AnimationTimer() {
        private int generationCount = 0;

        @Override
        public void handle(long now) {
            if (isRunning && generationCount < GENERATIONS) {
                runGeneration(); // 运行一代
                drawGrid(); // 更新绘制
                generationCount++;
            } else if (generationCount >= GENERATIONS) {
                stop(); // 结束动画
            }
        }
    };
}

上面这段代码是JavaFX的核心部分,创建棋盘界面和处理游戏逻辑。部分解释已经在代码中注释出来。

在“使用AnimationTimer更新棋盘”这部分中,创建了一个 AnimationTimer 对象,并重写其handle方法,用于定时更新棋盘状态。

3.计算“生死”情况与统计邻居细胞数量

//根据规则判断生死
private void runGeneration() {
    for (int i = 0; i < GRID_SIZE; i++) {
        for (int j = 0; j < GRID_SIZE; j++) {
            int liveNeighbors = countLiveNeighbors(i, j);
            if (grid[i][j] == 1) { // 当前细胞是活的
                nextGrid[i][j] = (liveNeighbors == 2 || liveNeighbors == 3) ? 1 : 0;
            } else { // 当前细胞是死的
                nextGrid[i][j] = (liveNeighbors == 3) ? 1 : 0;
            }
        }
    }
    copyNextGridToCurrent();
}

// 计算邻居活细胞数量
private int countLiveNeighbors(int row, int col) {
    int liveNeighbors = 0;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            if (i == 0 && j == 0) continue; // 跳过自身
            int newRow = (row + i + GRID_SIZE) % GRID_SIZE; // 考虑边界
            int newCol = (col + j + GRID_SIZE) % GRID_SIZE;
            liveNeighbors += grid[newRow][newCol];
        }
    }
    return liveNeighbors;
}

比较简单的代码,使用最基本的双重循环来遍历整个棋盘的细胞,得到其邻居的数量用于判断下一次迭代的状态。

在“计算邻居活细胞数量”中,用取模运算来处理边界情况,使得棋盘具有环绕效果。例如,如果当前细胞在第一行,且要检查上方的细胞,则通过取模确保索引循环回到棋盘的底部。


四、结语

以上主要浅显的实现了生命游戏的基本逻辑,并用简单的图形可视化来创建一个直观的界面来观察细胞的迭代,更直接的观察到由简单规则产生的复杂动态行为。在这个串行的生命游戏基础上,后续可以改写为多线程的生命游戏,并通过一些方法来比对串行与并行代码的效率。

标签:Java,游戏,int,private,GRID,细胞,串行,new,SIZE
From: https://blog.csdn.net/chashangcha/article/details/143085974

相关文章