Originally posted by Holly Leery:
I was wondering if someone could explain the Random Method to me. I want to use it where in a java applet a number between 0 to 3 is randomly picked to make a dot on a grid go north south east west. I will put it in a loop that runs 100 times to make this dot move around the grid. With this I will use a switch statement, but I am some what lost. Any help?
Example for java.util.Random class :
This will help you.
Random method is used to generate a number greater than or equal to 0.0 and less than 1.0
The above example is generated between 0 to 3
For the following example is 1 to 3
You can also read more about Math.random()
and also with Math.round()
As I can not post the linkage of Math.random() and Math.round() because Mapraputa's
Hope this help
[ September 30, 2004: Message edited by: siu chung man ]
I'll leave it to you to get that into real Java syntax. Are you familiar with the convention of constant variables in all caps? I'm implying there is a line somehwere something like:
private static final int UP = 0;
Did your assignment say anything about the size of your play area? What if you move off the edge of the screen? There's some interesting math at play - google for Drunkard's Walk for details - that always makes this thing go off the screen. (Or is it just the quality of Random?) You'd expect the average location to hang round the middle but don't count on it.
Every time you change position I think you'll want something to "erase" the old ant and draw a new one. Otherwise it will be hard to see where he's going. If you want to leave old ants around to see the path taken, you might redraw the current position in black then draw the new position in red.
What do you want to happen when the ant hits an edge? Say it's in the right-most column and random gives you a right. Maybe just stay put and hope the next time through the loop gets a different random direction? Should you count that in your 100 moves? Maybe it could wrap off the right side into the leftmost column. Any other cool ideas?
Basically it will mean that if you have randomly been assigned an illegal move you will need to generate new random directions until a legal move is generated.