For my first project using classes I decided to write "The game of Life". I made a class called cell and its work is to check the nearby cells whether they are alive(variable state is true) and than decide whether the cell will be alive next frame or not. Here is my code
public cell Cell[][] = new cell[10][10];
public boolean state[][] = new boolean[10][10];
void setup(){
size(200,200);
for(int x = 0;x > 10;x++){
for(int y = 0; y > 10;y++){
state[x][y] = false;
}
}
state[1][1] = true;
state[1][2] = true;
state[2][1] = true;
state[2][2] = true;
for(int x = 0;x > 10;x++){
for(int y = 0; y > 10;y++){
Cell[x][y] = new cell(x,y,state[x][y]);
}
}
}
void draw(){
for(int x = 0;x > 10;x++){
for(int y = 0; y > 10;y++){
Cell[x][y].update();
}
}
}
class cell{
boolean state; int ngbs,posx,posy;
cell(int gridX,int gridY,boolean State){
posx = gridX;
posy = gridY;
state = State;
}
void update(){
if(Cell[posx-1][posy].state == true){ngbs++;}
if(Cell[posx+1][posy].state == true){ngbs++;}
if(Cell[posx][posy-1].state == true){ngbs++;}
if(Cell[posx][posy+1].state == true){ngbs++;}
if(Cell[posx+1][posy-1].state == true){ngbs++;}
if(Cell[posx+1][posy+1].state == true){ngbs++;}
if(Cell[posx-1][posy+1].state == true){ngbs++;}
if(Cell[posx-1][posy-1].state == true){ngbs++;}
if(ngbs == 3){state = true;}
if((ngbs != 2) && (ngbs != 3)){state = false;fill(0);}
if(state){fill(255);}else{fill(0);}
rect(posx*10,posy*10,10,10);
}
}