简体   繁体   English

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

[英]Conway's Game of Life (constructor and updating the game)

I've been given an assignment dealing with Conway's Game of Life. 我得到了一份关于康威生命游戏的作业。

I'm having trouble with my CellGrid method and simulateStep method. 我的CellGrid方法和simulateStep方法有问题。 The probability for being alive doesn't seem to be working and in simulateStep, I'm getting NullPointerException errors. 活着的概率似乎不起作用,在simulateStep中,我收到了NullPointerException错误。

Here is my code: 这是我的代码:

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 method: setAlive方法:

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

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

Thank you for all your help! 谢谢你的帮助!

You should change Cell c = new Cell(); 你应该改变Cell c = new Cell(); to cells[i][j] = new Cell(); to cells[i][j] = new Cell(); in the constructor. 在构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM