jeudi 7 février 2019

Randomly draw circles on 2D board within a given range of coordinates

How can I randomly place circles on a 2D array board so that they fit in a defined zone instead of the entire board?

It's a 100x100 size and I can randomly draw those circles but they are drawn randomly on the entire board, how do I specify a range of coordinates where they can be drawn instead of filling the whole board?

The code below generates random circles (red or blue):

    //...
    int count = 50; //Declared in the onCreate() method

     private void drawRandomly(int count) {
       Random random = new Random();
       boolean playerTurns = false;

       try {
           for (int i = 0; i < count; i++) {
                int x = random.nextInt(99);
                int y = random.nextInt(99);
                board[x][y] = flipColors ? red : blue;
                flipColors = !flipColors;

           }
       } catch(ArrayIndexOutOfBoundsException e){
           e.printStackTrace();

       }

   }

I tried specifying a range with the code below, but hitting an ArrayIndexOutOfBounds exception:

int count = 15; // declared in the onCreate() method

 private void drawRandomly(int count) {
   Random random = new Random();
   boolean flipColors = false;

   try {
       for (int i = 0; i < count; i++) {
           for (int j = 0; j < count; j++) {
               if(i < 24 || i < 74){
                   if(j < 24 || j < 74){
                       int x = random.nextInt(99);
                       int y = random.nextInt(99);
                       board[x][y] = flipColors ? red : blue;
                       flipColors = !flipColors;
                   }
               }

           }
       }
   } catch(ArrayIndexOutOfBoundsException e){
       e.printStackTrace();

   }

   }

Basicaly, what I'm trying to achieve having the circles drawn at something like below:

board[47][47]= red;
board[46][47]= blue;
board[44][48] = red; 
board[44][49]= red;
board[45][47]= red;
board[45][48]= blue;
board[45][49]= blue;
board[45][50]= red;
board[46][50]= blue;
board[46][49]= red;
board[46][48]= red;
board[47][50]= blue;
board[47][48]= blue;
board[47][49]= red;
board[48][50]= red;
board[48][49]= red;
board[48][48]= red;
board[49][50]= blue;
board[48][51]= red;
board[43][50] = red; 
board[45][51] = red;
//.... depending on the value given to count

This is arbitrary manually placed and as you can see there is no random. distribution I'm a bit lost. Can somebody help me solve this? Still learning.




Aucun commentaire:

Enregistrer un commentaire