c++ - C++ 故障检测二维数组中的冲突
问题描述
我正在做一个简单的井字游戏。我的checkCollision
功能有一些错误。这是功能:
void checkCollision(const int rows, const int cols, char ticTacToe [][3])
{
//code to check for collision between x and o
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (ticTacToe[row][col] != '.')
{
std::cout << "Collision detected. Please try again.\n";
}
}
}
}
这是我的main
功能。
int main()
{
//create 2d array
char ticTacToe[3][3] = {
{'.', '.', '.'},
{'.', '.', '.'},
{'.', '.', '.'},
};
//declare variables
const int numRows{ 3 };
const int numCols{ 3 };
const int playerOne{ 1 };
const int playerTwo{ 2 };
int rowCordinate{};
int colCordinate{};
bool hasWon{};
//print grid
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
std::cout << ticTacToe[row][col];
}
std::cout << "\n";
}
//game loop
do {
std::cout << "\nPlayer one, please put in a row co-ordinate:\t";
std::cin >> rowCordinate;
std::cout << "\nPut in a column co-ordinate:\t";
std::cin >> colCordinate;
checkCollision(numRows, numCols, ticTacToe);
changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerOne);
std::cout << "\nPlayer two, please put in a row co-ordinate:\t";
std::cin >> rowCordinate;
std::cout << "\nPut in a column co-ordinate:\t";
std::cin >> colCordinate;
checkCollision(numRows, numCols, ticTacToe);
changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerTwo);
} while (!hasWon);
return 0;
}
每次我在第一个循环之后输入行和列坐标时,它都会告诉我有碰撞。感觉就像数组在 C++ 中如何工作的一个怪癖,但我不确定。任何人都可以帮忙吗?
解决方案
看起来您可能想专门检查 , 处的空间rowCordinate
是否colCordinate
被占用(并且可能不允许用户选择该点)。如果你尝试这样的事情怎么办:
bool checkCollision(const size_t row, const size_t col, char ticTacToe [][3])
{
return ticTacToe[row][col] != '.';
}
然后在主循环中,您需要将用户输入部分更改为:
//game loop
do {
// player 1 input
while (true) {
// get user input
std::cout << "\nPlayer one, please put in a row co-ordinate:\t";
std::cin >> rowCordinate;
std::cout << "\nPut in a column co-ordinate:\t";
std::cin >> colCordinate;
// if the user selected a valid spot, change the array and move on
if (!checkCollision(rowCordinate, colCordinate, ticTacToe)) {
changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerTwo);
break;
}
// otherwise print a message and keep looping
std::cout << "Collision detected. Please try again.\n";
}
// player 2 input
...
推荐阅读
- javascript - AngularJS ng-click 仅适用于第二次单击
- python - Spyder Debug - 如何修复代码并继续单步执行
- postgresql - 如何在 PostgreSQL 中创建序列以将 nextval 添加到表已存在的 id 列?
- c++ - QT - 将 QPushButtons 与 QCheckBoxes 连接
- php - PHP OAuth 错误处理
- ios - 如何修复 AWSCore (AWS-sdk-ios) 中的 [AWSTask 异常] 崩溃
- php - 无法在指定的语言环境中显示验证错误
- mysql - mysql查询某天fk不存在的地方
- flutter - 颤振构建错误。Flutter webview插件的问题
- ubuntu - 安装 OpenMPI:C C++ 编译器不兼容链接