【问题标题】:TicTacToe Java check for drawTicTacToe Java 检查抽奖
【发布时间】:2021-11-25 23:06:33
【问题描述】:

在我的井字游戏中,我有一个方法可以检查是否有人获胜,并且效果很好。但是检查是否有平局的方法不起作用。首先它检查是否有赢家,如果没有,它应该检查是否有平局。场上每打完 9 个名额,就不会出现“平局”消息。我找不到错误。

for (int i = 0; i < 5; i++) {
                System.out.println("welcome!");
                playerMove(gameBoard);
                if (checkIfCurrentPlayerIsWinner(gameBoard, 'X')) {
                    System.out.println("Player won the game!");
                    playerScore++;
                    break;
if (checkDraw(gameBoard)) {
                    System.out.println("It's a draw!");
                    tieScore++;
                    break;
                }
 private static boolean checkDraw(char[][] gameBoard){
        for(int i = 1; i< 10; i++){
            if(getFieldContent(gameBoard, i) != ' '){
                return false;
            }
        }
        return true;
    }
public static char getFieldContent(char[][] gameboard, int fieldNumber) {

        switch (fieldNumber) {
            case 1:
                return gameboard[0][0];
            case 2:
                return gameboard[0][2];
            case 3:
                return gameboard[0][4];
            case 4:
                return gameboard[2][0];
            case 5:
                return gameboard[2][2];
            case 6:
                return gameboard[2][4];
            case 7:
                return gameboard[4][0];
            case 8:
                return gameboard[4][2];
            case 9:
                return gameboard[4][4];
        }
        return ' ';
    }

【问题讨论】:

    标签: java intellij-idea draw tic-tac-toe


    【解决方案1】:

    我在这里推断gameboard 最初包含所有空格,并且您出于某种原因决定仅将移动存储在其偶数索引中。我还要注意您的代码缺少一些右括号 (}s)。请以后只发布可编译的代码,或者如果编译是您的问题,请指出。

    无论如何,如果gameboard 中的所有测试索引不是 ' 'true,则checkDraw 返回false。似乎您想要测试的是相反的,即整个棋盘都已播放,即不存在 non-space 单元格。在这种情况下,checkDraw 将如下所示:

    private static boolean checkDraw(char[][] gameBoard) {
        for(int i = 1; i < 10; i++) {
            // note that the test is now == instead of !=
            if(getFieldContent(gameBoard, i) == ' ') {
                return false;
            }
        }
        // no non-space cells were found, so the entire board has been
        // played out, resulting in a draw, provided that a separate
        // winner check has already been conducted
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多