java - 康威的生命游戏(构造器和更新游戏)

标签 java nullpointerexception conways-game-of-life

我接到了一项处理康威生命游戏的任务。

我在使用 CellGrid 方法和 simulateStep 方法时遇到问题。活着的概率似乎不起作用,在 simulateStep 中,我遇到了 NullPointerException 错误。

这是我的代码:

public class CellGrid
{
    private Cell[][] cells;


/**
 * This populates the grid with cells that will be
 * either living or dead (with this probability given by lifeChance)
 * 
 * @param size - grid size
 * @param lifeChance - probability of each cell starting out alive 
 */
public CellGrid(int size, double lifeChance)
{
    cells = new Cell[size][size];
    Random r = new Random();

    for (int i = 0; i < cells.length; i++)
    {
        for (int j = 0; j < cells.length; j++)
        {
            Cell c = new Cell();
            double nextVal = r.nextDouble();
            if (nextVal < lifeChance)
            {
                c.setAlive(false);
            }
            else
            {
                c.setAlive(true);
            }
        }
    }
}

/**
 * Iterates the simulation by one step (according to Game of Life rules)
 */
public void simulateStep()
{
    for (int y = 0; y < cells.length; y++)
    {
        for (int x = 0; x < cells.length; x++)
        {
            boolean living = cells[y][x].isAlive();
            int count = countNeighbours(y, x);
            boolean result = false;

            if (living && count <= 2)
            {
                result = false;
            }
            if (living && (count == 3 || count == 4))
            {
                result = true;
            }
            if (living && count == 5)
            {
                result = false;
            }
            if (living == true && count > 5)
            {
                result = true;
            }
            if (living == false && count > 5)
            {
                result = true;
            }

            result = cells[y][x].isAlive();
        }
    }
}

setAlive 方法:

public void setAlive(boolean alive)
{
    if (isAlive()== true)
    {
        this.alive = false;
    }

    if (isAlive() == false)
    {
        this.alive = true;
    }
}

谢谢大家的帮助!

最佳答案

您应该在构造函数中将 Cell c = new Cell(); 更改为 cells[i][j] = new Cell();

关于java - 康威的生命游戏(构造器和更新游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125446/

相关文章:

java - 需要 Spring 版本# - 只有 spring.jar 文件

java - Ubuntu 12.04 上带有 openjdk 6 的 NullPointerException

Java 对象中的空指针异常错误

java - 康威的生命游戏,每个细胞都是一条线

javascript - 康威的生命游戏 - 算法不正确?

java - 如何访问JWT Token然后处理请求?

java - ImageView 应该位于所有内容之上,例如 float 操作按钮

java - Jackson fastxml ObjectMapper defaultPrettyPrintingWriter() 方法未定义需要替换

java - 折线在模拟器上崩溃

javascript - 是否使用闭包,John Conway 的 Game of Life