我是C ++的初学者,正在寻找这段代码的帮助。我无法弄清楚为什么这段代码总是返回“你不能选择单元格。再次选择!” 是什么让这段代码错了?你可以帮忙吗?
#include <iostream>
#include <string>
void playTTT();
void outBoard(char board[3][3]);
char nextplay(char symbol);
bool checkResult(char board[3][3], char symbol, int plays);
bool check(int row, int col);
int main()
{
using namespace std;
cout << "Let's play Tic Tac Toe!" << endl;
cout << endl;
playTTT();
char yn = 'a';
return 0;
}
//Where the game starts. Sets up board and runs 9 plays
void playTTT()
{
using namespace std;
char board[3][3] =
{
{ ' ', ' ', ' ', },{ ' ', ' ', ' ', },{ ' ', ' ', ' ' }
};
outBoard(board);
char symbol = ' ';
for (int count = 1; count < 10; count++)
{
if (!(count % 2)) {
symbol = 'O';
}
else {
symbol = 'X';
}
nextplay(symbol);
outBoard(board);
if (count > 4)
if (checkResult(board, symbol, count)) break;
}
}
//Takes next move and checks for errors
char nextplay(char symbol) {
using namespace std;
char board[3][3];
char answer = false;
int row, col;
cout << "Player" << symbol << " Enter a row and column" << endl;
cin >> row >> col;
row--, col--;
answer = check(row, col);
if (answer == true) {
cout << " You can not choose the cell. Choose again!" << endl;
}
else {
return board[row][col] = symbol;
}
}
bool check(int row, int col) {
using namespace std;
char board[3][3];
if (board[row][col] == 'X' || 'O'){
return true;
}
else{
cout << "Going through Check";
return false;
}
}
//Output the board
void outBoard(char x[3][3])
{
using namespace std;
cout << " 1 2 3 \n";
cout << "1 " << x[0][0] << " | " << x[0][1] << " | " << x[0][2] << " \n";
cout << " ---+---+---\n";
cout << "2 " << x[1][0] << " | " << x[1][1] << " | " << x[1][2] << " \n";
cout << " ---+---+---\n";
cout << "3 " << x[2][0] << " | " << x[2][1] << " | " << x[2][2] << " \n";
}
//Check to see if a player win or even
bool checkResult(char board[3][3], char symbol, int count)
{
using namespace std;
bool winner = false;
//Check vertical and horizontal
for (int k = 0; k < 3; k++)
{
if (board[k][0] == symbol && board[k][1] == symbol && board[k][2] == symbol)
winner = true;
if (board[0][k] == symbol && board[1][k] == symbol && board[2][k] == symbol)
winner = true;
}
//Check diagonal
if (board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol)
winner = true;
if (board[2][0] == symbol && board[1][1] == symbol && board[0][2] == symbol)
winner = true;
if (winner)
cout << "Congratulations! The winner is " << symbol << "!!" << endl;
if (!(winner) && (count == 9))
cout << "The result is even." << endl;
return winner;
}
答案 0 :(得分:5)
您错误地检查了'X'或'O'
该行
if (board[row][col] == 'X' || 'O'){
应该是
if (board[row][col] == 'X' || board[row][col] == 'O'){
由于operator precedence,在||之前正在评估==。
board[row][col] == 'X'
可能与否,但
(true or false) || 'O'
总是如此。