我需要制作一个使用1-9格的双人tic tac toe游戏。玩家输入他们想要的字母代表的数字。但是,我无法识别谁赢了。在输入的每个数字之后,它表示输入数字的最后一个玩家赢了。
#include <iostream>
using namespace std;
int main()
{
int Xp, Op, turn;
char board[9] = {'1','2','3','4','5','6','7','8','9'};
cout << "Please enter a number on the board that is the spot you wish to use" << endl;
cout << "Board:\n";
cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;
do
{
for (turn=1; turn<10; turn++)
if (!(turn % 2) == 0)
{
cout << "\nPlayer X's turn." << endl;
cin >> Xp;
board[Xp-1] = 'X';
cout << "Current Board:\n";
cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;
if((board[0]&&board[1]&&board[2] == 'X') || (board[3]&&board[4]&&board[5] == 'X') || (board[6]&&board[7]&&board[8] == 'X') ||
(board[0]&&board[3]&&board[6] == 'X') || (board[1]&&board[4]&&board[7] == 'X') || (board[2]&&board[5]&&board[8] == 'X') ||
(board[0]&&board[4]&&board[8] == 'X') || (board[6]&&board[4]&&board[2] == 'X'));
{
cout << "Player X wins!!!!" << endl;
}
else
{
cout << "\nPlayer O's turn." << endl;
cin >> Op;
board[Op-1] = 'O';
cout << "Current Board:\n";
cout << board[0] << " " << board[1] << " " << board[2] << endl;
cout << board[3] << " " << board[4] << " " << board[5] << endl;
cout << board[6] << " " << board[7] << " " << board[8] << endl;
if((board[0]&&board[1]&&board[2] == 'O') || (board[3]&&board[4]&&board[5] == 'O') || (board[6]&&board[7]&&board[8] == 'O') ||
(board[0]&&board[3]&&board[6] == 'O') || (board[1]&&board[4]&&board[7] == 'O') || (board[2]&&board[5]&&board[8] == 'O') ||
(board[0]&&board[4]&&board[8] == 'O') || (board[6]&&board[4]&&board[2] == 'O'));
{
cout << "Player O wins!!!!" << endl;
}
}
}
while(turn<10);
cout << "We have a tie!!!";
return 0;
}
答案 0 :(得分:2)
问题在于if语句如下所示:
if((board[0]&&board[1]&&board[2] == 'X') || (board[3]&&board[4]&&board[5] == 'X') || (board[6]&&board[7]&&board[8] == 'X') ||
(board[0]&&board[3]&&board[6] == 'X') || (board[1]&&board[4]&&board[7] == 'X') || (board[2]&&board[5]&&board[8] == 'X') ||
(board[0]&&board[4]&&board[8] == 'X') || (board[6]&&board[4]&&board[2] == 'X'));
{
cout << "Player X wins!!!!" << endl;
}
在您打算成为if语句主体的代码块之前有一个;
。
;
结束语句,使下一个块不再是if的一部分,而只是一个代码块,无论条件的结果如何,都要执行。