【问题标题】:How do I determine a winner in my Tic Tac Toe program如何确定井字游戏计划的获胜者
【发布时间】:2015-11-16 14:59:53
【问题描述】:

较早的帖子:How do I make my tictactoe program scalable

我试图使井字游戏程序(人类与计算机)具有可扩展性(可以更改棋盘大小)。我之前遇到过大问题,但大部分都解决了。

游戏的规则是基本的井字游戏,但一个不同的规则是,无论棋盘有多大(>= 5 时),玩家或计算机只需连续五个标记即可获胜。

现在,我的程序唯一的破局问题是确定谁赢得了比赛。比赛目前只能以“平局”结束。 (另外我还没有实现“>= 5”)。

具体的问题解释是我需要为“computer wins”和/或“player wins”之类的内容确定获胜者和结束画面。

package tictactoe;

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

public class TicTacToe {

    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;

        while (true) {
            if (i % 2 == 1) {
                displayBoard();
                getMove();
            } else {
                computerTurn();
            }

            // isWon()
            if (isDraw()) {
                System.err.println("Draw!");
                break;
            }

            i++;
        }

    }

    /**
     * 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] == ' ');
    }
}

【问题讨论】:

  • 每回合后检查是否有人赢了?
  • @MuratK。根据他的代码(这与他的要求相矛盾),他已经得出了这个结论。在每个玩家/电脑轮换后,他的while(true) 中都有// isWon()。尽管 OP 没有明确提出这个问题,但我假设他想知道如何实现 isWon(),其中将检查三个/四个/五个(取决于板的大小)相邻的 X 或 O(水平、垂直或对角线)。同样,这只是我的假设,所以也许 OP 应该稍微编辑一下他的问题,并在 isWon()-method 中展示他迄今为止所尝试的内容。

标签: java arrays tic-tac-toe


【解决方案1】:

您已经有了要玩的循环,因此,在每次迭代中,以同样的方式检查游戏是否isDraw(),同时检查是否有一些玩家获胜:

while (true) {
    if (i % 2 == 1) {
        displayBoard();
        getMove();
    } else {
        computerTurn();
    }

    // isWon()
    if (isDraw()) {
        System.err.println("Draw!");
        break;
    } else if (playerHasWon()){
        System.err.println("YOU WIN!");
        break;
    } else if (computerHasWon()) {
        System.err.println("Computer WINS!\nYOU LOOSE!!");
        break;
    }

    i++;
}

创建所需方法后:

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 ;
}

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 ;
}

下一个问题当然是我如何创建这个方法??不知道如果你有这个问题,但做一个快速检查hereherehere你会发现一些想法。


添加:

为了澄清,我将创建一个函数返回int 而不是booleans,以使用一些常量检查游戏是否完成:

private final int DRAW = 0;
private final int COMPUTER = 1;
private final int PLAYER = 2;

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

然后简单地检查一个开关盒(check here how to break the while insite the while)

loop: while (true) {
    // other stufff
    switch (isGameFinished()) {
    case PLAYER:
        System.err.println("YOU WIN!");
        break loop;
    case COMPUTER:
        System.err.println("Computer WINS!\nYOU LOOSE!!");
        break loop;
    case DRW:       
        System.err.println("IT'S A DRAW");
        break loop;
}

【讨论】:

  • 有趣而有用的答案,非常感谢。仍然没有真正让程序完美运行,但我已经取得了一些进展。再次感谢!
猜你喜欢
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多