Search code examples
javascriptconways-game-of-life

Conway's Game of Life Rules


I'm aware this is kind of vague but I've been trying to implement the rules for Conway's Game of Life in JS but the result I get back is a mess (isn't a correct Conway's Game of Life frame). Can anyone tell me what's wrong with my implementation of the rules?

      // Update state of selected cell
      if ((neighbours < 2) && (cells[y][x].colour == "black")) {
        // "Any live cell with fewer than two live neighbours dies, as if by underpopulation."
        cells[y][x].colour = "white";
      } else if ((2 <= neighbours <= 3) && (cells[y][x].colour == "black")) {
        // "Any live cell with two or three live neighbours lives on to the next generation."
        cells[y][x].colour = "black";
      } else if ((neighbours == 3) && (cells[y][x].colour == "white")) {
        // "Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction."
        cells[y][x].colour = "black";
      } else if ((3 < neighbours) && (cells[y][x].colour == "black")) {
        // "Any live cell with more than three live neighbours dies, as if by overpopulation."
        cells[y][x].colour = "white";
      }

Note: I'm using a 2D array (matrix) to store the state of the game and each cell is modeled as a simple object - the only relevant parameter here being its state (stored as colour, live being "black").

Code in context here: https://github.com/HughEvans01/GameOfLife


Solution

  • You are updating the same grid that you read. You might want to start out by having two grids, the current state and the new state. Iterate over the cells in the current state to calculate the new state, then use the new state for the next iteration and so on.

    There's lots of optimizations you can do, but this will give you a correct starting point.

    Also, as others noted, the idiom 2 <= neighbours <= 3 won't evaluate the way you think it will in JS