Java TicTacToe - 比较大量值

时间:2013-09-02 12:38:31

标签: java while-loop

我正在写这个TicTacToe游戏。我们都知道TicTacToe是如何工作的,无论是有人获胜还是没有人赢,董事会都会满员。

board.playable()检查是否有人赢了比赛或者棋盘是否已满。这段代码运行正常,但我只是想知道是否有更简洁的方法来编写我的while循环。两次具有相同的条件似乎有点多余。但是我需要在计算机移动之前运行board.playable()检查。

public void runGame()
{
    while(board.playable()==true)
    {
        // Outputs a visual representation to console window
        this.displayBoard();
        // Asks player to enter a valid number
        this.playerMove();

        // Check if it still playable for the next
        if(board.playable() == true)
        {
            computerMove()
        }
    }

    this.displayBoard();

    // Outputs the final status of the game and the winner if any
    if(board.wonBoard()==true) {
        System.out.println(board.whoWon() + " has won the game");
    } else {
        System.out.println("The board is full. Nobody has won the game");
    }
}

3 个答案:

答案 0 :(得分:1)

您的程序似乎没有“转向”状态。如果它有这样一个实体,那么它可以转弯并在每个回合后检查获胜者。另外,在所有代码中删除== true

while (gameNotOver) {
  // assuming an enum called Turn
  if (turn == Turn.PLAYER) {
    doPlayersTurn();
  } else {
    doComputerTurn();
  } 
  checkForWin();
  turn = turn.nextTurn();
}

答案 1 :(得分:0)

while(board.playable())
    {
        // Outputs a visual representation to console window
        this.displayBoard();
        // Asks player to enter a valid number
        this.playerMove();

        // Check if it still playable for the next
        if(board.playable())
        {
            computerMove();
        }
    }

删除== true

答案 2 :(得分:0)

您可以使用该标志知道其移动是:像这样

boolean playerTurn = Boolean.TRUE;
    while(board.playable()==true)
    {
        // Outputs a visual representation to console window
        this.displayBoard();
        // Asks player to enter a valid number
        if(playerTurn){
            this.playerMove();
            playerTurn=Boolean.FALSE;
        }
        else{
            computerMove();
            playerTurn = Boolean.TRUE;
        }
    }