I’d do something like this
//Screen size 800x600
public int treeCount = 30;
public int[] treeLoc = new int[2*treeCount];
Random r = new Random();
public void RandomizeTreeLocs(){ //needs to be called once, during init
for(int i=0; i<(2*treeCount);i+=2){
treeLoc[i] = r.nextInt(800); // X location
treeLoc[i+1] = r.nextInt(600); // Y Location
}
}
public void drawTrees(){
//blah blah portion
for(int i=0; i<(2*treeCount);i+=2){
g.drawImage( treePicture, treeLoc[i], treeLoc[i+1],null);
}
}
//Main Loop
if(keyPressed == R){
RandomizeTreeLocs();
}
another method, although in my opinion, less efficient.
//Screen size 800x600
public int tree = 30;
public int[][] treeLoc = new int[800][600];
Random r = new Random();
//treePicture array contains an array of different image types for different trees/rocks/grass
public void RandomizeTreeLocs(){ //needs to be called once, during init
for(int i=0; i<tree;i++){
treeLoc[r.nextInt(800)][r.nextInt(600)] = 1;
// use different numbers for different "types of trees"
}
}
public void drawTrees(){
//blah blah portion
for(int i=0; i<800;i++){
for(int j=0; j<600;j++){
if( treeLoc[i][j] > 0){
//g.drawImage( treePicture[ treeLoc[i][j] ], i, j,null);
}
}
}
}
//Main Loop
/*if(keyPressed == R){
RandomizeTreeLocs();
}
There are better ways to write the above, these are just some quickly thrown together ideas.
Depending on the type of game and what all you need/want from it.
I think making the tree an entity, with x/y coordinates inside of it, perhaps with other variables and functions.
Then just maintaining a EntityList of all the trees, You could also with entities, have them check for distance to other trees and remove themselves if they are too close, or perhaps change the type of tree,(i.e. if 1 tree has 5 trees close to it, make itself a baby tiny tree) if the tree has nothing close to it, make it a bigger/older tree?