TIC-TAC-TOE计算机逻辑

发布于 2025-02-12 09:46:44 字数 6447 浏览 0 评论 0原文

我正在尝试制作一款TIC-TAC-TOE游戏,用户可以选择他们想玩单人游戏还是两个玩家游戏。我已经让他们俩都在工作,但是正在试图使AI对其放置“ O”的位置具有一定的逻辑。当前,计算机随机生成一行和列,如果数组中的相应正方形具有“ - ”(表示它是空的),它将用“ O”填充它。我正在寻找一种简单的方法来浏览2D阵列,并看到它是否有胜利。如果没有,它应该检查用户是否可以获胜并防止他们获胜。如果它们都不是真实的,那么它应该随机选择一个正方形并使其移动。另外,我对Java是相对较新的,因此,如果我做错了什么,请让我知道该怎么做,以便我可以修复并提高自己的技能。这是代码。

驱动程序文件:

public class DriverTicTacToe
{
   public static void main(String[] args)
   {
      TicTacToe game = new TicTacToe(); //creates an object
      game.play();//this simulates the whole game from asking the number of players all the way to printing the win message.
   }
}

资源文件:

import java.util.Scanner;

public class TicTacToe
{  
   //declares the symbol character that will hold either "x" or "o"
   char symbol;
   
   //create a 3*3 array of characters that acts as the board in the game.
   char[][] board = new char[3][3];
   //declares multiple integers used throughout the game simulation
   int player = 1, row, col, numPlayers;
   //creates scanner object used to get user input
   Scanner kb = new Scanner(System.in);
   
   //constructor that fill the board array with dashes.
   public TicTacToe()
   {
      for(int i = 0; i <3; i++)
      {
         for(int j = 0; j < 3; j++)
            board[i][j] = '-';
      }   
   }
   
   //asks the user for the number of players
   public int getNumPlayers()
   {
      System.out.println("How many players are there (1 or 2)");
      numPlayers = kb.nextInt();
      return numPlayers;
   }
   
   //used to cycle through "x" and "o"
   public void setSymbol(int playerNumber)
   {
      if (playerNumber % 2 == 1)
         symbol = 'x';
      else 
         symbol = 'o';
   }  
   
   //prints the array as a 3*3 board
   public void printBoard()
   {
      for(int i = 0; i < 3; i++)
      {
         for(int j = 0; j<3; j++)
            System.out.print(board[i][j]);
         System.out.println();
      }   
   }
   
   //checks if there is an empty place on the board
   public boolean boardNotFilled()
   {
      for(int i = 0; i < 3; i++)
      {
         for(int j = 0; j < 3; j++)
         {
            if(board[i][j] == '-') 
               return true;
         }
      }
      return false;
    }
   
   //checks if someone has won the game  
   public boolean checkGameOn()
   {
      if(board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '-')
         return false;
      else if(board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '-')
         return false;
      else if(board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '-')
         return false;
      else if(board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '-')
         return false;
      else if(board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-')
         return false;
      else if(board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '-')
         return false;
      else if(board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-')
         return false;
      else if(board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '-')
         return false;
      else
         return true;
   }
   
  //ask user for a row. The number is decreased by one to get to the corresponding index
  public void getRow()
  {
     System.out.println("Enter a row: ");
     row = kb.nextInt() - 1;
     //return row;
  } 
  
  //ask user for a column. The number is decreased by one to get to the corresponding index
  public void getColumn()
  {
     System.out.println("Enter a column: ");
     col = kb.nextInt() - 1;
     //return col;
  } 
  
  //switches the value at a point from a "-" to the symbol
  public boolean switchVal()
  {
      board[row][col] = symbol;
  }
  
  //selects to random numbers for a computer move. Keeps running until an empty index is found.
  public void compMove()
  {
     while(true)
     {
        row = (int)(Math.random()*3);
        col = (int)(Math.random()*3);
        if(board[row][col] == '-')
           break;
     }
  }
  
  //Prints winner for a 2 player game
  public void winStatement()
  {
     if(symbol == 'x')
        System.out.println("Congratulations Player 1, you win");
     else
       System.out.println("Congratulations Player 2, you win");
  }
  
  //simulates a single player game
  public void singlePlayer()
  {
     int playerNum = 1;
      
      TicTacToe game = new TicTacToe();
      
      while (game.checkGameOn() && game.boardNotFilled())
      {
         game.printBoard();
         if(playerNum != 1)
         {
            System.out.println();
            System.out.println("I made my move! Your turn.");
            System.out.println(); 
         }
         game.setSymbol(playerNum);
         game.getRow();
         game.getColumn();
         game.switchVal();
         game.printBoard();
         System.out.println();
         System.out.println("Computer's turn!");
         System.out.println();
         playerNum++;
         game.setSymbol(playerNum);
         game.compMove();
         game.switchVal();
         playerNum++;
      }
      
      game.printBoard();
      if(game.boardNotFilled())
         System.out.println("Congratulations, you win!");
      else
         System.out.println("Game Tied");
  }
  
  //simulates a two player game
  public void twoPlayer()
  {
     int playerNum = 1;
      
      TicTacToe game = new TicTacToe();
      
      while (game.checkGameOn() && game.boardNotFilled())
      {
         game.printBoard();
         game.setSymbol(playerNum);
         game.getRow();
         game.getColumn();
         game.switchVal();
         playerNum++;
      }
      
      game.printBoard();
      if(game.boardNotFilled())
         game.winStatement();
      else
         System.out.println("Game Tied");
  }
  
  //simulates everything from asking user how many players all the way to running the game.
  public void play()
  {
     TicTacToe game = new TicTacToe();
     int  numPlayers = game.getNumPlayers();
     if(numPlayers == 1)
        game.singlePlayer();
     else if(numPlayers == 2)
        game.twoPlayer();
     else
        System.out.println("Error");
  }
}

I am trying to make a Tic-tac-toe game where the user gets to select whether they would like to play a single player game or a two player game. I have gotten both of them to work but am trying to make the AI have some logic as to where it places its "o". Currently, the computer randomly generates a row and a column and if the corresponding square in the array has a "-" (signifying that it is empty), it will fill it with an "o". I am looking for a simple way to go through the 2d array and sees if it has a way to win. If not, it should check if the user can win and prevent them from winning. If none of them are true, then it should randomly select a square and make it's move. Also, I am relatively new to Java so if I am doing something wrong, please let me know how to do it so that I can fix it and improve my own skills. Here is the code.

Driver File:

public class DriverTicTacToe
{
   public static void main(String[] args)
   {
      TicTacToe game = new TicTacToe(); //creates an object
      game.play();//this simulates the whole game from asking the number of players all the way to printing the win message.
   }
}

Resource File:

import java.util.Scanner;

public class TicTacToe
{  
   //declares the symbol character that will hold either "x" or "o"
   char symbol;
   
   //create a 3*3 array of characters that acts as the board in the game.
   char[][] board = new char[3][3];
   //declares multiple integers used throughout the game simulation
   int player = 1, row, col, numPlayers;
   //creates scanner object used to get user input
   Scanner kb = new Scanner(System.in);
   
   //constructor that fill the board array with dashes.
   public TicTacToe()
   {
      for(int i = 0; i <3; i++)
      {
         for(int j = 0; j < 3; j++)
            board[i][j] = '-';
      }   
   }
   
   //asks the user for the number of players
   public int getNumPlayers()
   {
      System.out.println("How many players are there (1 or 2)");
      numPlayers = kb.nextInt();
      return numPlayers;
   }
   
   //used to cycle through "x" and "o"
   public void setSymbol(int playerNumber)
   {
      if (playerNumber % 2 == 1)
         symbol = 'x';
      else 
         symbol = 'o';
   }  
   
   //prints the array as a 3*3 board
   public void printBoard()
   {
      for(int i = 0; i < 3; i++)
      {
         for(int j = 0; j<3; j++)
            System.out.print(board[i][j]);
         System.out.println();
      }   
   }
   
   //checks if there is an empty place on the board
   public boolean boardNotFilled()
   {
      for(int i = 0; i < 3; i++)
      {
         for(int j = 0; j < 3; j++)
         {
            if(board[i][j] == '-') 
               return true;
         }
      }
      return false;
    }
   
   //checks if someone has won the game  
   public boolean checkGameOn()
   {
      if(board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '-')
         return false;
      else if(board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '-')
         return false;
      else if(board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '-')
         return false;
      else if(board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '-')
         return false;
      else if(board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-')
         return false;
      else if(board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '-')
         return false;
      else if(board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-')
         return false;
      else if(board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '-')
         return false;
      else
         return true;
   }
   
  //ask user for a row. The number is decreased by one to get to the corresponding index
  public void getRow()
  {
     System.out.println("Enter a row: ");
     row = kb.nextInt() - 1;
     //return row;
  } 
  
  //ask user for a column. The number is decreased by one to get to the corresponding index
  public void getColumn()
  {
     System.out.println("Enter a column: ");
     col = kb.nextInt() - 1;
     //return col;
  } 
  
  //switches the value at a point from a "-" to the symbol
  public boolean switchVal()
  {
      board[row][col] = symbol;
  }
  
  //selects to random numbers for a computer move. Keeps running until an empty index is found.
  public void compMove()
  {
     while(true)
     {
        row = (int)(Math.random()*3);
        col = (int)(Math.random()*3);
        if(board[row][col] == '-')
           break;
     }
  }
  
  //Prints winner for a 2 player game
  public void winStatement()
  {
     if(symbol == 'x')
        System.out.println("Congratulations Player 1, you win");
     else
       System.out.println("Congratulations Player 2, you win");
  }
  
  //simulates a single player game
  public void singlePlayer()
  {
     int playerNum = 1;
      
      TicTacToe game = new TicTacToe();
      
      while (game.checkGameOn() && game.boardNotFilled())
      {
         game.printBoard();
         if(playerNum != 1)
         {
            System.out.println();
            System.out.println("I made my move! Your turn.");
            System.out.println(); 
         }
         game.setSymbol(playerNum);
         game.getRow();
         game.getColumn();
         game.switchVal();
         game.printBoard();
         System.out.println();
         System.out.println("Computer's turn!");
         System.out.println();
         playerNum++;
         game.setSymbol(playerNum);
         game.compMove();
         game.switchVal();
         playerNum++;
      }
      
      game.printBoard();
      if(game.boardNotFilled())
         System.out.println("Congratulations, you win!");
      else
         System.out.println("Game Tied");
  }
  
  //simulates a two player game
  public void twoPlayer()
  {
     int playerNum = 1;
      
      TicTacToe game = new TicTacToe();
      
      while (game.checkGameOn() && game.boardNotFilled())
      {
         game.printBoard();
         game.setSymbol(playerNum);
         game.getRow();
         game.getColumn();
         game.switchVal();
         playerNum++;
      }
      
      game.printBoard();
      if(game.boardNotFilled())
         game.winStatement();
      else
         System.out.println("Game Tied");
  }
  
  //simulates everything from asking user how many players all the way to running the game.
  public void play()
  {
     TicTacToe game = new TicTacToe();
     int  numPlayers = game.getNumPlayers();
     if(numPlayers == 1)
        game.singlePlayer();
     else if(numPlayers == 2)
        game.twoPlayer();
     else
        System.out.println("Error");
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无所谓啦 2025-02-19 09:46:44

您如何在CheckGameon方法中添加板作为参数,然后您可以循环循环并检查板的修改版本,如果它是获胜的动作,在这种情况下,计算机想要绘制其O。

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if(board[i][j] != '-')continue;
            board[i][j] = 'x';
            if (checkGameOn(board)) board[i][j] = 'o';
            else board2[i][j] = '-';
        }
    }

How about you add board as a parameter in the checkGameOn method, then you can loop through and check for modified versions of your board if its a winning move and in that case thats where the computer wants draw its O.

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if(board[i][j] != '-')continue;
            board[i][j] = 'x';
            if (checkGameOn(board)) board[i][j] = 'o';
            else board2[i][j] = '-';
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文