Random numbers

To create a random number you use this line of code.

int Number= (arc4random() % ModNumber)+Firstnumber;

so this is relatively simple, arc4ramdom() will create a random int -2147483648 to 2147483647. Then we mod, when we mod an integer it gives us the remainder. If we where to mod 5%2 we would get 1, because 2 goes into 5, 2 times and we are then left with the remainder of 1. So for the Mod Number you will replace it with how many numbers you want to get out of the random number. If you wanted a dice to roll you would want 6 numbers, so your code would look like following.

int Number= (arc4random() % 6);

The only problem with the code is it creates a random number 0-5. We fix it by adding a one to the end.

int Number= (arc4random() % 6)+1;

Now the code generates a number 1-6. The number you add to the end is the first num you want in the range of random numbers, and the ModNumber is how many numbers you want in the range.

Copy right Britney Lee Johnson August 2010.

This entry was posted in cocos2d. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>