while循环在中断之后再循环一次

时间:2015-11-01 05:15:21

标签: c++

我用方法制作了小小的tic tac toe。但它没有按预期工作。排在第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 个答案:

答案 0 :(得分:2)

因为在移动中,你移动,更改播放器,然后检查(现在其他)玩家是否有一个。