gpt4 book ai didi

c++ - 在 Conway 的生命游戏 C++ 中包装

转载 作者:行者123 更新时间:2023-11-28 06:04:42 25 4
gpt4 key购买 nike

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.

因此,任何位置为 (1, col) 的单元格都将在 (maxRow, col) 处有一个邻居。位置为 (row, 1) 的任何单元格都将在 (row, maxCol) 处有一个邻居。

下面的函数应该计算相邻单元格的数量。它适用于不在边缘上的坐标,但不适用于边缘上的坐标。例如,如果在 (1, 10)(1, 11)(1, 12) 处有点>(1, 10) 被传递到函数中,它将返回一个高数作为邻居计数而不是 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;
}

最佳答案

首先,我会将网格更改为基于 0 而不是基于 1。

然后你可以写一个简单的循环:

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];
}
}
}

+ maxrow是为了确保索引是正数。

关于c++ - 在 Conway 的生命游戏 C++ 中包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com