所以即时编程以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;
}
}
}
也许我错过了什么,但我很确定这是对的。有什么建议吗?
答案 0 :(得分: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);
我还将显示部分中的逻辑数据(布尔值网格)分开 - 这里的“业务逻辑”不应该知道任何颜色。