Game Development Reference
In-Depth Information
Here's another way of looking at it. Let's say that the random number is 0.3378208608542148. That
would mean the code will look like this:
Multiplied by 100, the random number will then look like this:
The decimal point is just moved two spaces to the right, giving a nice big number to work with. But
you still have the problem of those infuriating decimals to deal with! Not to worry; I]pd*_aeh comes
to the rescue by rounding the whole thing up. So the result is very satisfying:
Perfect for the number guessing game! Figure 5-20 shows an example of this process in action.
Figure 5-20. From useless to useful: using Math.random and
Math.ceil to help generate random whole numbers within
a specific range
You can use this same format for any range of numbers simply by changing the number that you mul-
tiply the random number by. Here are some examples:
I]pd*_aeh$I]pd*n]j`ki$%&-,% generates a random number between 1 and 10.
I]pd*_aeh$I]pd*n]j`ki$%&.3% generates a random number between 1 and 27.
I]pd*_aeh$I]pd*n]j`ki$%&1% generates a random number between 1 and 5.
The reason why using I]pd*_aeh starts the range of random numbers with 1 is that any number less
than 1, such as 0.23, will be rounded up to 1.That saves you from having to deal with values of 0, which
are often not useful for the ranges of numbers you'll be looking for in your games. If you do want 0 to
Search Nedrilad ::

Custom Search