gpt4 book ai didi

c++ - 生命游戏邻居检查(更简单的方法可能吗?)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:45 24 4
gpt4 key购买 nike

目前我正在尝试用 C++ 制作生命游戏,这是我第一次使用 C++ 练习。我有一个问题,我们需要制作一些游戏模式,例如一种称为“圆环”的游戏模式,其中离开棋盘的单元格应在另一侧重新进入棋盘。

现在,我正在检查邻居。但是我用大量的 if 子句对它进行了硬编码,因为我尝试了一些 for 循环但它没有用。

但这真的是唯一的选择吗?对每一种可能性进行硬编码(左侧、右侧、上侧、下侧等的单元格?

这是我的代码片段:

int countNeighboursTorus(int a, int b) {

int living = 0;

// when the starting cell is the one on the upper left (start of the board)
if (a == 0 && b == 0) {

// cell below
if (board[a - 1][b] != DEAD) {
living++;
}
// cell right below
if (board[a + 1][b + 1] != DEAD) {
living++;
}
// cell right
if (board[a][b + 1] != DEAD) {
living++;
}
// cell above (other side of the board)
if (board[HEIGHT - 1][b] != DEAD) {
living++;
}
// cell above right (other side of the board)
if (board[HEIGHT - 1][b + 1] != DEAD) {
living++;
}

}

// first edge case (height = 0, width != 0):
else if (a == 0 && b != 0) {
// cell below
if (board[a - 1][b] != DEAD) {
living++;
}
// cell right below
if (board[a + 1][b + 1] != DEAD) {
living++;
}
// cell right
if (board[a][b + 1] != DEAD) {
living++;
}
// cell left below
if (board[a + 1][b - 1] != DEAD) {
living++;
}
// cell left
if (board[a][b - 1] != DEAD) {
living++;
}
// cell left above (other side of the board)
if (board[HEIGHT - 1][b - 1] != DEAD) {
living++;
}
// cell above (other side of the board)
if (board[HEIGHT - 1][b] != DEAD) {
living++;
}
// cell above right (other side of the board)
if (board[HEIGHT - 1][b + 1] != DEAD) {
living++;
}
}

return living;

我编写的 for 循环之一,但没有真正起作用,如下所示 - 该循环始终计算了太多的单元格。循环后,所有细胞总是处于死亡状态,因为程序总是计算出 3 个以上的活细胞,即使从一开始只有 2 个细胞是活的。我希望这个解释对你有帮助,解释起来有点困难。我做了一个输出 - “+” - 它通常显示大约 5/6 加号,即使它应该只显示两次(两个活细胞)。

// for any other "normal" cases inside of the board:
else if (a != 0 && b != 0 && a < HEIGHT - 1 && b < WIDTH - 1) {
for (int c = -1; c < 2; c++) {
for (int d = -1; d < 2; d++) {
if (!(c == 0 && d == 0)) {
if (board[a + c][b + d] != DEAD) {
living++;
}
}
}
}
}

是否有任何选项可以简化它?例如循环,就像我试过的那样?还是应该这样做?我现在真的看不到隧道尽头的曙光。只是为了让我知道我是否白白做这件事。我确实对 C++ 语法有一些问题,因为到目前为止我只用了大约一年的 Java,所以我是 C++ 的初学者。我很感激任何提示!

最佳答案

是的。使用取模运算符:

代替

    if (board[a + 1][b + 1] != DEAD) {

使用:

    if (board[(a + 1) % HEIGHT][(b + 1) % WIDTH] != DEAD) {

做减法时会稍微复杂一些(% 实际上不是取模运算,而是取余运算)。你不想在 -1 上使用它(它只会返回 -1),所以添加一个额外的高度/宽度:

    if (board[(a - 1 + HEIGHT) % HEIGHT][(b - 1 + WIDTH) % WIDTH] != DEAD) {

然后您可以对电路板的所有单元格使用相同的代码。

关于c++ - 生命游戏邻居检查(更简单的方法可能吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139096/

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