samedi 16 janvier 2021

Code using Java.util.Random for AI in Connect4 not working

I'm trying to make a connect4 game where you play against the computer but it isn't working correctly and I have no clue why not. Though it usually works the first two rounds. My pattern is a [7][15] array so that's why I need the 2*p+1.

1st) This won't allow the player place a yellow disk onto a red disk.

2nd) I receive the out of bounds error.

3rd) Sometimes the red disk is placed in random areas of the pattern. It also pushes the yellow disk to random places as well

public static void dropRed(String[][] str)
{
    //make lowest empty row of specific column red
   //randomly choose what column to drop disk
   System.out.println("Computer drop red into a column between 0 and 6");
   Random rand = new Random();
   int p = rand.nextInt(7);
   boolean found =  false;
   while(!found)
   {
      if(p==0|| p==1||p==2 ||p==3 ||p==4 ||p==5 ||p==6){
          for(int i = 5; i>=0; i--)
          {
              p = 2*p+1;
              if(str[i][p] == " "){
                  str[i][p] = "R";
                  break;}
          }
          found = true;
      }
      else{
          p = rand.nextInt();
      }
   }
}
public static void dropYellow(String[][] str)
{
   //same as above just for Yellow player
   System.out.println("Yellow player drop into a column between 0 and 6");
   Scanner sc = new Scanner(System.in);
   int col = sc.nextInt();
   boolean found = false;
   while(!found)
   {
      if(col==0|| col==1||col==2 ||col==3 ||col==4 ||col==5 ||col==6){
          for(int i = 5; i>=0; i--)
          {
              col = 2*col+1;
              if(str[i][col] == " "){
                  str[i][col] = "Y";
                  break;}
          }
          found = true;
      }
      else{
          System.out.println("Column doesn't exist. Drop into columns 0-6.");
          col= sc.nextInt();
      }
   }
}



Aucun commentaire:

Enregistrer un commentaire