簡體   English   中英

井字游戲java只使用方法和二維數組

[英]Tic Tac Toe Game java using only methods and 2d arrays

仍然無法弄清楚我做錯了什么。 我不知道如何在板上選擇 CPU。 我確實讓電路板重新顯示更新后的電路板,其中包含玩家選擇的行和列。 我需要有 4 種方法和 id 喜歡他們來做這件事:1)displayBoard(采用代表當前井字棋板的二維數組的單個傳遞參數。2.)makeAMove(需要 2 個傳遞參數:代表 tictactoe 棋盤的二維數組和玩家角色值('X' 或 'O')。使用玩家角色選擇的有效行和列更新數組。此方法不返回任何內容,它只是更新棋盤數組。3.)hasWon(接受 2 個傳遞的參數,代表井字棋盤和玩家角色('X' 或 'O')的二維數組。如果玩家角色獲勝,則返回 TRUE,否則返回 FALSE。4.) boardFull(采用代表 TicTacToe 棋盤的二維數組的單個傳遞參數,如果返回 TRUE所有單元格都被占用了,否則是錯誤的。這些領域包括方法,其中一些我以低效的方式完成(我知道)但我試圖首先自學它的邏輯而不使用任何課程。任何人都可以發表評論在這里它會 gr 非常有幫助,因為我在這一點上感到卡住了。

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類型,不如使用一個enum Player ,它帶有兩個常量 - XO 並使用Player[]代替。

     enum Player { X, O; }
  • 無需使用'1', '2', ...初始化數組。 現在它們默認為null

  • 與其將board作為局部變量,並將其傳遞到所有方法中,不如將其作為類中的一個字段。

  • 目前,您的代碼只進行了一項操作。 為什么? 此外,您甚至沒有使用hasWon()boardFull()方法的返回值。

  • 您可以將hasWon方法分為 3 個方法 - hasWonHorizontal()hasWonVertical()hasWonDiagonal() 這將避免在同一方法中出現那么長的if條件。 然后從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);

和列相同以防止這種情況。 您還可以添加對字符串等的檢查。

游戲的其他一些方面:

  • 你想在每一步之前要求繼續嗎? 如果沒有,最好將其移至新方法並在開始時詢問一次。
  • 制作 board、player 和 cpu 類變量。 (或見下文)
  • 使用圍繞您的游戲狀態的循環,通過提供您的功能,您已經擁有了一個非常好的“狀態”機:

.

// a possible loop/game might look like this:
if(askForPlaying()) {
    char currentPlayer = player;
    while(!(boardFull(board) || hasWon(board, player) || hasWon(board, cpu)) {
        displayBoard(board);
        if(currentPlayer == player) {
            makeAMove(board, currentPlayer);
        } else {
            cpuMove(board, currentPlayer);
        }
        currentPlayer==player?cpu:player;
    }
    if(hasWon(board, player)) System.out.println("You won!");
    if(hasWon(board, player)) System.out.println("You lost!");
}

改進游戲的最佳方法是創建 TicTacToe 類和 Main 類。 TicTacToe 類將保存棋盤、播放器、cpu 和一些顯示棋盤和修改它的方法,也可能還可以切換播放器等。

然后 Main 類將只創建 TicTacToe 實例並運行一個主循環(我在上面發布的 while 循環),它會相應地修改它。 但是現在就采用你的方法,也許以后你可能想要進一步改進它。 然后你可以回來考慮一下。

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

來源:點擊這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM