因此,即时通讯程序以GUI形式简化了生活游戏。输出不正确,我不知道为什么。这是处理“下一代”的代码。

for(int i=0; i < ROW; i++) {
    for(int j=0; j < COL; j++) {
        if(i > 0 && i < ROW-1 && j > 0 && j < COL -1) {
            if(grid.getButton(i-1, j-1).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i-1, j).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i-1, j+1).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i, j-1).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i, j+1).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i+1, j-1).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i+1, j).getBackground() == Color.BLUE) liveNeighbor++;
            if(grid.getButton(i+1, j+1).getBackground() == Color.BLUE) liveNeighbor++;

            if(grid.getButton(i, j).getBackground() == Color.WHITE) {
                if(liveNeighbor == 3)
                    newGrid.getButton(i, j).setBackground(Color.BLUE);
                } else {
                    if(liveNeighbor > 3 || liveNeighbor < 2)
                        newGrid.getButton(i, j).setBackground(Color.WHITE);
            }
            liveNeighbor=0;
        }
    }
}


也许我错过了一些东西,但是我很确定这是正确的。有什么建议?

最佳答案

这就是问题:

if(grid.getButton(i, j).getBackground() == Color.WHITE) {
    if(liveNeighbor == 3)
        newGrid.getButton(i, j).setBackground(Color.BLUE);
    } else {
        if(liveNeighbor > 3 || liveNeighbor < 2)
            newGrid.getButton(i, j).setBackground(Color.WHITE);
}


您的代码仅在当前图块已死的情况下设置颜色。如果它还活着,它将永远不会死。我可以这样写:

boolean currentlyAlive = grid.getButton(i, j).getBackground() == Color.BLUE;
boolean aliveNextStep = (liveNeighbour == 3) ||
                        (currentlyAlive && liveNeighbor == 2);
newGrid.getButton(i, j).setBackground(aliveNextStep ? Color.BLUE : Color.WHITE);


我还将显示部分的逻辑数据(布尔值的网格)分开-这里的“业务逻辑”对颜色一无所知。

关于java - 编程康威的生活游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12721421/

10-10 07:53