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

Preface

This book is all about offering you a fun introduction to the world of game programming, C++, and the OpenGL-powered SFML using five fun, fully playable games of increasing difficulty and advancing features. These games are an addictive, frantic two-button tapper, a Pong game, a multilevel zombie survival shooter, a split-screen multiplayer puzzle platformer, and a shooter game.

With this improved and extended second edition, we will start with the very basics of programming, such as variables, loops, and conditions, and you will become more skillful with each game as you move through the key C++ topics, such as object-oriented programming (OOP), C++ pointers, and an introduction to the Standard Template Library (STL). While building these games, you will also learn exciting game programming concepts, such as particle effects, directional sound (spatialization), OpenGL programmable Shaders, how to spawn thousands of objects, and more.

Who this book is for

This book is perfect for you if any of the following describes you: You have no C++ programming knowledge whatsoever, or need a beginner level refresher course, if you want to learn to build games or just use games as an engaging way to learn C++, if you have aspirations to publish a game one day, perhaps on Steam, or if you just want to have loads of fun and impress friends with your creations.

What this book covers

Chapter 1, C++, SFML, Visual Studio, and Starting the First Game, represents 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 about the games we will build, discover C++, find out about Microsoft Visual C++, explore SFML and its relationship with C++, set up the development environment, plan and prepare for the first game project, Timber!!!, write the first C++ code in the book, and make a runnable game that draws a background.

Chapter 2, Variables, Operators, and Decisions – Animating Sprites, covers quite a bit more drawing on screen and, in order to achieve this, we will need to learn some of the basics of C++. We will learn how to use variables to remember and manipulate values, and we will also begin to add more graphics to the game. As the chapter progresses, we will see how we can manipulate these values to animate the graphics. These values are known as variables.

Chapter 3, C++ Strings and SFML Time – Player Input and HUD, continues with the Timber!!! game. We will spend half the chapter 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 the following: Pausing and restarting the game, C++ Strings, SFML Text and SFML Font classes, adding an HUD to Timber!!!, and adding a time bar to Timber!!!.

Chapter 4, Loops, Arrays, Switches, Enumerations, and Functions – Implementing Game Mechanics, probably has more C++ information than any other chapter in the book. It is packed with fundamental concepts that will improve our understanding 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 mechanics—the tree branches—move. By the end of this chapter, we will be ready for the final phase and the completion of Timber!!!. This is what we will explore in this chapter: Loops, arrays, making decisions with switches, enumerations, getting started with functions, and creating and moving the tree branches.

Chapter 5, Collisions, Sound, and End Conditions – Making the Game Playable, constitutes 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 final section of this chapter as it will suggest ways to make the game better. In this chapter, we will cover the following topics: Adding the remainder 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 – Starting the Pong Game, contains quite a large amount of theory, but the theory will give us the knowledge to start using OOP to powerful effect. Furthermore, we will not waste any time in putting that theory to good use coding the next project, a Pong game. We get to look behind the scenes at how we can create new types that we use as objects by coding a class. We will first look at a simplified Pong scenario to learn some class basics, and then we will start again and code a Pong game for real using the principles we have learned.

Chapter 7, Dynamic Collision Detection and Physics – Finishing the Pong Game, explains how to code our second class. We will see that although the ball is obviously quite different from the bat, we will use the exact same techniques to encapsulate the appearance and functionality of a ball inside a Ball class, as we did with the bat and the Bat class. We will then add the finishing touches to the Pong game by coding some dynamic collision detection and score keeping. This may sound complicated, but, as we are coming to expect, SFML will make things much easier than they otherwise would be.

Chapter 8, SFML Views – Starting the Zombie Shooter Game, explains how this project makes even more use of OOP, and to a powerful effect. We will also be exploring the SFML View class. This versatile class will enable us to easily divide our game up into layers for different aspects of the game. In the Zombie Shooter project, we will have a layer for the HUD and a layer for the main game. This will be necessary because, as the game world expands each time the player clears a wave of zombies, eventually, the game world will be bigger than the screen and will need to scroll. The use of the View class will prevent the text from the HUD from scrolling with the background. In the next project, we will take things even further and create a co-op split-screen game with the SFML View class doing most of the hard work. This is what we will do in this chapter: Plan the Zombie Arena game, code the Player class, learn about the SFML View class, and build the Zombie Arena game engine, putting the player class to work.

Chapter 9, C++ References, Sprite Sheets, and Vertex Arrays, explores C++ references, which allow us to work on variables and objects that are otherwise out of scope. In addition, references will help us to 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 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 parts in a single image file. By the end of the chapter, we will have a scalable, random, scrolling background, using references and a VertexArray object.

Chapter 10, Pointers, the Standard Template Library, and Texture Management, first covers the fundamental C++ topic of pointers. Pointers are variables that hold a memory address. 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 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 newly acquired 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.

Chapter 11, Collision Detection, Pickups, and Bullets, explains how we have implemented the main visual aspects of our game so far. 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 one another. A zombie can wonder 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.

Chapter 12, Layering Views and Implementing the HUD, is the chapter where 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 and the Pong 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.

Chapter 13, Sound Effects, File I/O, and Finishing the Game, demonstrates 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 the play function will go. We will also tie up a few loose ends to make the game complete. In this chapter, we will do the following: Save and load the hi-score using file input and file output, add sound effects to allow the player to level up, and create never-ending multiple waves.

Chapter 14, Abstraction and Code Management – Making Better Use of OOP, focuses on getting the Thomas Was Alone project started, especially exploring how the code will be structured to make better use of OOP. Here are the details of the topics that will be covered in this chapter: The final project, Thomas Was Late, is introduced, including the gameplay features and project assets, and a detailed discussion is provided of how we will improve the structure of the code compared to previous projects, code the Thomas Was Late game engine, and implement the split-screen functionality.

Chapter 15, Advanced OOP – Inheritance and Polymorphism, extends our knowledge of OOP further 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 this chapter: 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 class, put inheritance to work with the Thomas and Bob classes, and add Thomas and Bob to the game project.

Chapter 16, Building Playable Levels and Collision Detection, will probably prove to be one of the most satisfying chapters of this project. The reason for this is that by the end of it, we will have a playable game. Although there will still be features to implement (sound, particle effects, HUD, and 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 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 that our game can use and keep track of the level details, such as spawn position, current level, and allowed time limit, update the game engine to use LevelManager, and code a polymorphic function to handle the collision detection for both Bob and Thomas.

Chapter 17, Sound Spatialization and the HUD, adds all the sound effects and the HUD. We have done this in both 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 an HUD class to encapsulate our code that draws information to the screen. We will complete the tasks in the following order: What spatialization is, how SFML handles spatialization, building a SoundManager class, deploying emitters, using the SoundManager class, and building and then using an HUD class.

Chapter 18, Particle Systems and Shaders, examines what a particle system is and then proceeds to code one into our game. We will scratch the surface of the topic of OpenGL shaders and see how writing code in another language OpenGL Shading 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.

Chapter 19, Game Programming Design Patterns – Starting the Space Invaders ++ Game, introduces the final project. As you have come to expect by now, this project will take a significant step forward in learning new C++ techniques. The next four chapters will look at topics including smart pointers, C++ assertions, using a gamepad controller, debugging using Visual Studio, casting pointers of a base class to become pointers of a specific derived class, debugging, and taking a first look at design patterns. The author is surmising that if you are going to make deep, large-scale games in C++, then design patterns are going to be a big part of your learning agenda in the months and years ahead. In order to introduce this vital topic, I have chosen a relatively simple, but fun, game to serve as an example. Let's find out a bit more about the Space Invaders ++ game, and then we can move on to the topic of design patterns and why we need them. In this hefty chapter, we will cover the following topics: Finding out about Space Invaders ++ and why it has been chosen for the final project, learning what design patterns are and why they matter to game developers, studying the design patterns in the Space Invaders ++ project that will be used over the next four chapters, getting started on the Space Invaders ++ project, and coding numerous classes to begin to flesh out the game.

Chapter 20, Game Objects and Components, covers all the coding related to the Entity-Component pattern we discussed at the beginning of the previous chapter. This means we will code the base component class that all the other components will be derived from. We will also put to good use our new knowledge of smart pointers so that we don't have to concern ourselves with keeping track of the memory we allocate for these components. We will also code the GameObject class in this chapter. Here is a list of the sections in this chapter: Preparing to code the components, coding the component base class, coding the collider components, coding the graphics components, coding the update components, and coding the GameObject class.

Chapter 21, File I/O and the Game Object Factory, explains how a GameObject gets into the m_GameObjects vector used in the game. We will see how we can describe individual objects and an entire level in a text file. We will write code to interpret the text and then load up values into a class that will be a blueprint for a game object. We will code a class called LevelManager that oversees the whole process, starting from the initial request to load a level sent from an InputHandler via the ScreenManager, right through to the factory pattern class that assembles a game object from components and delivers it to the LevelManager class neatly packed away in the m_GameObjects vector.

Chapter 22, Using Game Objects and Building a Game, constitutes the final stage of the Space Invaders ++ project. We will learn how to receive input from a gamepad using SFML to do all the hard work, and we will also code a class that will handle communication between the invaders and the GameScreen class, as well as the player and the GameScreen class. The class will allow the player and the invaders to spawn bullets, but the exact same technique could be used for any kind of communication that you need between different parts of your own game, so it is useful to know. The final part of the game (as usual) will be collision detection and the logic of the game itself. Once Space Invaders ++ is up and running, we will learn how to use the Visual Studio debugger, which will be invaluable when you are designing your own logic because it allows you to step through your code a line at a time and see the value of variables. It is also a useful tool for studying the flow of execution of the patterns we have assembled over the course of this project.

Chapter 23, Before You Go..., brings our journey to an end. When you first opened this big doorstop of a book, the back page probably seemed like a long way off. But it wasn't too tough, I hope? The point is that you are here now and hopefully, you have a good insight into how to build games using C++. It might surprise you to hear that even after all these hundreds of pages, we have only dipped our toes into C++. Even the topics we did cover could be covered in more depth and there are numerous, some quite significant, topics that we haven't even mentioned. With this in mind, let's take a look at what might be next.

To get the most out of this book

The following requirements need to be satisfied:

  • 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 and Mac users will probably have no trouble running the code and following the instructions using their favorite programming environment.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at http://www.packt.com.
  2. Select the Support tab.
  3. Click on Code Downloads.
  4. Enter the name of the book in the Search box and follow the on screen instructions.

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-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838648572_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "My main project directory is D:\VS Projects\Timber."

A block of code is set as follows:

int main()
{
    return 0;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

int main()
{
    return 0;
}

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Click on the Create a new project button."

Important note

Warnings or important notes appear like this.

Tip

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

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