-1

我正在写这个井字游戏。我们都知道井字游戏是如何运作的,要么有人赢,要么没有人赢,然后棋盘就满了。

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");
    }
}
4

3 回答 3

1

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

while (gameNotOver) {
  // assuming an enum called Turn
  if (turn == Turn.PLAYER) {
    doPlayersTurn();
  } else {
    doComputerTurn();
  } 
  checkForWin();
  turn = turn.nextTurn();
}
于 2013-09-02T12:41:51.240 回答
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;
        }
    }
于 2013-09-02T12:44:40.943 回答
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

于 2013-09-02T12:43:01.683 回答