【问题标题】:How to fix Tic Tac Toe winner determination如何修复井字游戏获胜者的确定
【发布时间】:2015-11-19 07:42:45
【问题描述】:

每次我运行井字游戏程序时,我都可以创建棋盘并完成我的第一个回合。

第一回合结束后,游戏结束为:“IT'S A DRAW”,这是三种结局之一。这发生在计算机甚至可以自己轮到自己之前。

我的程序中的另一个问题是扫描仪用户输入限制(er)不起作用(在代码末尾)。如果用户输入一个字母而不是 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
        }
    }
}

【问题讨论】:

    标签: java arrays draw tic-tac-toe


    【解决方案1】:

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

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

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

    【讨论】:

    • 我把它改成了-1,现在游戏可以结束了,但只是平局。谢谢你的提示。 + 我在getMove 中没有Integer.parseInt 吗?在int xint y 中。
    • @jjimih 1. 你的playerHasWoncomputerHasWon 没有完成,所以它们总是返回false。 2. 你有Integer.parseInt,但你没有捕捉到输入不是数字时可能抛出的异常。
    猜你喜欢
    • 2013-02-11
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多