Game Development Reference
Tackling random numbers
You'll tackle the random number problem first because you'll almost certainly find yourself needing to
use random numbers in most of your game projects. AS3.0 has a built-in class called I]pd that includes
quite a few methods that are useful for manipulating numbers. One of these is the n]j`ki method,
which generates a random number between 0 and 1. Here's what it looks like:
You can assign this random number to a variable just as you assign other values to variables, as in this
The fictitious n]j`kiR]ne]^ha is now assigned a random number between 0 and 1, with up to 16 deci-
mal places. So it could be anything; for example, 0.3669164208535294 or 0.5185672459021346.
What use is a random number between 0 and 1 with 16 decimal places, you ask? Well, practically none
whatsoever. Fortunately, you can do a bit of tweaking to get something more useful.
First, random numbers for games usually need to be integers—whole numbers. All those decimal
places have got to go! Can you imagine what a nightmare the guessing game would be to play if the
mystery number were something like 33.6093155708325684? If you chop off all those decimals, you'll
have something useful, such as 33, which is within the realms of most human lifetimes to be able to
The I]pd class fortunately has a few built-in methods that can help us round decimals up or down:
I]pd*nkqj`: Can be used to round numbers either up or down. For example, I]pd*nkqj`$/*0%
returns a value of /. I]pd*nkqj`$/*4% returns 0. I]pd*nkqj`$/*1% also returns 0.
I]pd*bhkkn: Always rounds numbers down. I]pd*bhkkn$/*.% returns /. I]pd*bhkkn$/*5% also
I]pd*_aeh: Always rounds numbers up. I]pd*_aeh$/*.% returns 0, and I]pd*_aeh$/*5% also
returns 0. (_aeh is short for ceiling . Ceilings are up; floors are down. Make sense?)
To use any of these methods along with the I]pd*n]j`ki method, you need to use a format that looks
Think about what this is doing. I]pd*n]j`ki$% generates a random number between 0 and 1 with loads
of decimals. So imagine that it came up with a deliciously useless number such as 0.6781340985784098.
You could pretend that the preceding line of code now looks like this:
How would you round that number? You'd round it up, and the result would be the following: