Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tic Tac Toe游戏java只使用方法和2d数组_Java - Fatal编程技术网

Tic Tac Toe游戏java只使用方法和2d数组

Tic Tac Toe游戏java只使用方法和2d数组,java,Java,我还是不知道我做错了什么。我不知道如何将CPU的选择放入电路板。我确实让棋盘重新显示更新后的棋盘,并显示玩家选择的行和列。我需要有4个方法,我希望他们能做到这一点:1)displayBoard(采用2d数组中表示当前tic tac趾板的单传递参数。2.)makeAMove(采用2个传递参数:二维数组表示tictactoe板和玩家角色值('X'或'O'))。使用玩家角色选择的有效行和列更新数组。此方法不返回任何内容,只更新棋盘数组。3.)hasWon(接受2个传递的参数,表示Tictaoe棋盘和玩

我还是不知道我做错了什么。我不知道如何将CPU的选择放入电路板。我确实让棋盘重新显示更新后的棋盘,并显示玩家选择的行和列。我需要有4个方法,我希望他们能做到这一点:1)displayBoard(采用2d数组中表示当前tic tac趾板的单传递参数。2.)makeAMove(采用2个传递参数:二维数组表示tictactoe板和玩家角色值('X'或'O'))。使用玩家角色选择的有效行和列更新数组。此方法不返回任何内容,只更新棋盘数组。3.)hasWon(接受2个传递的参数,表示Tictaoe棋盘和玩家角色的二维数组('X'或'O')。如果玩家角色已赢,则返回TRUE,否则返回FALSE。4.)boardFull(获取表示TictoE板的二维数组的单个传递参数,如果所有单元格都被占用,则返回TRUE,否则返回false。这些区域将包含所有方法,其中一些方法是我以不确定的方式完成的(我知道)但是我试着在不使用任何课程的情况下先教自己它的逻辑。任何人都可以在这里发表评论,这将非常有帮助,因为我觉得在这一点上卡住了

import java.util.Scanner;

public class TicTacToe {

    public static void main(String[] args) {

        char[][] board = {{'1','2','3'}, {'4','5','6'}, {'7', '8', '9'}};
        // assign player to char value of X's only

        int play;

        char player = 'X';

        char cpu = 'O';

        int rowNumber;

        int columnNumber;

        int playerORow;
        int playerOcolumn;

        System.out.println("Welcome to tic, tac, toe!\n");

        System.out.println("Do you wish to play? 1 for yes, 2 for no ");

        Scanner input = new Scanner(System.in);

        play = input.nextInt();

        if(play != 1) {
            System.out.print("Invalid input, game will now EXIT thanks for playing!");
            System.exit(0);
        } // end if

            displayBoard(board);
            System.out.println("You are limited to X's only, good luck!");
            System.out.println("Please enter row (0-3) of your move: ");
            rowNumber = input.nextInt();
            System.out.println("Please enter column (1-3); of your move: ");
            columnNumber = input.nextInt();

            System.out.println("Please enter row (0-3) for player O: ");
            playerORow = input.nextInt();
            System.out.println("Please enter column (1-3); of your move: ");
            playerOcolumn = input.nextInt();


            if(board[rowNumber][columnNumber] != 'X' && board[rowNumber][columnNumber] != 'O')  {
                board[rowNumber][columnNumber] = player;
            } // end if

            else {

            }


            makeAMove(board, player);
            hasWon(board, player);
            boardFull(board);

} // end main method

// displays only the tic tac toe board
public static void displayBoard(char[][] board) {
    // loop for each row
    System.out.println(board[0][0] + " | " + board[0][1] + " | " + board[0][2] + "\n---------");
    System.out.println(board[1][0] + " | " + board[1][1] + " | " + board[1][2] + "\n---------");
    System.out.println(board[2][0] + " | " + board[2][1] + " | " + board[2][2] + "\n");

} // end display board method

// takes board array of values and updates it with valid row and column selected by player..does not return anything
public static void makeAMove(char[][] board, char player) {
    displayBoard(board);


} // end makeAMove method


// compare each element in board to see if the char value of 'X' exists
    // if exists then then return true, else return false
public static boolean hasWon(char[][] board, char player) {

        // Check if the player has won by checking winning conditions.
        if (board[0][0] == player && board[0][1] == player && board[0][2] == player || // 1st row
            board[1][0] == player && board[1][1] == player && board[1][2] == player || // 2nd row
            board[2][0] == player && board[2][1] == player && board[2][2] == player || // 3rd row
            board[0][0] == player && board[1][0] == player && board[2][0] == player || // 1st col.
            board[0][1] == player && board[1][1] == player && board[2][1] == player || // 2nd col.
            board[0][2] == player && board[1][2] == player && board[2][2] == player || // 3rd col.
            board[0][0] == player && board[1][1] == player && board[2][2] == player || // Diagonal          \ 
            board[2][0] == player && board[1][1] == player && board[0][2] == player) //   Diagonal      /

            return true;

        else {

            return false;
        }

} // end hasWon method

public static boolean boardFull(char [][] board) {

    if (board[0][0] != '1' && board[0][1] != '2' && board[0][2] != '3' &&
        board[1][0] != '4' && board[1][1] != '5' && board[1][2] != '6' &&
        board[2][0] != '7' && board[2][1] != '8' && board[2][2] != '9')

        return true;

    else {

        return false;
    } // end else

} // end boardFull method

}//结束类

您只需执行以下操作:

board[rowNumber][columnNumber] = player;
当然,您必须事先检查手机是否已被占用。如果是,请再次请求用户输入。我想这不会太难

除此之外,我建议您对代码进行一些改进:

  • 不要将两个播放器作为
    char
    类型,而是使用带有两个常量的
    X
    O
    enum播放器
    ,并改用
    Player[]

    enum Player {
        X, O;
    }
    
  • 无需使用
    '1',2',…
    初始化数组。现在默认情况下它们将为
    null

  • 与其将
    board
    作为局部变量,并将其传递给所有方法,不如将其作为类中的字段

  • 目前您的代码只进行了一次移动。为什么?而且,您甚至没有使用
    hasWon()
    boardFull()
    方法的返回值

  • 您可以将
    hasWon
    方法分为3个方法-
    hasWonHorizontal()
    hasWonVertical()
    hasWonDiagonal()
    。这将避免在同一方法中出现长
    条件。然后从
    hasWon()
    方法依次调用这3个方法


似乎您所需要做的就是检查播放器/cpu是否已经占用了该空间。如果没有,您应该只为数组中的该元素指定“X”或“O”

if(board[rowNumber][columnNumber] != 'X' && board[rowNumber][columnNumber] != 'O')
    {
        board[rowNumber][columnNumber] = player;
    }


您可能希望在main()函数中有某种循环,以连续允许玩家移动。当前的实现似乎只允许玩家移动一步。

首先,请直接回答您的问题:

// update board array with player row number and player column number
board[rowNumber][columnNumber] = player;
要显示新板,只需再次调用
displayBoard()
方法即可

您应该小心扫描仪,因为它不会验证输入。如果您得到的数字不在[0..2]中,您将在此处获得ArrayIndexOutOfBounds,因此您可能需要执行以下操作

do {
    System.out.println("Please enter row (0-3) of your move: ");
} while((rowNumber = input.nextInt()) < 0 || rowNumber > 2);
改进游戏的最佳方法是创建一个TicTacToe类和一个Main类。TicTacToe类包含棋盘、玩家、cpu以及一些显示和修改棋盘的方法,也可能包含切换玩家的方法,等等

然后,主类只需创建TicTacToe实例并运行一个主循环(我在上面发布的while循环),该循环会相应地对其进行修改。但现在只需继续使用您的方法,也许以后您可能需要进一步改进它。然后您可以回来考虑它

  There is fully code for tic tac toe game. I have refer this article 

公共类TicTacTOe{
int_行=3;
字符板[][]=新字符[\\行][\\行];
公共空白制作板(){

对于(int i=0;i=0&&r=0&&cha有人教过你如何创建和使用多个类吗?这个问题确实需要一些其他类。还没有。我们应该只使用多维数组。以下是本书中的说明,而不是讲师想要的。第254页,练习7.9。所以它不是一个家庭作业是吗?如果你这样做只是为了学习,那么我可以提出更多的建议。是的,如果你能做到这一点,那就太好了。b.c.我已经连续4个小时在做这件事了,只是不知道如何反复提示,验证一切,只说玩家赢了还是输了,然后打印棋盘是满的还是没满的。你是在编码这4个小时吗想想你需要什么?好吧,我的第一个建议来了。你应该先考虑“什么”,然后再考虑“如何”.在你触摸电脑之前,在纸上写下来。嗯,我现在对所有这些问题感到非常抱歉。首先,我不确定我该如何让玩家移动。其次,我在系统下放置了带有行和列编号的if语句。out语句“X将被放入…”还有,我将如何用程序实现这些返回语句?。分配一个变量来保存main中表示返回的每个方法?或者什么?天哪!好困惑的家伙们:/我想你们可以使用我们所有的三个答案来找出如何做到最好。使用我向你们介绍的循环思想,使用SchwartzCode的代码片段来检查电路板和place一个新的标记,如果它被占用,请再次询问(这可以通过do/while或while完成)。为了进一步改进变量字段,请改进一些方法,并可能按照Rohit Jain的建议使用枚举。返回值可用于分配变量或直接检查。例如:
boolean playerWon=hasWon(棋盘,玩家)
或直接检查:
如果(hasWon(board,player)){doIt();}
。我对验证输入有点困惑。它不需要说do{System.ou吗
  There is fully code for tic tac toe game. I have refer this article 
  public class TicTacTOe {
      int _row=3;
    char _board[][]=new char[_row][_row]; 
    public void makeBoard(){
     for (int i = 0; i <_row; i++) {
      for (int j = 0; j < _row; j++) {
       _board[i][j]='o';
      }

     }
    }
    boolean isValid(int r,int c){
     return((r>=0&&r<_row)&&(c>=0&&c<_row));
    }
    boolean isFill(int r,int c){
     return(_board[r][c]!='o');
    }
    public boolean gamePlay(int r ,int c,int playerNo){
     if (!(isValid(r,c))) {
      System.out.println("Enter Correct index");
      return true ;
     }
     if (isFill(r,c)) {
      System.out.println("This index already fill");
      return true;
     }
     if (playerNo==1) {
      _board[r][c]='*';
     } else {
            _board[r][c]='+';
     }
     return false;
    }

    boolean horizontalAndVerticalMatch(char ch,int n){
     // for row and col math
          boolean flag=true;
      for (int i = 0; i < _row; i++) {
           flag=true;
         for (int j = 0; j < _row; j++) {
          System.out.println("i="+i+"j="+j);
          char ch1=(n==1)?_board[i][j]:_board[j][i];
               if (ch1!=ch) {
                System.out.println("y");
        flag=false;
        break;
       }
        } 
         if (flag) {
          return flag;
      }
      }
     return flag; 
    }
    boolean majorDiagonal(char ch){
     return((_board[0][0]==ch)&&(_board[1][1]==ch)&&(_board[2][2]==ch));
    }
    boolean minorDiagonal(char ch){
     return((_board[2][0]==ch)&&(_board[1][1]==ch)&&(_board[0][2]==ch));
    }
    public boolean isGameOver(int PlayerNo){
     char ch;
     if (PlayerNo==1) {
       ch='*';
     } else {
       ch='+';
     }
     return(horizontalAndVerticalMatch(ch,1)||horizontalAndVerticalMatch(ch,2)||majorDiagonal(ch)||minorDiagonal(ch));
    }
    public void display(){
     for (int i = 0; i <_row; i++) {
      for (int j = 0; j < _row; j++) {
       System.out.print("     "+_board[i][j]);
      }
      System.out.println("");
     }
    } 

    }

    MainTicTacToe.java
    import java.util.Scanner;

    public class MainTicTacToe extends TicTacTOe {
     public static void main(String[] args) {
     TicTacTOe obj=new TicTacTOe();
     obj.makeBoard();
     obj.display();
     int r,c;
     Scanner input=new Scanner(System.in);
     while(true){
      boolean flag=true;
      while(flag){
       System.out.println("Player 1");
       System.out.println("enter row");
       r=input.nextInt();
       System.out.println("enter col");
       c=input.nextInt();
       flag=obj.gamePlay(r,c,1);
      }
      if (obj.isGameOver(1)) {
       obj.display();
       System.out.println("Player 1 Win Game");   
       break;
      }
      System.out.println("============");
      obj.display();
      flag=true;
      while(flag){
      System.out.println("Player 2");
      System.out.println("enter row");
      r=input.nextInt();
      System.out.println("enter col");
      c=input.nextInt();
      flag=obj.gamePlay(r,c,2);
      }
      if (obj.isGameOver(2)) {
       obj.display();
       System.out.println("Player 2 Win Game");   
       break;
      }
      System.out.println("============");
      obj.display();
     }
    }
    }