2015-11-01 71 views
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; 
} 
+0

猜測是某些其他「不同的位置」不正確地執行檢查或忘記返回1. –

+1

添加更多('cout')語句以幫助您進行調試。特別是在每個函數的'return'語句附近,以顯示實際返回的內容。或者使用IDE的調試器來遍歷代碼。 – selbie

+0

它們完全一樣,但在_board上的位置不同。但是,即使在上面代碼中給出的位置上有3個標記,它也不會立即退出循環。 – AleksandarAngelov

回答

2

因爲在動,你做出的舉動,改變播放器,然後檢查看看(現在是其他)玩家是否有一個。

+1

這是一個合乎邏輯的解釋。對不起,我的新手代碼 – AleksandarAngelov