I’m not sure if I’m going about this the right way, I’ve created my code which works for all “still life” cell arrangements, ie. Beehive, Block, Boat and Loaf. However, for arrangements that are supposed of be manipulated and involve the death and birth of cells I have problems.
Right now I’m creating cells first, and then killing off anyone’s which fall into the rules (If the surrounding neighbours is a total less than or equal to one, equal to or greater than four).
What I have going now, doesn’t work how it’s supposed to. I’ll include some images underneath my code:
public class Untitled {
public static void main(String[] params){
Life life = new Life();
String[][] list = life.readGame();
life.print(list);
System.out.println();
for(int i = 1; i <= 5; i++){
list = life.run(list);
life.print(list);
System.out.println();
}
}
}
class Life {
public String[][] readGame(){
String[][] array = {
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"}
};
return array;
}
public void print(String[][] array){
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
System.out.print(array[x][y]);
}
System.out.println();
}
}
public String[][] run(String[][] array){
populateCells(array);
System.out.println("Populated:\n");
print(array);
killCells(array);
System.out.println("Killed:\n");
print(array);
return array;
}
public int amountOfNeighbors(String[][] array, int x, int y){
int amount = 0;
for(int x1 = -1; x1 <= 1; x1++){
if(x + x1 >= 0 && x + x1 < array.length){
for(int y1 = -1; y1 <= 1; y1++){
if(y + y1 >= 0 && y + y1 < array[x1 + x].length){
if(!(x1 == 0 && y1 == 0) && !array[x1 + x][y1 + y].equals("-")){
amount++;
}
}
}
}
}
return amount;
}
public void populateCells(String[][] array){
int neighbours;
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
neighbours = amountOfNeighbors(array,x,y);
if(neighbours == 3){
array[x][y] = "x";
}
}
}
}
public void killCells(String[][] array){
int neighbours;
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
neighbours = amountOfNeighbors(array,x,y);
if(neighbours <= 1 || neighbours >= 4){
array[x][y] = "-";
}
}
}
}
}
As for the images, here’s a simple blinker structure and what happens after population and deletion of cells:



Each time you call
run()you need to create a copy of the original board, and use that copy to check the state of each cell as you modify the cells in the original board.Otherwise, each time you update a cell you will be inadvertently changing the states of the cells around it.
This is a fairly common bug in simulations that involve game boards like Game of Life – so now you know to watch out for it 🙂