0

所以我以 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;
        }
    }
}

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

4

1 回答 1

3

这就是问题:

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);

我还将逻辑数据(布尔值网格)与显示部分分开——这里的“业务逻辑”不应该对颜色有任何了解。

于 2012-10-04T06:29:04.497 回答