在 C++ 中搜索 2D 数组以查看一行/列是否与另一行/列相同
searching a 2d array in c++ to see if one row/column is the same as another
我正在创建一个 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,则表示当前玩家与其他玩家激活的单元格发生冲突,需要死亡。
- 如何测试一行是否为空?
- 如何检查一行中的3个节点是否相同C++?
- 如何检查从键盘输入的特定整数值是否存在于C++文件中的一行或多行中
- 是否可以让 Bitset 将位打印到一行?
- 在 C++ 中搜索 2D 数组以查看一行/列是否与另一行/列相同
- 更改值,并知道它是否在一行中更改
- 如何确定输入文件中的一行是否是最后一行?C++
- 是否可以使用一行代码从 std::cin 中提取格式化输入
- 是否可以遍历文本文件行并使用字符串流来解析每一行
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- 是否可以<int>在一行中将向量值分配给 std::unordered<int,std::vector<int>>?
- 在C++中检查输入文件中的一行是否只有一个int
- 如何检查文件的最后一行是否有new_line字符?C++
- 是否可以在一行中初始化一个值递增的向量
- 如何在初始化的同一行检查流是否失败
- 如果输入大于零,是否有一行用于从输入中减去 1
- 如何知道文本文件中的字符串是否在第一行?[C++ ]
- 是否可以将其重写为一行
- 给定尺寸为 26 * 7 的图像是否有可能在垫子的每一行中包含 78 个单独的颜色值,而另一个可以包含 77
- 确定文件中的一行是否包含阿拉伯数字或罗马数字的c++程序