0
我得到了用方法制作的小型tic tac脚趾。但它不能按预期工作。在3行之后,它不立即退出循环,而是再执行一次,然后结束它。虽然循环使得一个循环后击中休息
while(1){ // infinite loop until someone has won, or the board is full
game.printBoard(); //prints the board
game.move(); // player enters a move
if(game.checkWin()) //returns 1 if there are 3 in row by same mark or 0 if
// the condition is not met
{
break;
}
} // end of while loop
行有3之后,它进入到功能“game.checkWin()”,并应该返回1,执行break语句并结束while循环。
从checkWin()的某些代码:
bool TicTacToe::checkWin() //this function belongs to a calss
{
//checks for 3 in row 1-2-3 by the same mark, this is made for all combinations
if(_board[0] == _turn && _board[1] == _turn && _board[2] == _turn)
{
cout << _turn << " has won the match by: 1-2-3\n";
return 1; // returns 1 meaning that somebody has won
}
...... //same code as above but with different positions
return 0 // returns 0 meaning that nobody has met the winning conditions
} // ends of the function
编辑: 一些休息的代码
class TicTacToe
{
public:
void setBoard(); //sets the board
void printBoard(); //prints the board
void move(); // user makes a move
bool checkInput(); // checking whether the move is valid
bool checkWin(); //chekcs for win
private:
char _turn = 'X'; // players turn
char _board[9]; // the board
int _position; // the int used for cin
};
void TicTacToe::move() // user is about to enter a move
{
if(checkInput()) // let user enter a valid move
{
_board[_position - 1] = _turn; // setting the board to it's mark
(_turn == 'X')? _turn = 'O': _turn = 'X'; // switching from X to O and vice versa
}
}
bool TicTacToe::checkInput() // function called only with the TicTacToe::move() function
{
cout << "It is " << _turn << " turn!\n";
cout << "Please enter one of the available squares!\n";
cin >> _position;
if (!(_position >= 1 && _position <= 9))
{
cout << "Error! Invalid input!\n";
return 0; //meaning the user is not allowed to enter that position
}
else if(_board[_position - 1] != '_')
{
cout << "Error! There is already a mark!\nPlease enter another square!\n";
return 0; //meaning the user is not allowed to enter that position
}
return 1; //means that position is valid and proceeds to change the board
} // end of the function
int main()
{
cout << "Welcome to TicTacToe!\n";
TicTacToe game;
game.setBoard();
while(1){
....... // some code already shown above
} // end of while loop
cout << "Thank you for playing!\n";
return 0;
}
猜测是某些其他“不同的位置”不正确地执行检查或忘记返回1. –
添加更多('cout')语句以帮助您进行调试。特别是在每个函数的'return'语句附近,以显示实际返回的内容。或者使用IDE的调试器来遍历代码。 – selbie
它们完全一样,但在_board上的位置不同。但是,即使在上面代码中给出的位置上有3个标记,它也不会立即退出循环。 – AleksandarAngelov