Reader small image

You're reading from  Beginning C++ Game Programming. - Second Edition

Product typeBook
Published inOct 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648572
Edition2nd Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

Chapter 4: Loops, Arrays, Switches, Enumerations, and Functions – Implementing Game Mechanics

This chapter probably has more C++ information in it than any other chapter in this book. It is packed with fundamental concepts that will move our understanding on enormously. It will also begin to shed light on some of the murky areas we have been skipping over a little bit, such as functions and the game loop.

Once we have explored a whole list of C++ language necessities, we will then use everything we know to make the main game mechanic—the tree branches—move. By the end of this chapter, we will be ready for the final phase and the completion of Timber!!!.

In this chapter, we will cover the following topics:

  • Loops
  • Arrays
  • Making decisions with switch
  • Enumerations
  • Getting started with functions
  • Creating and moving the tree branches

Loops

In programming, we often need to do the same thing more than once. The obvious example that we have seen so far is the game loop. With all the code stripped out, our game loop looks like this:

while (window.isOpen())
{
}

There are a few different types of loops, and we will look at the most commonly used ones here. The correct term for this type of loop is a while loop.

while loops

The while loop is quite straightforward. Think back to the if statements and their expressions that evaluated to either true or false. We can use the exact same combination of operators and variables in the conditional expressions of our while loops.

Like if statements, if the expression is true, the code executes. The difference with a while loop, however, is that the C++ code within it will repeatedly execute until the condition is false. Take a look at the following code.

int numberOfZombies = 100;
while(numberOfZombies > 0)
{
    // Player kills a zombie...

Arrays

If a variable is a box in which we can store a value of a specific type, such as int, float, or char, then we can think of an array as a row of boxes. The rows of boxes can be of almost any size and type, including objects made from classes. However, all the boxes must be of the same type.

Tip

The limitation of having to use the same type in each box can be circumvented to an extent once we learn some more advanced C++ in the penultimate project.

This array sounds like it could have been useful for our clouds in Chapter 2, Variables, Operators, and Decisions – Animating Sprites. So, how do we go about creating and using an array?

Declaring an array

We can declare an array of int type variables like this:

int someInts[10];

Now, we have an array called someInts that can store ten int values. Currently, however, it is empty.

Initializing the elements of an array

To add values to the elements of an array, we can use the type of syntax we are already...

Making decisions with switch

We have already looked at if, which allows us to decide whether to execute a block of code based upon the result of its expression. But sometimes, a decision in C++ can be made in other ways that are better.

When we must make a decision based on a clear list of possible outcomes that don't involve complex combinations or wide ranges of values, then switch is usually the way to go. We can start a switch decision as follows:

switch(expression)
{
    // More code here
}

In the previous example, expression could be an actual expression or just a variable. Then, within the curly braces, we can make decisions based on the result of the expression or value of the variable. We do this with the case and break keywords:

case x:
    //code for x
    break;
 
case y:
    //code for y
    break;

As you can see, each case states a possible result...

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...

Getting started with functions

What exactly are C++ functions? A function is a collection of variables, expressions, and control flow statements (loops and branches). In fact, any of the code we have learned about in this book so far can be used in a function. The first part of a function that we write is called the signature. Here is an example function signature:

void shootLazers(int power, int direction);

If we add an opening and closing pair of curly braces {...} along with some code that the function performs, we will have a complete function, that is, a definition:

void shootLazers(int power, int direction)
{
    // ZAPP!
}

We could then use our new function from another part of our code, perhaps like this:

// Attack the player
shootLazers(50, 180) // Run the code in the function
// I'm back again - code continues here after the function ends

When we use a function, we say that we call it. At the point where we call shootLazers, our...

Growing the branches

Next, as I have been promising for the last 20 pages, we will use all the new C++ techniques we've learned about to draw and move some branches on our tree.

Add the following code outside of the main function. Just to be absolutely clear, I mean before the code for int main():

#include <sstream>
#include <SFML/Graphics.hpp>
using namespace sf;
// Function declaration
void updateBranches(int seed);
const int NUM_BRANCHES = 6;
Sprite branches[NUM_BRANCHES];
// Where is the player/branch?
// Left or Right
enum class side { LEFT, RIGHT, NONE };
side branchPositions[NUM_BRANCHES];
int main()

We just achieved quite a few things with that new code:

  • First, we wrote a function prototype for a function called updateBranches. We can see that it does not return a value (void) and that it takes an int argument called seed. We will write the function definition soon, and we will then see exactly what it does.
  • Next, we declare an int constant...

Summary

Although not quite the longest, this was probably the chapter where we've covered the most C++ so far. We looked at the different types of loops we can use, such as for and while loops. We then studied arrays that we can use them to handle large amounts of variables and objects without breaking a sweat. We also learned about enumerations and switch. Probably the biggest concept in this chapter was functions, which allow us to organize and abstract our game's code. We will be looking more deeply at functions in a few more places in this book.

Now that we have a fully "working" tree, we can finish the game off, which we will do in the next and final chapter for this project.

FAQ

Q) You mentioned there were a few more types of C++ loops. Where can I find out about them?

A) Yes, take a look at this tutorial and explanation for the do while loops: http://www.tutorialspoint.com/cplusplus/cpp_do_while_loop.htm.

Q) Can I assume I am now an expert on arrays?

A) Like many of the topics in this book, there is always more to learn. You know enough about arrays to proceed, but if you're hungry for more, take a look at this fuller arrays tutorial: http://www.cplusplus.com/doc/tutorial/arrays/.

Q) Can I assume that I am an expert on functions?

A) Like many of the topics in this book, there is always more to learn. You know enough about functions to proceed, but if want to know even more, take a look at this tutorial: http://www.cplusplus.com/doc/tutorial/functions/.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Beginning C++ Game Programming. - Second Edition
Published in: Oct 2019Publisher: PacktISBN-13: 9781838648572
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton