The Game of Life

To anyone that has watched The Coding Train’s Video about it or just knows the Game of Life, can you take a look at my script in over here and tell me if I did anything wrong? I made it just for fun, and noticed that it looked kind of weird, and that the shapes at the end are looking different in The Coding Train’s Video as I checked afterwards. I don’t know, I can be mistaking, but I don’t feel very sure about this :sweat_smile:

int scale = 10;
boolean stop = true;
Cell[][] cells;

void setup() {
  size(600, 400);
  cells = new Cell[width/scale][height/scale];
  for (int x = 0; x < width/scale; x++) {
    for (int y = 0; y < height/scale; y++) {
      cells[x][y] = new Cell(0);
      stroke(0);
      fill(cells[x][y].colCheck());
      rect(x*scale, y*scale, scale, scale);
    }
  }
  frameRate(10);
}

void draw() {
  if (mousePressed) {
    int i = round(mouseX/scale), j = round(mouseY/scale);
    if (cells[i][j].col == 0) {
      cells[i][j].col = 1;
    } else {
      cells[i][j].col = 0;
    }
  }
  Cell[][] nCells = new Cell[width/scale][height/scale];
  for (int x = 0; x < width/scale; x++) {
    for (int y = 0; y < height/scale; y++) {
      if (stop == false) {
        nCells[x][y] = new Cell(1);
        nCells[x][y].col = cells[x][y].aliveCheck(x, y);
      }
      stroke(0);
      fill(cells[x][y].colCheck());
      rect(x*scale, y*scale, scale, scale);
    }
  }

  if (stop == false) {
    cells = nCells;
  }
}

void keyPressed() {
  stop = !stop;
}

class Cell {
  int col;

  Cell(int c) {
    if (c == 0) {
      col = round(random(0,1));
    }
  }

  int aliveCheck(int x, int y) {
    int alive = 0;

    for (int i = -1; i < 2; i++) {
      for (int j = -1; j < 2; j++) {
        int cols = (width/scale), rows = (height/scale);
        PVector pos = new PVector((x+i+cols)%cols,(y+j+rows)%rows);
        
        alive += cells[int(pos.x)][int(pos.y)].col;
      }
    }
    
    if (col == 0 && alive == 3) {
      return 1;
    } else if (col == 1 && (alive < 2 || alive > 3)) {
      return 0;
    } else {
      return col;
    }
  }

  color colCheck() {
    color temp = color(0);
    if (col == 1) {
      temp = color(255);
    }
    return temp;
  }
}

1 Like

I think you may have forgotten when doing the aliveCheck() to not check the current cell or subtract it afterwards. Adding alive -= col; right after the for loops in aliveCheck() should do the trick. Otherwise the code looks good!

Right! I have added that in one point in Time, but back when I did, it didnt make much difference… But since I’ve added a lot by now, I may also try it again! Thanks for the help, and feel free to notice me when you find another failure.

1 Like