I have the following logic code for my Game of Life application in Java. I have the problem that the rules do not act like the default Conway's Game of Life rules. I have read up on them on Wikipedia, and they are the following;
I have attempted to duplicate these rules in the following code, but it acts unlike the normal Conway' Game of Life;
int surroundingLife = 0;
if (lifeMap[cX+1][cY]) { //Right
surroundingLife++;
}
if (lifeMap[cX-1][cY]) { // Left
surroundingLife++;
}
if (lifeMap[cX][cY+1]) { // Above
surroundingLife++;
}
if (lifeMap[cX][cY-1]) { // Below
surroundingLife++;
}
if (lifeMap[cX-1][cY-1]) { // Bottom left
surroundingLife++;
}
if (lifeMap[cX+1][cY+1]) { // Top Right
surroundingLife++;
}
if (lifeMap[cX-1][cY+1]) { // Some other corner (I don't know which one)
surroundingLife++;
}
if (lifeMap[cX+1][cY-1]) { // Yet another corner (I don't know which one)
surroundingLife++;
}
if (running) {
// Logic for life
if (surroundingLife < 2 && lifeMap[cX][cY]) {// Rule 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
lifeMap[cX][cY] = false;
} else if (surroundingLife == 2 && lifeMap[cX][cY]) { // Rule 2. Any live cell with two or three live neighbours lives on to the next generation.
lifeMap[cX][cY] = true;
} else if (surroundingLife == 3 && lifeMap[cX][cY]) { // Rule 3. Same as above
lifeMap[cX][cY] = true;
} else if (surroundingLife > 3 && lifeMap[cX][cY]) { // Rule 4. Any live cell with more than three live neighbours dies, as if by overcrowding.
lifeMap[cX][cY] = false;
} else if (surroundingLife == 3 && !lifeMap[cX][cY]) { // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
lifeMap[cX][cY] = true;
}
}
This is how it looks after running a couple of generations;
It reminds me of the 'maze' ruleset, which is odd.
I don't believe there is a fault with my surroundingLife calculator, as it returns 8 when entities have 8 others surrounding them. Is the problem due to me looping through Y then X?
The problem is that you are modifying the grid in the same pass as you are evaluating what needs to change. Each time you change a cell, you are affecting the outcome of all future tests in the same pass that border that cell.
You need to make a copy of the grid. Always test (read) from that copy, and apply changes (write) to the original.