Game Development Reference
In-Depth Information
But what would happen if the random number were lower, like this?
I]pd*nkqj`\$,*.015234/,43,/-.1%
It would be rounded down to this:
,
This means that you can use the line of code, I]pd*nkqj`\$I]pd*n]j`ki\$%%, to generate a random
number that has a 50% chance of being either 0 or 1. Not yet quite what you're looking for in the
game, but not entirely useless, either. There will be many instances where calculating a 50% chance of
something happening will be really useful in your games, and you can use this little snippet of code
to do exactly that.
In fact, you can use the snippet to generate random >kkha]j (pnqa/b]hoa) values.
Let's pretend that you have a >kkha]j variable called n]ejPk`]u. You could initialize
it with a value of b]hoa:
n]ejPk`]u9b]hoa7
Oh, if only that were true! So to make it a little more realistic, you can give it a 50%
chance of being either pnqa or b]hoa. All you need to do is use the I]pd*nkqj`\$I]pd*
n]j`ki\$%% code snippet in an eb+ahoa statement and compare it against a value of -.
Here's what the code might look like:
eb\$I]pd*nkqj`\$I]pd*n]j`ki\$%%99-%
w
n]ejPk`]u9pnqa7
y
ahoa
w
n]ejPk`]u9b]hoa7
y
I]pd*nkqj`\$I]pd*n]j`ki\$%% has an exactly 50% chance of generating either the
number - or ,. If it happens to be -, the first directive runs and n]ejPk`]u becomes
pnqa. If it's ,, no rain today!
So a random number between 0 and 1 is slightly more useful, but not exactly what you're looking for
in the game. How can you get a random number between 1 and 100? Here's how:
I]pd*_aeh\$I]pd*n]j`ki\$%&-,,%
The asterisk is AS3.0's multiplication operator . &-,, means multiplied by 100 . This line of code mul-
tiplies the random number by 100 and then uses I]pd*_aeh to round it up so the lowest number it can
possibly be is 1. That gives a perfect random whole number that falls within the range of 1 to 100.