Java中的Tic-Tac-Toe

时间:2014-04-07 03:41:41

标签: java arrays

我很难弄清楚如何打印胜者是谁。我应该创建一个单独的方法来决定是否有人赢了或抽签?这是我到目前为止的代码。任何帮助是极大的赞赏。

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String[][] board = {
        {" ", " ", " "},
        {" ", " ", " "},
        {" ", " ", " "}
    };
    boolean done = false;
    int player = 1;
    int row = 0;
    int col = 0;
    while (done != true) {
        System.out.println("Enter the row and column for your next move");
        row = in.nextInt();
        col = in.nextInt();
        if (player == 1) {
            board[row][col] = "X";
            player = 2;
        } else {
            board[row][col] = "O";
            player = 1;
        }
        printBoard(board);

    }

}

public static void printBoard(String[][] boardValues) {
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            System.out.print("|" + boardValues[row][col] + "|");
        }
        System.out.println();
        System.out.println("-------");
    }
}

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,你缺少确定某人是否获胜的所有逻辑。我个人认为在这种情况下主要是:

print the blank board
while (done is false)
   player makes move
   check for win if true set done to true
   print board

然后基本上你需要一个函数来进行移动,在那里确定它是X还是O.然后是一个检查获胜的方法,这只需要根据之前检查过的最后一次移动来检查,或者它可能更容易检查所有选项。最后打印更新的板,在循环退出后,您可以打印一条获胜消息。

我发现这会将程序分解为一个很好的简单结构。这个链接有一些你可以学习的代码 http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe.html

祝你好运