views:

68

answers:

1

This compiles and runs okay, but the results are totally different from what they should be.

I've snipped irrelavent code:

bool grid[1280][1024]; // hardcoded to my screen res for now

for (int x = 0; x<1280; x++)     //init grid to false
{
    for (int y = 0; y<1024; y++)
    {
        grid[x][y] = false;
    }
}

grid[320][120] = true; // add a simple pattern
grid[320][121] = true;
grid[320][122] = true;
grid[320][123] = true;
grid[320][124] = true;
grid[320][125] = true;
grid[320][126] = true;
grid[320][127] = true;
grid[320][128] = true;

// [snipped]

for (int x = 1; x< (1280 - 1); x++)
{
    for (int y = 1; y< (1024 - 1); y++)
    {
        int n = 0; // neighbours
        if (grid[x-1][y-1]) n++; // top left
        if (grid[x][y-1])   n++; // top middle
        if (grid[x+1][y-1]) n++; // top right

        if (grid[x-1][y])   n++; // left
        if (grid[x+1][y])   n++; // right

        if (grid[x-1][y+1]) n++; // bottom left
        if (grid[x][y+1])   n++; // bottom middle
        if (grid[x+1][y+1]) n++; // bottom right


        if (grid[x][y]) // current cell is on
        {
            SetPixel(screen, x, y, on); // drawing function

            if (n < 2) grid[x][y] = false; // die. :(
            if (n > 3) grid[x][y] = false; // die. :(
            // otherwise (2 or 3), survive. :)

        }
        else // current cell is off
        {
            SetPixel(screen, x, y, off); // drawing function

            if (n == 3) grid[x][y] = true; // IT'S ALIVE!!!
        }



    }
}
+3  A: 

Firstly, it doesn't work because you haven't separated each cell's results, i.e., if grid[0][0] dies, then this will be immediately reflected on grid[1][0]'s life or death, which is not how Game of Life works. Secondly, it doesn't work because you don't appear to have run the game more than one iteration.

DeadMG
oooh damn. I think I have to create a duplicate of the array each turn then, and write the results to the duplicate, and overwrite the original with the duplicate at the start of each turn. Am I right? I don't get your second comment though, how have I run it more than one iteration?
Dataflashsabot
You don't have to overwrite the original array each time. Just toggle the current array in each iteration. The "other" array is always the next current array.
Dialecticus
@Dataflashsabot: You haven't run it more than one iteration. That's the problem. The Game of Life runs forever, not just once.
DeadMG
@Dialecticus: If you update cells in raster-scan order, you only need a 1280x1 array to store updates, not a full-blown 1280x1024...
Oli Charlesworth
@DeadMG everything after the snip is in a loop. Sorry, thought that was clear at the time :)
Dataflashsabot
@Data: The reason I didn't find it clear is because it's not indented further - it's indented like it's at the first scope level.
DeadMG
Ah, whoops. It's indented in the actual code, of course, that was an editing error.
Dataflashsabot