使用二维数组的(Java)Tic Tac Toe游戏

使用二维数组的(Java)Tic Tac Toe游戏,java,arrays,Java,Arrays,在课堂上,我们的任务是创建一个二维数组,并围绕它创建一个井字游戏。我已经做了所有的事情,除了当整个棋盘都满了,比赛是平局时展示。我尝试了一些事情,但我没有找到解决办法,我需要一些帮助。。。这是我的密码: import java.util.Scanner; public class TicTacToe { public static void main(String[] args) { Scanner in = new Scanner(System.in);

在课堂上,我们的任务是创建一个二维数组,并围绕它创建一个井字游戏。我已经做了所有的事情,除了当整个棋盘都满了,比赛是平局时展示。我尝试了一些事情,但我没有找到解决办法,我需要一些帮助。。。这是我的密码:

import java.util.Scanner;

public class TicTacToe {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int row, column;
        char player = 'X';

        //create 2 dimensional array for tic tac toe board
        char[][] board = new char[3][3];
        char ch = '1';
        for (int i = 0; i < 3; i++){
            for (int j = 0; j < 3; j++) {
                board[i][j] = ch++;
            }
        }
        displayBoard(board);
        while(!winner(board) == true){

            //get input for row/column
            System.out.println("Enter a row and column (0, 1, or 2); for player " + player + ":");
            row = in.nextInt();
            column = in.nextInt();

            //occupied
            while (board[row][column] == 'X' || board[row][column] == 'O') {
                System.out.println("This spot is occupied. Please try again");
            }
            //place the X
            board[row][column] = player;
            displayBoard(board);

            if (winner(board)){
                System.out.println("Player " + player + " is the winner!");
            }

            //time to swap players after each go.
            if (player == 'O') {
                player = 'X';

            }
            else {
                player = 'O';
            }
            if (winner(board) == false) {
            System.out.println("The game is a draw. Please try again.");

        }

    }

    private static void displayBoard(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (j == board[i].length - 1) System.out.print(board[i][j]);
                else System.out.print( board[i][j] + " | ");
            }
            System.out.println();
        }


    }
    //method to determine whether there is an x or an o in the spot
    public static Boolean winner(char[][] board){
        for (int i = 0; i< board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'O' || board[i][j] == 'X') {
                    return false;
                }
            }
        }

        return (board[0][0] == board [0][1] && board[0][0] == board [0][2]) ||
            (board[0][0] == board [1][1] && board[0][0] == board [2][2]) ||
            (board[0][0] == board [1][0] && board[0][0] == board [2][0]) ||
            (board[2][0] == board [2][1] && board[2][0] == board [2][2]) ||
            (board[2][0] == board [1][1] && board[0][0] == board [0][2]) ||
            (board[0][2] == board [1][2] && board[0][2] == board [2][2]) ||
            (board[0][1] == board [1][1] && board[0][1] == board [2][1]) ||
            (board[1][0] == board [1][1] && board[1][0] == board [1][2]);
    }
}
import java.util.Scanner;
公共类Tictatcoe{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
int行,列;
字符播放器='X';
//为tic tac趾板创建二维阵列
字符[][]板=新字符[3][3];
char ch='1';
对于(int i=0;i<3;i++){
对于(int j=0;j<3;j++){
board[i][j]=ch++;
}
}
显示板;
而(!winner(board)=true){
//获取行/列的输入
System.out.println(“输入行和列(0、1或2);对于播放器“+player+”:”;
row=in.nextInt();
column=in.nextInt();
//占用
而(板[行][列]='X'| |板[行][列]=='O'){
System.out.println(“此位置已被占用,请重试”);
}
//放置X
棋盘[行][列]=玩家;
显示板;
if(优胜者(董事会)){
System.out.println(“玩家”+Player+“是赢家!”);
}
//每次围棋后交换球员的时间。
如果(玩家=='O'){
玩家='X';
}
否则{
玩家='O';
}
如果(优胜者(董事会)=错误){
System.out.println(“游戏是平局,请再试一次。”);
}
}
专用静态无效显示板(字符[][]板){
对于(int i=0;i
我希望输出表明,当电路板满时,它已满,但我什么也得不到。这是我输出的最后一行,正如您所看到的,我当前的策略不起作用,因为它继续要求输入。-->

输入行和列(0、1或2);对于播放器X: 2 0 X | O | X O | O | X X | X | O
输入行和列(0、1或2);对于播放器O:

您可以尝试合并以下新方法:

public Boolean boardFull()
{
    short count = 0;
    for(short i = 0; i < 3; i++){
        for(short j = 0; j < 3; j++){
            if(board[i][j] == ‘O’ || board[i][j] == ’X’){
                count++;
            } else {
                continue;
            }
        }
    }

    if(count == 9){
        return true;
    } else {
        return false;
    }
}
public Boolean boardFull()
{
短计数=0;
对于(短i=0;i<3;i++){
对于(短j=0;j<3;j++){
如果(板[i][j]='O'| |板[i][j]=='X'){
计数++;
}否则{
继续;
}
}
}
如果(计数=9){
返回true;
}否则{
返回false;
}
}
您可以使用if语句查看它是否返回true,然后在返回true时打印出来。

首先:

 while (board[row][column] == 'X' || board[row][column] == 'O') {
            System.out.println("This spot is occupied. Please try again");
        }
这将创建一个无限循环,因为
不应更改,您应该请求新的输入

但你有三种状态:

  • 未完成
用改变后的方法,你只有赢了才能完成比赛

原因:

 while(!winner(board) == true)
这使得游戏在没有赢家的情况下运行 (winner()将为false,因为所有内容都已占用或没有winner)

您可以编写一个类似于winner的方法,但它只检查板上是否有空点:

public static Boolean hasEmptySpot(char[][] board){
   //loop and check if there is empty space 
    for (int i = 0; i< board.length; i++) {
        for (int j = 0; j < board[0].length; j++) {
            if (board[i][j] != 'O' && board[i][j] != 'X') {
                return true;
            }
        }
    }
    return false;
}

//New code 
while(hasEmptySpot(board) || !winner(board)){
          //Your code for the game here
     ....
    }
为什么?? 因为你完成了比赛,你知道只有两种可能的结果——赢或平

我希望这对你有点帮助

编辑 我自己也犯了逻辑错误

第一个错误: 你仍然需要在游戏运行时检查是否有赢家忘记那一点

while(hasEmptySpot(board) || !winner(board)){
}
现在,当有赢家或没有空位时,这将退出游戏循环

第二个错误: 在haspendyspot()中

不是

在上面的示例中修复了它

很抱歉给您带来不便!

解决方案 不起作用的代码是您的
winner()
方法。如果至少有一个单元格被占用,它将始终返回
false
。您可以根据该方法的最后一部分继续

额外问题 单元检查回路 检查单元格是否被占用的代码将无限运行。您需要使用“if”语句而不是“while”循环:

if(board[row][column] == 'X' || board[row][column] == 'O'){
    System.out.println("This spot is occupied. Please try again");
    continue;
}
您的旧代码总是在检查1个单元格是否被占用时被卡住,它总是返回
true
,这使循环保持活动状态并淹没了您的控制台。
continue
语句将退出另一个“while”循环的当前迭代并开始新的迭代,从而请求新的输入

例外情况 老兄,这是很多未预料到的例外!如果我
while(!false==true) => while(true) 
public static Boolean hasEmptySpot(char[][] board){
   //loop and check if there is empty space 
    for (int i = 0; i< board.length; i++) {
        for (int j = 0; j < board[0].length; j++) {
            if (board[i][j] != 'O' && board[i][j] != 'X') {
                return true;
            }
        }
    }
    return false;
}

//New code 
while(hasEmptySpot(board) || !winner(board)){
          //Your code for the game here
     ....
    }
public static Boolean winner(char[][] board){
    return (board[0][0] == board [0][1] && board[0][0] == board [0][2]) ||
        (board[0][0] == board [1][1] && board[0][0] == board [2][2]) ||
        (board[0][0] == board [1][0] && board[0][0] == board [2][0]) ||
        (board[2][0] == board [2][1] && board[2][0] == board [2][2]) ||
        (board[2][0] == board [1][1] && board[0][0] == board [0][2]) ||
        (board[0][2] == board [1][2] && board[0][2] == board [2][2]) ||
        (board[0][1] == board [1][1] && board[0][1] == board [2][1]) ||
        (board[1][0] == board [1][1] && board[1][0] == board [1][2]);
}
while(hasEmptySpot(board) || !winner(board)){
}
 if (board[i][j] != 'O' && board[i][j] != 'X') {
                return true;
 if (board[i][j] != 'O' || board[i][j] != 'X') {
                return true;
if(board[row][column] == 'X' || board[row][column] == 'O'){
    System.out.println("This spot is occupied. Please try again");
    continue;
}
try {
    row = in.nextInt();
    column = in.nextInt();

    // Attempt to place player (an ArrayOutOfBoundsException could be thrown)
    if(board[row][column] == 'X' || board[row][column] == 'O'){
        System.out.println("This spot is occupied. Please try again");
        continue;
    }

    board[row][column] = player;
} catch(Exception e){
    System.out.println("I'm sorry, I didn't get that.");
    continue;
}
public static class Board {
    private char[][] spaces = new char[3][3];
    private int numMoves = 0;

    public void makeMove(int row, int col, char player) {
        if (spaces[row][col] == 'X' || spaces[row][col] == 'O') {
            System.out.println("This spot is occupied. Please try again");
        } else {
            spaces[row][col] = player;
            numMoves++;
        }
    }

    public boolean isFull() {
        return numMoves == 9;
    }

    public boolean hasWinner() {
        ...
    }

    public void display() {
        ...
    }
}
import java.util.Scanner;

public class TicTacToe {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int row, column;
        char player = 'X';

        //create 2 dimensional array for tic tac toe board
        char[][] board = new char[3][3];
        char ch = '1';
        for (int i = 0; i < 3; i++){
            for (int j = 0; j < 3; j++) {
                board[i][j] = ch++;
            }
        }
        displayBoard(board);
        while(!winner(board) == true){

            //get input for row/column
            System.out.println("Enter a row and column (0, 1, or 2); for player " + player + ":");
            row = in.nextInt();
            column = in.nextInt();

            //occupied
            while (board[row][column] == 'X' || board[row][column] == 'O') {
                System.out.println("This spot is occupied. Please try again");
            }
            //place the X
            board[row][column] = player;
            displayBoard(board);

            if (winner(board)){
                System.out.println("Player " + player + " is the winner!");
            }

            //time to swap players after each go.
            if (player == 'O') {
                player = 'X';

            }
            else {
                player = 'O';
            }
            if (winner(board) == false && !hasFreeSpace(board)) {
                System.out.println("The game is a draw. Please try again.");
            }
        }

        //Don't forget to close the scanner.
        in.close();

    }

    public static void displayBoard(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (j == board[i].length - 1) System.out.print(board[i][j]);
                else System.out.print( board[i][j] + " | ");
            }
            System.out.println();
        }
    }

    /**
     * Determines whether the board is completely occupied by X and O characters
     * @param board the board to search through
     * @return true if entire board is populated by X or O, false otherwise.
     */
    public static boolean hasFreeSpace(char[][] board){
        for (int i = 0; i< board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] != 'O' && board[i][j] != 'X') {
                    return true;
                }
            }
        }
        return false;
    }

    //method to determine whether there is a winner
    public static boolean winner(char[][] board){
        return isHorizontalWin(board) || isVerticalWin(board) || isDiagonalWin(board);
    }

    /**
     * Determines if there is a winner by checking each row for consecutive
     * matching tokens.
     * @return true if there is a winner horizontally, false otherwise.
     */
    private static boolean isHorizontalWin(char[][] board) {
        for(int row = 0; row < board.length; row++){
            if(isWin(board[row]))
                return true;
        }
        return false;
    }

    /**
     * Determines whether all of the buttons in the specified array have the 
     * same text and that the text is not empty string.
     * @param lineToProcess an array of buttons representing a line in the grid
     * @return true if all buttons in the array have the same non-empty text, false otherwise.
     */
    private static boolean isWin(char[] lineToProcess) {
        boolean foundWin = true;
        char prevChar = '-';
        for(char character: lineToProcess) {
            if(prevChar == '-')
                prevChar = character;
            if ('O' != character && 'X' != character) {
                foundWin = false;
                break;
            } else if (prevChar != character) {
                foundWin = false;
                break;
            }
        }
        return foundWin;
    }

    /**
     * Determines whether there is a winner by checking column for consecutive
     * matching tokens.
     * @return true if there is a vertical winner, false otherwise.
     */
    private static boolean isVerticalWin(char[][] board) {
        char[] column = null;
      //assuming all rows have same legnth (same number of cols in each row), use first row
        for(int col = 0; col < board[0].length; col++){
            column = new char[board[0].length]; 
            for(int row = 0; row < column.length; row++){
                column[row] = board[row][col];
            }
            if(isWin(column))
                return true;
        }
        return false;
    }

    /**
     * Determines if there is a winner by checking each diagonal for consecutive
     * matching tokens.
     * @return true if a diagonal winner exists, false otherwise.
     */
    private static boolean isDiagonalWin(char[][] board) {

        int row = 0, col = 0;
        int cols = board.length;
        int rows = board[0].length; //assuming all rows are equal length so just use the first one

        //Create a one-dimensional array to represent the diagonal. Use the lesser
        // of the rows or columns to set its size. If the grid is rectangular then
        // a diagonal will always be the size of the lesser of its two dimensions.
        int size = rows < cols ? rows : cols;
        char[] diagonal = new char[size];

        //Since we know the grid is a square we really could just check one of
        // these - either row or col, but I left both in here anyway.
        while (row < rows && col < cols) {
            diagonal[col] = board[row][col];

            row++;
            col++;
        }
        if (isWin(diagonal)) {
            return true;
        }


        row = rows - 1;
        col = 0;
        diagonal = new char[size];
        while (row >=0 && col < cols) {
            diagonal[col] = board[row][col];
            row--;
            col++;
        }
        return isWin(diagonal);

    }
}