对于我的第一个使用类的项目,我决定编写“生命游戏”。我创建了一个名为 cell 的类,它的工作是检查附近的细胞是否还活着(变量状态为真),然后决定下一帧细胞是否还活着。这是我的代码
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);
}
}