Table of Contents
- Initializing Allegro
- Keyboard Input
- Drawing Graphics
- Playing Sound
- Drawing Text
- Regulating FPS
- Enumerations and Random Numbers
- Bounding Box Collision Detection
- Planning the Game
- Super Basic Game Structure
- Wrapping up
Part 8 – Enumerations and Random Numbers
Just a quick look at them in case you didn’t cover them in C++.
Enumerations are a handy way of representing numbers. Numbers are a lot smaller in size than strings. Maybe you want to use a number to represent the direction a player is pointing? Using a string would take too much space, and while you COULD use a char like ‘r’, ‘u’, ‘d’, ‘l’, it’s much easier to read if it’s something like if ( direction == UP )
Enums look like this:
If you don’t assign a number value to each one, it will still be assigned an arbitrary number. The reason you may use numbers for directions are to tell where in the tilestrip the image is.
This way, when you draw the character, you will crop the sprite out like this:
spritesheet_x = frame * width; spritesheet_y = currentDir * height;
Random numbers. What are they used for? Well, a lot. In this game, our stick will get random coordinates every time it’s picked up. In other games, it may generate an enemy location or even be used for AI (What do I feel like doing today? *rand()* I’m going to do option #3).
Seeding – what is it, and how do we do it
Since random numbers aren’t truly random and have to have a “seed” number to generate the numbers from, seeding is usually done to the current time. If you seed to a constant number, you’ll find that each time you run the program, you’ll get the same random numbers in the same order. You may want this, and you may not.
So here’s how you seed to the time:
Generating random numbers
Now to actually generate the random numbers, you will use rand(). However, this will create a number between 0 and 1 (some long decimal number), so how do you get it between the numbers you want?
This code will generate a random number between 0 and 9. If you want it from 1 to 10, then add +1 to the end of the expression.
% is for modulus, and is pretty interesting. It’s basically an expression to get the remainder from (int)rand() divided by 10. It also makes sure that if the value is above 10, it “wraps around” back to 0 and continues.
If you want to generate random coordinates for the stick, it should look something like this:
x = ( (int)rand() % 608 ); y = ( (int)rand() % 448 );
The screen is 640×480. If the stick’s x coordinate gets generated as 640, then it’s left side will be at that value and it will essentially be off the screen. This is why we subtract 32 from each of the values.
© Rachel J. Morris, 2009