[英]searching a 2d array in c++ to see if one row/column is the same as another
我正在创建一个 tron 游戏,其中包含一个用于保存游戏板的 2d 数组我想创建一个函数来搜索数组的每个索引以查看是否发生了碰撞,即如果玩家一个进入玩家二拥有的方块已经是碰撞了
我不知道如何开始,但我写的代码是我认为可行的,但它只是不搜索或返回任何内容
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;
}
我写的代码是我认为可行的,但它只是不搜索或返回任何东西。
不幸的是,你犯了一些逻辑错误。
显然您想检测二维数组中的某个单元格是否包含一些数据。 看着你 for 循环:
for (board[0][0]; board[0][0] <100; board[0][0]++)
for 循环的第一部分通常初始化在“for”中使用的“running”变量。 但是board[0][0];
什么也没做。 这是一个 noOp。 没有操作。 你也可以把它放在一边。 它将编译为空。 然后,在 for 循环的条件部分,您只是检查板上是否有一个特定的单元格,索引为 0,0 的单元格小于 100。您总是在查看同一个单元格 0,0。 “for”语句的最后一部分也是如此。 您总是将单元格增加 0,0。
在下面的 if 中,您要比较相同的单元格 0,0 是否等于相同的单元格 0,0 + 1。这永远不会是真的。 它总是假的。 就像写 if (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,则表示当前玩家与其他玩家激活的单元格发生碰撞,需要死亡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.