Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomize tictactoe

Tags:

java

eclipse

A while I did an assignment creating a tictactoe program through eclipse. It works well enough, with me clicking empty boxes to place O's, and the program inputting X's afterward. However, I was using a pretty simple code for the placement of X's:

 public int putX(){
 for(int i=0; i<3;i++)
  for(int j = 0;j<3;j++) {
     if(position[i][j]==' ') {
       position[i][j]='X';
       return 0;
     }
  }
  return -1; //some error occurred. This is odd. No cells were free.
 }

Because of this, the X's are just placed in the row of each column, going down until the next column. Can someone show me a simple way to randomize this program?

like image 994
CJH1955958 Avatar asked Mar 26 '26 04:03

CJH1955958


1 Answers

What we want to do is generate an array of all the possible points, and pick one of those points at random. We use a for loop to iterate through all points in the 3x3 array, and add the valid ones to our temporary array, and then we choose a random index, and place an X there.

String[] list = new String[9]; // maximum 9 points
int size = 0;

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        if(position[i][j] == ' ') {
            list[size] = "" + i + j;
            size++;
        }
    }
}

int index = (int) (Math.random() * (size+1));
position[Integer.parseInt(list[index].charAt(0))][Integer.parseInt(list[index].charAt(1))] = 'X';

Alternatively, instead of storing the x,y coordinates of the point in a String we could store them in a java.awt.Point like so:

Point[] list = new Point[9]; // maximum 9 points
int size = 0;

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        if(position[i][j] == ' ') {
            list[size] = new Point(i, j);
            size++;
        }
    }
}

int index = (int) (Math.random() * (size+1));
position[list[index].getX()][list[index].getY()] = 'X';

As you can see, the code for using a Point is practically the same, but instead of parsing the coordinates out of the String, we can just access them directly from the Class.

You should also check to make sure that there are some elements left, by checking if size is still 0 after the for loop. If so, you should probably return -1 (what your existing code does). Otherwise, at the end of the whole code return 0.

like image 129
Vineet Kosaraju Avatar answered Mar 28 '26 17:03

Vineet Kosaraju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!