在 C++ 中搜索 2D 数组以查看一行/列是否与另一行/列相同

searching a 2d array in c++ to see if one row/column is the same as another

本文关键字:一行 是否 C++ 搜索 数组 2D      更新时间:2023-10-16

我正在创建一个 tron 游戏,其中包括一个 2d 数组来容纳游戏板 我想创建一个函数来搜索数组的每个索引以查看是否发生了碰撞,即如果玩家 1 进入一个正方形,则玩家 2 已经发生了碰撞

我不知道如何开始,但我编写的代码是我认为会起作用的,但它只是不搜索或返回任何内容

board::searchForCollision(){
found = false;
for (board[0][0]; board[0][0] <100; board[0][0]++)
{ if (board[0][0] == board[0][0] +1){
found= true;
}
else
found = false;
}
return found;
}

我写的代码是我认为会起作用的,但它只是不搜索或返回任何内容。

不幸的是,你犯了一些逻辑错误。

显然,您要检测 2 D 数组中的某个单元格是否包含一些数据。看着你循环:

for (board[0][0]; board[0][0] <100; board[0][0]++)

for 循环的第一部分通常初始化 "running" 变量,用于 "for"。但board[0][0];什么也没做。这是一个无操作。无操作。你也可以把它放在一边。它将编译为任何内容。然后,在 for 循环的条件部分,您只需检查电路板中的一个特定单元格,索引为 0,0 的单元格是否小于 100。您始终在查看相同的单元格 0,0。"for"语句的最后一部分也是如此。您始终递增单元格 0,0。

在下面的if中,您正在比较相同的单元格0,0是否等于相同的单元格0,0 + 1。 这永远不会正确。它总是错误的。就像写如果(3 == 4(。这永远行不通。

此外,您在 if else 语句中对 true 和 false 的处理也不起作用。

您可能想要做的是迭代数组的索引。

类似的东西

for (size_t row = 0U; row < 100 ; ++row)
for (size_t col = 0U; col < 100; ++col) {
// do something with     array[row][col];  
}
}

我不能帮你更多,因为这个问题对我来说不是那么清楚。

假设你想先创建这个 2D Tron 游戏,你需要一个这样的板:

static constexpr int boardSize = 100;
static constexpr int PlayerOneValue = 1;
static constexpr int PlayerTwoValue = 2;
class board {
int board[boardSize][boardSize];
bool tryActivateCell(const int x, const int y, const int playerValue);
board() {
memset(array, 0, sizeof(board));
}
}

当玩家在 2D 板上移动每移动一次时,您需要调用函数来激活单元格,或者如果因为单元格已被其他玩家激活而无法激活单元格,则返回false

bool board::tryActivateCell(const int x, const int y, const int playerValue) {
// Maybe do a check to avoid an overflow if x or y is equal or greater than boardSize
const int& boardValue = board[y][x];
if (boardValue != 0 && boardValue != playerValue) {
// The other player already activate the cell
return false;
}
// Activate the cell with the value of the current player
boardValue = playerValue;
return true;
}

最后,如果前一个函数返回 false,则表示当前玩家与其他玩家激活的单元格发生冲突,需要死亡。