简体   繁体   中英

Wrapping in Conway's Game of Life C++

I am trying to write a program that implements Conway's game of life on a 20x60 cell board. The grid will wrap around so the left side will be connected to (neighbouring) the right side and the top will be connected to the bottom.

Thus any cell with position (1, col) , will have a neighbour at (maxRow, col) . Any cell with position (row, 1) will have a neighbour at (row, maxCol) .

The following function is supposed to count the number of neighbouring cells. It works for coordinates not on the edges, but not for ones that are. For instance, if there are points at (1, 10) , (1, 11) , and (1, 12) and (1, 10) is passed into the function, it will return a high number as neighbour count instead of 1 .

{
    int i, j;
    int count = 0;
    for (i = row - 1; i <= row + 1; i++)
       for (j = col - 1; j <= col + 1; j++) 
           count += grid[i][j]; }

    if (row==maxrow-1 || row==0)
         count = count+ grid [(row-(maxrow-1))*-1][col-1]+grid[(row-(maxrow-1))*-1][col]+grid[(row-(maxrow-1))*-1][col+1];

    if (col==0 || col==maxcol-1)
         count=count +grid[row-1][(col-(maxcol-1))*-1]+grid[row][(col-(maxcol-1))*-1]+grid[row+1][(col-(maxcol-1))*-1];



    count -= grid[row][col];
    return count;
    } 

First, I would change the grid to be 0-based instead of 1-based.

Then you can write a simple loop:

int count = 0;
for (i = row - 1; i <= row + 1; i++) {
   for (j = col - 1; j <= col + 1; j++) {
      if(i != row && j != col) {
         count += grid[(i + maxrow)%maxrow][(j + maxcol)%maxcol];
      }
   }
}

The + maxrow is to make sure the index is positive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM