因此,代码正在编译并完美运行。但是,通常,康威的生命游戏会在一段时间后稳定下来,而这段代码会无限期地运行,而不会出现死分支,如果有人能帮助我找出原因,我会很高兴。
int[][] world;
int SCALE_FACTOR = 4;
float DENSITY = 0.1;
void setup() {
size(500,500);
world = new int[width/SCALE_FACTOR][height/SCALE_FACTOR];
for(int i = 0; i < width/SCALE_FACTOR; i++) {
for (int j = 0; j < height/SCALE_FACTOR; j++) {
int r = (int)random(100);
world[i][j] = r % (int)(1/DENSITY) == 0 ? 1 : 0;
}
}
frameRate(1);
stroke(0, 255, 0);
}
void draw() {
scale(SCALE_FACTOR);
background(0);
for(int i = 0; i < width/SCALE_FACTOR; i++) {
for (int j = 0; j < height/SCALE_FACTOR; j++) {
if (world[i][j] == 1) point(i, j);
}
}
lifeCycle();
}
void lifeCycle() {
int[][] newworld = new int[width/SCALE_FACTOR][height/SCALE_FACTOR];
for(int i = 0; i < width/SCALE_FACTOR; i++) {
for (int j = 0; j < width/SCALE_FACTOR; j++) {
if (world[i][j] == 1) {
if (neighbours(i, j) == 3) {
newworld[i][j] = 1;
} else {
newworld[i][j] = 0;
}
} else {
if (neighbours(i, j) == 2 || neighbours(i, j) == 3) {
newworld[i][j] = 1;
} else {
newworld[i][j] = 0;
}
}
}
}
for (int i = 0; i < width/SCALE_FACTOR; i++) {
for (int j = 0; j < height/SCALE_FACTOR; j++) {
world[i][j] = newworld[i][j];
}
}
}
int neighbours(int x, int y) {
int px = (x == width/SCALE_FACTOR - 1) ? 0 : (x+1);
int py = (y == height/SCALE_FACTOR - 1) ? 0 : (y+1);
int mx = (x == 0) ? (width/SCALE_FACTOR - 1) : (x-1);
int my = (y == 0) ? (height/SCALE_FACTOR - 1) : (y-1);
return world[mx][my] + world[mx][y] + world[mx][py]
+ world[x][my] + world[x][py]
+ world[px][my] + world[px][y] + world[px][py];
}