This book is about learning C++ programming the fun way. Starting from zero experience, you will learn the basics of C++, such as variables and loops, through to advanced topics, such as inheritance and polymorphism. Everything you learn will be put into practice building three fully-playable games.
These are our three projects for the book.
The first game is an addictive, fast-paced clone of the hugely successful Timberman, http://store.steampowered.com/app/398710/. Our game, Timber!!!, will allow us to be introduced to all the C++ basics at the same time as building a genuinely playable game.
Next we will build a frantic, zombie survival-shooter, not unlike the Steam hit, Over 9,000 Zombies, http://store.steampowered.com/app/273500/. The player will have a machine gun, and must fight off ever growing waves of zombies. All this will take place in a randomly generated, scrolling world. To achieve this, we will learn about object-oriented programming and how it enables us to have a large code base (lots of code) that is easy to write and maintain. Expect exciting features such as hundreds of enemies, rapid-fire weaponry, pick-ups and a character that can be "leveled-up" after each wave.
The third game will be a stylish and challenging, single player and co-op puzzle platformer. It is based on the very popular game, Thomas was Alone, http://store.steampowered.com/app/220780/. Expect to learn cool topics such as particle effects, OpenGL Shaders, and split-screen cooperative multiplayer.
Chapter 1, C++, SFML, Visual Studio, and Starting the First Game, this is quite a hefty first chapter, but we will learn absolutely everything we need in order to have the first part of our first game up and running. Here is what we will do:
Find out more about the games we will build
Learn a bit about C++
Explore SFML and its relationship with C++
Look at the software, Visual Studio, that we will use throughout the book
Set up a game development environment
Create a reusable project template, which will save a lot of time
Plan and prepare for the first game project, Timber!!!
Write the first C++ code of the book and make a runnable game that draws a background
Chapter 2, Variables, Operators, and Decisions – Animating Sprites, in this chapter, we will do quite a bit more drawing on the screen, and to achieve this we will need to learn some of the basics of C++. Here is what is in store:
Learn all about C++ variables
See how to manipulate the values stored in variables
Add a static tree, ready for the player to chop
Draw and animate a bee and three clouds
Chapter 3, C++ Strings, SFML Time – Player Input, and HUD, in this chapter, we will spend around half the time learning how to manipulate text and display it on the screen, and the other half looking at timing and how a visual time-bar can inform the player and create a sense of urgency in the game. We will cover:
Pausing and restarting the game
C++ strings
SFML text and SFML font classes
Adding a HUD to Timber!!!
Adding a time-bar to Timber!!!
Chapter 4, Loops, Arrays, Switch, Enumerations, and Functions – Implementing Game Mechanics, this chapter probably has more C++ information than any other chapter in the 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 like 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!!!. Get ready for the following topics:
Loops
Arrays
Making decisions with switch
Enumerations
Getting started with functions
Creating and moving the tree branches
Chapter 5, Collisions, Sound, and End Conditions – Making the Game Playable, this is the final phase of the first project. By the end of this chapter, you will have your first completed game. Once you have Timber!!! up and running, be sure to read the last section of this chapter as it will suggest ways to make the game better:
Adding the rest of the sprites
Handling the player input
Animating the flying log
Handling death
Adding sound effects
Adding features and improving Timber!!!
Chapter 6, Object-Oriented Programming, Classes, and SFML Views, this is the longest chapter of the book. There is a fair amount of theory, but the theory will give us the knowledge to start using OOP (object-oriented programming) to great effect. Furthermore, we will not waste any time in putting that theory to good use. Before we explore C++ OOP, we will find out about and plan our next game project. This is what we will do:
Plan the Zombie Arena game
Learn about OOP and classes
Code the Player class
Learn about the SFML View class
Build the Zombie Arena game engine
Put the Player class to work
Chapter 7, C++ References, Sprite Sheets, and Vertex Arrays , in this chapter, we will explore C++ references, which allow us to work on variables and objects that are otherwise out of scope. In addition, references will help us avoid having to pass large objects between functions, which is a slow process. It is a slow process because each time we do this, a copy of the variable or object must be made.
Armed with this new knowledge about references, we will take a look at the SFML VertexArray
class, which allows us to build up a large image that can be very quickly and efficiently drawn to the screen using multiple images from a single image file. By the end of the chapter, we will have a scaleable, random, scrolling background, using references and a VertexArray
object.
We will now talk about:
C++ references
SFML
VertexArrays
Coding a random, scrolling background
Chapter 8, Pointers, the Standard Template Library, and Texture Management, we will learn a lot, as well as get plenty done to the game, in this chapter. We will first learn about the fundamental C++ topic of pointers. Pointers are variables that hold memory addresses. Typically, a pointer will hold the memory address of another variable. This sounds a bit like a reference, but we will see how they are much more powerful and we will use a pointer to handle an ever-expanding horde of zombies.
We will also learn about the Standard Template Library (STL), which is a collection of classes that allow us to quickly and easily implement common data management techniques.
Once we understand the basics of the STL, we will be able to use that new knowledge to manage all the textures from the game, because if we have 1,000 zombies, we don't really want to load a copy of a zombie graphic into the GPU for each and every one.
We will also dig a little deeper into OOP and use a static function, which is a function of a class that can be called without an instance of the class. At the same time, we will see how we can design a class to ensure that only one instance can ever exist. This is ideal when we need to guarantee that different parts of our code will use the same data.
In this chapter we will:
Learn about pointers
Learn about the STL
Implement the Texture Holder class using static functions and a singleton class
Implement a pointer to a horde of zombies
Edit some existing code to use the TextureHolder class for the player and background
Chapter 9, Collision Detection, Pickups, and Bullets, so far, we have implemented the main visual parts of our game. We have a controllable character running around in an arena full of zombies that chase him. The problem is that they don't interact with each other. A zombie can wander right through the player without leaving a scratch. We need to detect collisions between the zombies and the player.
If the zombies are going to be able to injure and eventually kill the player, it is only fair that we give the player some bullets for his gun. We will then need to make sure that the bullets can hit and kill the zombies.
At the same time, if we are writing collision detection code for bullets, zombies, and the player, it would be a good time to add a class for health and ammo pickups as well.
Here is what we will do and the order we will cover things:
Shooting bullets
Adding a crosshair and hiding the mouse pointer
Spawning pickups
Detecting collisions
Chapter 10, Layering Views and Implementing the HUD, in this chapter, we will get to see the real value of SFML Views. We will add a large array of SFML Text objects and manipulate them as we did before in the Timber!!! project. What is new is that we will draw the HUD using a second View instance. This way the HUD will stay neatly positioned over the top of the main game action, regardless of what the background, player, zombies, and other game objects are doing.
Here is what we will do:
Add text and a background to the home/game over screen
Add text to the level-up screen
Create the second View
Add a HUD
Chapter 11, Sound Effects, File I/O, and Finishing the Game, we are nearly there. This short chapter will demonstrate how we can easily manipulate files stored on the hard drive using the C++ standard library, and we will also add sound effects. Of course, we know how to add sound effects but we will discuss exactly where in the code the calls to play
will go. We will also tie up a few loose ends to make the game complete. In this chapter we will do the following:
Saving and loading the highscore
Adding sound effects
Allowing the player to levelup
Creating, never-ending multiple waves
Chapter 12, Abstraction and Code Management – Making Better Use of OOP, in this chapter, we will take a first look at the final project of the book. The project will have advanced features, such as directional sound that comes out of the speakers relative to the position of the player. It will also have split-screen co-operative gameplay. In addition, this project will introduce the concept of Shaders which are programs written in another language that run directly on the graphics card. By the end of Chapter 16: Extending SFML Classes, Particle Systems and Shaders, you will have a fully functioning, multiplayer platform game built in the style of the hit classic Thomas Was Alone. This chapter's main focus will be getting the project started, especially exploring how the code will be structured to make better use of OOP. Here are the details of this chapter.
Introduce the final project, Thomas Was Late, including the gameplay features and project assets
A detailed discussion of how we will improve the structure of the code compared to previous projects
Coding the Thomas Was Late game engine
Implementing split-screen functionality
Chapter 13, Advanced OOP – Inheritance and Polymorphism, in this chapter, we will further extend our knowledge of OOP by looking at the slightly more advanced concepts of inheritance and polymorphism. We will then be able to use this new knowledge to implement the star characters of our game, Thomas and Bob. Here is what we will cover, in a little more detail:
Learn how to extend and modify a class using inheritance
Treat an object of a class as if it is more than one type of class by using polymorphism
Learn about abstract classes and how designing classes that are never instantiated can actually be useful
Build an abstract
PlayableCharacter
classPut inheritance to work with the
Thomas
andBob
classesAdd Thomas and Bob to the game project
Chapter 14, Building Playable Levels and Collision Detection, this chapter will probably be one of the most satisfying of this project. The reason for this is that by the end of it we will have a playable game. Although there will be features still to implement (sound, particle effects, HUD, shader effects), Bob and Thomas will be able to run, jump, and explore the world. Furthermore, you will be able to create your very own level designs of almost any size or complexity, by simply making platforms and obstacles in a text file. We will achieve all this by covering these topics:
Exploring how to design levels in a text file
Building a
LevelManager
class that will load levels from a text file, convert them into data our game can use, and keep track of the level details such as spawn position, current level, and allowed time limitUpdate the game engine to use
LevelManager
Code a polymorphic function to handle the collision detection for both Bob and Thomas
Chapter 15, Sound Spatialization and HUD, in this chapter we will be adding all the sound effects and the HUD. We have done this in both of the previous projects, but we will do things a bit differently this time. We will explore the concept of sound spatialization and how SFML makes this otherwise complicated concept nice and easy; in addition, we will build a HUD class to encapsulate our code draws information to the screen.
We will complete these tasks in this order:
What is spatialization?
How SFML handles spatialization
Building a
SoundManager
classDeploying emitters
Using the
SoundManager
classBuilding a
HUD
classUsing the
HUD
class
Chapter 16, Extending SFML Classes, Particle Systems, and Shaders, in this final chapter, we will explore the C++ concept of extending other people's classes. More specifically, we will look at the SFML Drawable
class and the benefits of using it as a base class for our own classes. We will also scratch the surface of the topic of OpenGL Shaders and see how writing code in another language (GLSL), which can be run directly on the graphics card, can lead to smooth graphical effects that might otherwise be impossible. As usual, we will also use our new skills and knowledge to enhance the current project.
Here is a list of the topics in the order we will cover them:
SFML Drawable
Building a particle system
OpenGl shaders and GLSL
Using shaders in the Thomas Was Late game
Chapter 17, Before You Go..., a quick discussion of what you might like to do next.
Windows 7 Service Pack 1, Windows 8 or Windows 10
1.6 GHz or faster processor
1 GB of RAM (for x86) or 2 GB of RAM (for x64)
15 GB of available hard disk space
5400 RPM hard disk drive
DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution
All the software used in this book is free. Obtaining and installing the software is covered step by step within the book. The book uses Visual Studio for Windows throughout, but experienced Linux users will probably have no trouble running the code and following the instructions using their favorite Linux programming environment.
This book is for those who have no C++ programming knowledge whatsoever and want to learn to build games or just use games, as a more engaging way to learn C++. If you have aspirations of one day publishing a game on Steam, or just want to have a load of fun while learning C++, then this book was written for you.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Beginning-Cpp-Game-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/BeginningCppGameProgramming_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.