创建“生命游戏”;在Java中具有不同的类 [英] Creating "Game of Life" in Java with different classes

查看:80
本文介绍了创建“生命游戏”;在Java中具有不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用不同的类别来创建生命游戏,但我遇到了麻烦。
我想检查是否有一个活着的人在带有索引行的列上。

I am trying to create the Game of Life with different classes, and I have gotten into trouble. I want to check if there's an alive individual in the box with index row, col.

到目前为止,这是我的代码:

Here's my code so far:

public class LifeBoard {

    private int rows;
    private int cols;
    private int generation;


    /**Creates a playing field with rows as rows and cols as columns. 
    The counter for generations is 1.*/
    public LifeBoard(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.generation = 1;
    }

    /**Checks if there's a living individual in the box row, col*/
    public boolean get(int row, int col) {
        if(this.board[row][col] == null){
            return false;
        } else {
            return true;
        }
    }
}

我不知道什么去做。我该如何检查?

I don't know what to do. How do I check this?

推荐答案

这取决于您对游戏的建模方式。这段代码假定 boolean [] [] 网格。

It depends on how you've modeled the game. This code assumes a boolean[][] grid.

一个单元格周围最多有8个单元格。由于我们必须检查网格的边界,因此每个单元周围可能没有8个单元。

There are up to 8 cells that surround a cell. Since we have to check for the boundaries of the grid, there might not be 8 cells surrounding every cell.

public synchronized void cycleGrid() {
    this.generationCount++;

    for (int i = 0; i < GRID_WIDTH; i++) {
        for (int j = 0; j < GRID_WIDTH; j++) {
            int count = countCells(i, j);
            if (count == 3) grid[i][j] = true;
            if (grid[i][j] && count < 2) grid[i][j] = false;
            if (grid[i][j] && count > 3) grid[i][j] = false;
        }
    }
}

private int countCells(int i, int j) {
    int count = 0;

    int iminus = i - 1;
    int jminus = j - 1;
    int iplus = i + 1;
    int jplus = j + 1;

    if (iminus >= 0) {
        if (jminus >= 0) {
            if (grid[iminus][jminus])   count++;
        }

        if (grid[iminus][j])            count++;

        if (jplus < GRID_WIDTH) {
            if (grid[iminus][jplus])    count++;
        }
    }

    if (jminus >= 0) {
        if (grid[i][jminus])            count++;
    }

    if (jplus < GRID_WIDTH) {
        if (grid[i][jplus])             count++;
    }

    if (iplus < GRID_WIDTH) {
        if (jminus >= 0) {
            if (grid[iplus][jminus])    count++;
        }

        if (grid[iplus][j])             count++;

        if (jplus < GRID_WIDTH) {
            if (grid[iplus][jplus])     count++;
        }
    }

    return count;
}

看看我的文章,约翰·康威(John Conway)的Java Swing人生游戏,以获取更多提示。

Take a look at my article, John Conway’s Game of Life in Java Swing, for more hints.

这篇关于创建“生命游戏”;在Java中具有不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆