Alca
Alca

Reputation: 55

Conway's Game Of Life - Incorrect Algorithm?

The algorithm I created (implementation of Conway's Game of Life's rules) doesn't match Conway's GoL. I've tried just about everything I can do, but it just doesn't match.

Additionally, if anyone knows how to make it into an infinite plane or perhaps wrap on itself, I'd be interested to see it implemented with my code!

Running JSFiddle: http://jsfiddle.net/jGkKF/2/

Pertinent code:

Checking the surrounding cells for live cells: (Line 28)

var   x2 = x+1,   x3 = x-1,   y2 = y+1,   y3 = y-1;     // Math
if(tC[x][y3] !== undefined && tC[x][y3]) ne++;          // T
if(tC[x][y2] !== undefined && tC[x][y2]) ne++;          // TR
if(tC[x2] !== undefined) {
    if(tC[x2][y]) ne++;                                 // R
    if(tC[x2][y3] !== undefined && tC[x2][y3]) ne++;    // BR
    if(tC[x2][y2] !== undefined && tC[x2][y2]) ne++;    // B
}
if(tC[x3] !== undefined) {
    if(tC[x3][y]) ne++;                                 // BL
    if(tC[x3][y3] !== undefined && tC[x3][y3]) ne++;    // L
    if(tC[x3][y2] !== undefined && tC[x3][y2]) ne++;    // TL
}

And the algorithm: (Line 50)

if(cell && (ne < 2 || ne > 3)) cell = 0; // Over- or under- populated?
else if(!cell && ne == 3) cell = 1;      // Give life?

Upvotes: 0

Views: 264

Answers (2)

Shawn C
Shawn C

Reputation: 356

A few items:

  1. The game rules say to check all 8 surrounding squares. Based on your code, you seem to be only checking 6 of them. Edit: OP is checking all 8. I still recommend point 2, it allows consistent handling of each cell being checked.
  2. The easiest way to hand it is to set up a list of cells that need to be check, then run a loop over that list to do the counting.
  3. To set up a wrapping list, have bounds checking code when setting up the list of cells, e.g.
    • if cellIndex < 0 then cellIndex == maxIndex
    • if cellIndex >= maxIndex then cellIndex = 0
  4. You need to be wary of a "scan line" effect that can occur if you update the values representing "this" generation while trying to calculate the "next" generation. The two need to be stored independently. Note if you are using arrays of ints, this can simply mean storing "this" generation as 0 and 1, and the "next" generation of live cells can be indicated by adding 8 etc. After you process the current generation, change everything >= 8 to 1, and any cell < 8 becomes 0.

Upvotes: 1

Pointy
Pointy

Reputation: 413717

The statement

tC = cells;

does not make a copy of the cell array. It merely creates a second reference to the exact same array. Thus, later on, when you do this:

cells[x][y] = cell; // Setting the cell

that's modifying the same array that the loop is looking at.

Also, in your loop to check neighbors, you've coded an exact comparison to undefined. However, the rest of your code seems to fill empty cells in with 0.

Upvotes: 0

Related Questions