如何解决Tic Tac Toe获胜者的决心

时间:2015-11-19 07:42:46

标签: java arrays draw tic-tac-toe

每次我运行Tic Tac Toe程序时,我都可以创建电路板并进行第一次转弯。

在第一回合之后,游戏结束为:“IT'S A DRAW”,这是三种结束可能性之一。这恰好发生在电脑甚至可以自行转弯之前。

我的程序中的另一个问题是扫描仪用户输入限制(呃)不起作用(在代码的末尾)。如果用户输入,即字母而不是int,则程序崩溃。

package newtictactoe;

import java.util.Scanner;
import java.util.Random;

public class NewTicTacToe {

public static final int DRAW = 0;
public static final int COMPUTER = 1;
public static final int PLAYER = 2;

public static int size;
public static char[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);

/**
 * Creates base for the game.
 *
 * @param args the command line parameters. Not used.
 */
public static void main(String[] args) {

    System.out.println("Select board size");
    System.out.print("[int]: ");
    size = Integer.parseInt(scan.nextLine());

    board = new char[size][size];
    setupBoard();

    int i = 1;

    loop:
    while (true) {
        if (i % 2 == 1) {
            displayBoard();
            getMove();
        } else {
            computerTurn();
        }
        switch (isGameFinished()) {
            case PLAYER:
                System.err.println("YOU WIN!");
                break loop;
            case COMPUTER:
                System.err.println("Computer WINS!\nYOU LOOSE!!");
                break loop;
            case DRAW:
                System.err.println("IT'S A DRAW");
                break loop;
        }

        i++;
    }
}

private static int isGameFinished() {
    if (isDraw()) {
        return DRAW;
    } else if (computerHasWon()) {
        return COMPUTER;
    } else if (playerHasWon()) {
        return PLAYER;
    }
    return 0;
}

/**
 * Checks for computer's win.
 *
 * @return if this game is won by computer.
 */
public static boolean playerHasWon() {
    boolean hasWon = false;

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            // check if 5 in a line
        }
    }

    return hasWon;
}

/**
 * Checks for player's win.
 *
 * @return if this game is won by computer.
 */
public static boolean computerHasWon() {
    boolean hasWon = false;

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            // check if 5 in a line
        }
    }

    return hasWon;
}

/**
 * Checks for draws.
 *
 * @return if this game is a draw
 */
public static boolean isDraw() {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (board[i][j] == ' ') {
                return false;
            }
        }
    }

    return true;
}

/**
 * Displays the board.
 *
 *
 */
public static void displayBoard() {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            System.out.printf("[%s]", board[i][j]);
        }

        System.out.println();
    }
}

/**
 * Displays the board.
 *
 *
 */
public static void setupBoard() {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            board[i][j] = ' ';
        }
    }
}

/*
 * Checks if the move is allowed. 
 *
 *
 */
public static void getMove() {

    Scanner sc = new Scanner(System.in);

    while (true) {
        System.out.printf("ROW: [0-%d]: ", size - 1);
        int x = Integer.parseInt(sc.nextLine());
        System.out.printf("COL: [0-%d]: ", size - 1);
        int y = Integer.parseInt(sc.nextLine());

        if (isValidPlay(x, y)) {
            board[x][y] = 'X';
            break;
        }
    }
}

/*
 * Randomizes computer's turn - where it inputs the mark 'O'.
 *
 *
 */
public static void computerTurn() {
    Random rgen = new Random();  // Random number generator   

    while (true) {
        int x = (int) (Math.random() * size);
        int y = (int) (Math.random() * size);

        if (isValidPlay(x, y)) {
            board[x][y] = 'O';
            break;
        }
    }
}

/**
 * Checks if the move is possible.
 *
 * @param inX
 * @param inY
 * @return
 */
public static boolean isValidPlay(int inX, int inY) {

    // Play is out of bounds and thus not valid.
    if ((inX >= size) || (inY >= size)) {
        return false;
    }

    // Checks if a play have already been made at the location,
    // and the location is thus invalid.  
    return (board[inX][inY] == ' ');
}

代码中的最后两个方法检查扫描仪输入是否有效,但它们不起作用,我不知道原因。

/**
 * Checks if user input is valid
 *
 * @param scan
 * @param prompt
 * @return
 */
public static String getInput(Scanner scan, String prompt) {
    System.out.print(prompt); // Tell user what to input
    String text = "Enter one integer value i.e 5.";
    while (true) { // Keeps on looping until valid input
        text = scan.nextLine();
        if (isInteger(text)) // Checks input is int
        {
            break; // Exit loop
        }
        System.out.print("Try again, " + prompt); // If invalid
    }
    return text; // Return valid user input
}

/**
 * Checks if input string is int.
 *
 * @param str
 * @return
 */
public static boolean isInteger(String str) {
    try {
        Integer.parseInt(str); // If this succeeds the input is int
        return true;
    } catch (NumberFormatException e) {
        return false; // If not int
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的isGameFinished()方法默认返回0(当游戏未结束时),但您的DRAW常量也是0.尝试将其更改为在游戏时返回(例如)-1还没结束。

一个更好的解决方案是让一个方法isGameFinished()返回boolean以指示游戏是否结束,另一个方法getWinner()将返回获胜者(DRAW或COMPUTER)或者PLAYER),只有在isGameFinished()返回true时才会被调用。

你的getMove方法应该捕获NumberFormatException,Integer.parseInt可以抛出它。