lundi 3 décembre 2018

creating random objects on a board without overlapping in Java

We are trying to make several objects (TREES, represented by the number 10 and CATS (number 5)) appear on a board. Our code can make these numbers appear, but sometimes trees and cats overlap, so we don't have the number of objects we would want (two trees and three cats). How do we solve this?

final static int TREES = 10; 
final static int CAT = 5;

public void createRandomTiles() {
    ArrayList<Integer> list = new ArrayList<Integer>(); 
    for (int row = 0; row < counts.length; row++) {
        for (int col = 0; col < counts[0].length; col++) {
            list.add(row*100+col); 

        }

    }
        counts = new int [5] [5];
        int numTrees = 2; 

        for (int i = 0; i < numTrees; i++) {
            int choice = (int) (Math.random() * list.size());
            int choice2 = (int) (Math.random() * list.size());



            counts[list.get(choice) / 100] [list.get(choice) % 100] =     TREES;
            counts[list.get(choice2) / 100] [list.get(choice2) % 100] =      CAT;   
            }   


        }




Aucun commentaire:

Enregistrer un commentaire