Class enumerations
An enumeration is a list of all the possible values in a logical collection. C++ enumerations are a great way of, well, enumerating things. For example, if our game uses variables that can only be in a specific range of values and if those values could logically form a collection or a set, then enumerations are probably appropriate to use. They will make your code clearer and less error-prone.
To declare a class enumeration in C++, we can use these two keywords, enum class, together, followed by the name of the enumeration, followed by the values the enumeration can contain, enclosed in a pair of curly braces {...}.
As an example, examine the following enumeration declaration. Note that it is convention to declare the possible values from the enumeration in uppercase:
enum class zombieTypes {
REGULAR, RUNNER,
CRAWLER, SPITTER, BLOATER
};
Note that, at this point, we have not declared any instances of zombieType, just the type itself. If that sounds odd, think about it like this. SFML created the Sprite, RectangleShape, and RenderWindow classes, but to use any of those classes, we had to declare an object/instance of the class.
At this point, we have created a new type called zombieTypes, but we have no instances of it. So, let's do that now:
zombieType jeremy = zombieTypes::CRAWLER;
zombieType anna = zombieTypes::SPITTER;
zombieType diane = zombieTypes::BLOATER;
/*
Zombies are fictional creatures and any resemblance
to real people is entirely coincidental
*/
Next is a sneak preview of the type of code we will soon be adding to Timber!!!. We will want to track which side of the tree a branch or the player is on, so we will declare an enumeration called side, like this:
enum class side { LEFT, RIGHT, NONE };
We could position the player on the left like this:
// The player starts on the left
side playerSide = side::LEFT;
We could make the fourth level (arrays start from zero) of an array of branch positions have no branch at all, like this:
branchPositions[3] = side::NONE;
We can use enumerations in expressions as well:
if(branchPositions[5] == playerSide)
{
// The lowest branch is the same side as the player
// SQUISHED!!
}
The preceding code tests whether the branch in position [5] element of the array is on the same side as the player.
We will look at one more vital C++ topic, that is, functions, and then we will get back to coding the game. When we want to compartmentalize some code that does one specific thing, we can use a function.