控制台tic tac toe

时间:2015-09-22 10:59:42

标签: java console-application tic-tac-toe

好吧,我已经完成了之前的一些问题,这并没有真正帮助我,因为大多数人都在使用java swing和其他远离我联盟的东西。我只需要一个基于功能控制台的tic tac toe,但我不想复制+粘贴完成的代码。    到目前为止,我被困在最后一个方法makeMove。它现在要求坐标并保存变量行和输入中的输入。 col,但那又怎样?如何让棋子出现在棋盘上? 此外,它不喜欢我使用行&在下一个循环中再次col,所以我不确定该怎么做。

import java.util.Scanner;

public class TTT {

    static Scanner keyboard = new Scanner(System.in);
    static int counter;
    static String player1, player2;
    static boolean gameOver = false;
    static char[][] board = new char[3][3];
    static char playerMarker;

    public static void main(String[] args) {

        setupPlayers();
        printBoard();
        setupBoard();
        makeMove();
    }

    public static void setupBoard() {
        for (int i = 0; i < 3; i++)
            for (int k = 0; k < 3; k++)
                board[i][k] = ' ';


    }

    static public void printBoard() {
        System.out.println("\n");
        System.out.println(board[0][0] + "   |" + board[0][1] + "   |" + board[0][2]);
        System.out.println("-----------");
        System.out.println(board[1][0] + "   |" + board[1][1] + "   |" + board[1][2]);
        System.out.println("-----------");
        System.out.println(board[2][0] + "   |" + board[2][1] + "   |" + board[2][2]);

    }

    public static void setupPlayers() {

        System.out.print("Player1, what's your name?: ");
        player1 = keyboard.next();
        System.out.print("Alright " + player1 + ", who's Player2?");
        player2 = keyboard.next();
        System.out.print(player1 + " versus. " + player2 + ", good luck!");
    }

    public static void makeMove()
    {
        System.out.println("Enter a row and a column: ");
        int row = keyboard.nextInt();
        int col = keyboard.nextInt();

        while (board[row][col] != ' ')
        {
            System.out.println("\nCoordinates already in use. Please try again: ");

        }
    }
}

2 个答案:

答案 0 :(得分:0)

有点(如果我不准)

public static void makeMove()
{
    System.out.println("Enter a row and a column: ");
    int row = keyboard.nextInt();
    int col = keyboard.nextInt();

    if (board[row][col] != ' ')
    {
        System.out.println("\nCoordinates already in use. Please try again: ");
       return;
    }
    board[row][col] = 'X' ... or '+' please code 
    printBoard();


}
编辑:Joop说计算机移动,我的答案是纠正用户移动。 Yout工作是一起收集代码:)

答案 1 :(得分:0)

以下break使用自由命名的标签loop输出for循环。 通常不应该使用标签,但这里似乎很自然。 你无法打破,但寻找最好的(i,k)。

boolean found = false;
loop: for (int i = 0; i < 3; i++) {
    for (int k = 0; k < 3; k++) {
        if (board[i][k] == ' ') {
            found = true;
            row = i;
            col = j;
            break loop;
        }
    }
}