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, which 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 use two keywords, enum
and 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 this enumeration declaration. Note that it is conventional to declare the possible values from the enumeration all in uppercase:
enum class zombieTypes {REGULAR, RUNNER, CRAWLER, SPITTER, BLOATER };
Note, 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 create them now:
zombieType dave = zombieTypes::CRAWLER; zombieType angela = zombieTypes::SPITTER zombieType jose = 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
, as in the following example:
enum class side { LEFT, RIGHT, NONE };
We could position the player on the left as follows:
// 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, as follows:
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!! }
We will look at one more vital C++ topic and then we will get back to coding the game.
18.219.156.161