[英]Programming Conway's Game of Life
so im programming conways game of life in GUI form. 因此,即时通讯程序以GUI形式简化了生活游戏。 the output is not correct and i dont know why.
输出不正确,我不知道为什么。 this is the code that handles the "next generation".
这是处理“下一代”的代码。
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;
}
}
}
maybe im missing something, but im pretty sure this is right. 也许我错过了一些东西,但是我很确定这是正确的。 any suggestions?
有什么建议么?
This is the problem: 这就是问题:
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);
}
Your code only sets the color if the current tile is dead. 您的代码仅在当前图块已死的情况下设置颜色。 If it's alive, it will never become dead.
如果它还活着,它将永远不会死。 I would write this as:
我可以这样写:
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);
I'd also separate the logical data (a grid of boolean values) from the display part - the "business logic" here shouldn't know anything about colors. 我还要从显示部分分离逻辑数据(布尔值的网格)-这里的“业务逻辑”应该对颜色一无所知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.