-
[RESOLVED] What's wrong?
I'm really stuck and don't know what to do
Code:
public Block (int x, int y) {
pt = new Point(x, y) ;
color=colors[new Random().nextInt(colors.length)];
}
This code is a constructor, my problem is in the second line "Random color"
it's supposed to select a random color for each block from an array containing 4 colors
here is how I call it:
Code:
for (int i = 0 ; i < blocks.length ; i++) {
for (int j = 0 ; j < blocks[i].length ; j++) {
blocks[i][j] = new Block(i*20, j*20) ;
}
}
my problem is, when I call it from the paint method (Applet) blocks[i][j].paint(g):
Code:
public void paint (Graphics g) {
g.setColor(this.color) ;
g.fill3DRect(pt.x, pt.y, 15, 15, true) ;
}
All blocks are the same color, I tried adding System...print to check if the problem is in the paint but it's not, all randoms are the same value.
Any help would be great
-
Re: What's wrong?
My guess is that each new random object produces the same sequence of numbers (probably seeded using the current time). You should use a single random object for all blocks. Something like:
Code:
class MyRandom {
private static Random random;
public static int random(int max) {
if (!random) random = new Random();
return random.nextInt(max);
}
}
-
Re: What's wrong?
You're "something like" got me banging my head..
But thank you for the idea (seeded using the current time). I didn't think of that
-
Re: What's wrong?
How many times are you calling this constructor? I assume it's once per block? The problem with a random number generator is that it's not really random. If you don't use the same random generator then you will probably get ALMOST identical results each time.
I would either make the random number generator static for the class, or wherever you have this code:
Code:
for (int i = 0 ; i < blocks.length ; i++) {
for (int j = 0 ; j < blocks[i].length ; j++) {
blocks[i][j] = new Block(i*20, j*20) ;
}
}
Make the random number generator global and set the color through the loop:
Code:
Random r = new Random();
for (int i = 0 ; i < blocks.length ; i++) {
for (int j = 0 ; j < blocks[i].length ; j++) {
blocks[i][j] = new Block(i*20, j*20) ;
blocks[i][j].setColor(colors[r.nextInt(colors.length)];
}
}
That would require you take out some coding from your blocks class, so I don't know if you want to do that or not. Try making the random generator a static global variable and see what happens.
-
Re: What's wrong?
It might also be useful to know that the random generator (if the same object instance) will not select the same number twice unless all numbers have been touched once.
-
Re: What's wrong?
I've created a static Random for the Block class and it works now, thank you very much