我如何确定我的井字程序赢家 [英] How do I determine a winner in my Tic Tac Toe program

查看:198
本文介绍了我如何确定我的井字程序赢家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此前后:<一href=\"http://stackoverflow.com/questions/33655531/how-do-i-make-my-tictactoe-program-scalable/33655701?noredirect=1#comment55208355_33655701\">How让我的井字游戏程序可扩展

我试图做一个井字程序(人类VS计算机)可扩展性(电路板尺寸可以改变)。我有大的问题,但早期固定其中的大多数。

这个游戏的规则是基本的井字但有不同的规则是,无论该板是多么大时(&GT; = 5 )的播放器或计算机只需要连续5痕赢了。

现在我的计划的唯一gamebreaking的问题是确定谁赢得了比赛。该比赛结束的那一刻一个'平局'这是唯一可能的。 (另外我还没有实现的&GT; = 5 还)。

具体问题的解释是,我需要确定一个胜利者,最终屏幕类似计算机胜和/或玩家赢

 包井字游戏;进口java.util.Scanner中;
进口了java.util.Random;公共类井字游戏{    公共静态INT大小;
    公共静态的char [] []板;
    公共静态INT得分= 0;
    公共静态扫描程序扫描=新的扫描仪(System.in);    / **
     *创建为游戏基地。
     *
     * @参数ARGS的命令行参数。不曾用过。
     * /
    公共静态无效的主要(字串[] args){        的System.out.println(选择董事会规模);
        System.out.print([INT]:);
        大小=的Integer.parseInt(scan.nextLine());        板=新的char [大小] [SIZE]
        setupBoard();        INT I = 1;        而(真){
            如果(ⅰ%2 == 1){
                displayBoard();
                getMove();
            }其他{
                computerTurn();
            }            // isWon()
            如果(isDraw()){
                通信System.err.println(画!);
                打破;
            }            我++;
        }    }    / **
     *检查是否有平局。
     *
     返回:如果这场比赛是平局
     * /
    公共静态布尔isDraw(){
        的for(int i = 0; I&LT;大小;我++){
            对于(INT J = 0; J&LT;大小; J ++){
                如果(板[I] [J] ==''){
                    返回false;
                }
            }
        }        返回true;
    }    / **
     *显示板。
     *
     *
     * /
    公共静态无效displayBoard(){
        的for(int i = 0; I&LT;大小;我++){
            对于(INT J = 0; J&LT;大小; J ++){
                System.out.printf([%s]的电路板[I] [J]);
            }            的System.out.println();
        }
    }    / **
     *显示板。
     *
     *
     * /
    公共静态无效setupBoard(){
        的for(int i = 0; I&LT;大小;我++){
            对于(INT J = 0; J&LT;大小; J ++){
                板[I] [J] ='';
            }
        }
    }    / *
     *检查,如果此举是允许的。
     *
     *
     * /
    公共静态无效getMove(){        扫描仪SC =新的扫描仪(System.in);        而(真){
            System.out.printf(ROW:0-%D]。:大小 - 1);
            INT X =的Integer.parseInt(sc.nextLine());
            System.out.printf(COL:0-%D]。:大小 - 1);
            INT Y =的Integer.parseInt(sc.nextLine());            如果(isValidPlay(X,Y)){
                板[X] [Y] ='X';
                打破;
            }
        }
    }    / *
     *电脑随机化的回合 - 它输入标志O。
     *
     *
     * /
    公共静态无效computerTurn(){
        随机RGen元=新的随机(); //随机数发生器        而(真){
            INT X =(INT)(的Math.random()*尺寸);
            INT Y =(INT)(的Math.random()*尺寸);            如果(isValidPlay(X,Y)){
                板[X] [Y] ='O';
                打破;
            }
        }
    }    / **
     *检查,如果此举是可能的。
     *
     * @参数INX
     * @参数INY
     * @返回
     * /
    公共静态布尔isValidPlay(INT INX,诠释INY){        //玩的就是出界,因而无效。
        如果((INX&GT; =大小)||(INY&GT; =大小)){
            返回false;
        }        //检查是否戏已经在该位置做,
        //和位置是这样无效。
        返程(板[INX] [INY] =='');
    }
}


解决方案

您已经将循环播放,所以,在每次迭代中,以同样的方式,你是否在游戏 isDraw(),也检查了一些选手获得:

 ,而(真){
    如果(ⅰ%2 == 1){
        displayBoard();
        getMove();
    }其他{
        computerTurn();
    }    // isWon()
    如果(isDraw()){
        通信System.err.println(画!);
        打破;
    }否则如果(playerHasWon()){
        通信System.err.println(你赢!);
        打破;
    }否则如果(computerHasWon()){
        通信System.err.println(计算机WINS \\ n您LOOSE !!!);
        打破;
    }    我++;
}

创建后,需要的方法:

 公共静态布尔playerHasWon(){
    布尔hasWon = FALSE;    的for(int i = 0; I&LT;大小;我++){
        对于(INT J = 0; J&LT;大小; J ++){
              //在一行检查5
        }
    }    返回hasWon;
}公共静态布尔computerHasWon(){
    布尔hasWon = FALSE;    的for(int i = 0; I&LT;大小;我++){
        对于(INT J = 0; J&LT;大小; J ++){
              //在一行检查5
        }
    }    返回hasWon;
}

当然,接下来的问题是如何我创建这个方法?? 说不上来,如果你有这个问题,但做一个快速检查<一href=\"http://stackoverflow.com/questions/20399904/array-programming-check-winner-in-a-tic-tac-toe-game-for-an-nxn-board-with-n-p?rq=1\">here <一href=\"http://stackoverflow.com/questions/23257871/finding-the-winner-in-tic-tac-toe-java-using-2-d-arrays?rq=1\">here和这里你会发现一些想法。


Add(添加):

为了澄清,我会做一个函数返回一个 INT 而不是布尔值,以检查是否游戏使用一些常量完成:

 私人最终诠释DRAW = 0;
私人最终诠释计算机= 1;
私人最终诠释PLAYER = 2;私人诠释isGameFinished(){
    如果(isDraw())返回DRAW;
    否则,如果(computerHasWon())返回计算机;
    否则,如果(playerHasWon())返回播放器;
}

然后,只需一个开关的情况下检查<一href=\"http://stackoverflow.com/questions/22823395/java-how-can-i-break-a-while-loop-under-a-switch-statement\">(check这里如何突破,而INSITE的同时)

 循环:while(TRUE){
    //其他stufff
    开关(isGameFinished()){
    案例PLAYER:
        通信System.err.println(你赢!);
        打破循环;
    案例计算机:
        通信System.err.println(计算机WINS \\ n您LOOSE !!!);
        打破循环;
    案例DRW:
        通信System.err.println(这是一场平局);
        打破循环;
}

Earlier post: How do I make my tictactoe program scalable

I have tried to make a Tic Tac Toe program (human vs computer) scalable (the board size can be changed). I had major problems earlier but fixed most of them.

The game's rules are basic Tic Tac Toe but one different rule is that no matter how large the board is (when >= 5) the player or computer only need five marks in a row to win.

Now the only gamebreaking problem with my program is determining who wins the game. It is only possible that the game ends a 'draw' at the moment. (Also I have not implemented the ">= 5" yet).

Specific problem explanation is that I need to determine a winner and end screen for something like "computer wins" and/or "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] == ' ');
    }
}

解决方案

You have already the loop to play, so, in each iteration, in the same way you check if the game isDraw(), check also if some of the players won:

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

After create the needed methods:

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

Next question of course is HOW DO I CREATE THIS METHODS?? dunno if you have problems with this, but doing a fast check here here and here you will find some ideas.


ADD ON:

In order to clarify, I would make a function returning an int instead booleans, to check if the game is finished using some constants:

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

Then simply check with a switch case (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;
}

这篇关于我如何确定我的井字程序赢家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆