Book Image

Game Development Patterns and Best Practices

By : John P. Doran, Matt Casanova
Book Image

Game Development Patterns and Best Practices

By: John P. Doran, Matt Casanova

Overview of this book

You’ve learned how to program, and you’ve probably created some simple games at some point, but now you want to build larger projects and find out how to resolve your problems. So instead of a coder, you might now want to think like a game developer or software engineer. To organize your code well, you need certain tools to do so, and that’s what this book is all about. You will learn techniques to code quickly and correctly, while ensuring your code is modular and easily understandable. To begin, we will start with the core game programming patterns, but not the usual way. We will take the use case strategy with this book. We will take an AAA standard game and show you the hurdles at multiple stages of development. Similarly, various use cases are used to showcase other patterns such as the adapter pattern, prototype pattern, flyweight pattern, and observer pattern. Lastly, we’ll go over some tips and tricks on how to refactor your code to remove common code smells and make it easier for others to work with you. By the end of the book you will be proficient in using the most popular and frequently used patterns with the best practices.
Table of Contents (19 chapters)
Title Page
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
4
Artificial Intelligence Using the State Pattern

Preface

As your programs get larger, it is critical that you understand how to write code in such a way that classes and modules can communicate with each other in an intelligent way. Knowing how to write code that is clean and extensible is critical for the success of medium to large scale projects, especially if there are multiple programmers involved. We don't want to spend time rewriting another programmer’s code because it is easier than figuring out how the original code works. Likewise, we don’t want other programmers to be confused by our code and rewrite solutions to problems that we already solved. This book explores the ins and outs of the most common ways to design code so that it can be understood, reused, maintained, and extended if necessary. These common design patterns will make communication between classes simple and clean. Whether you are using a commercial game engine or writing your own from scratch, knowledge of these patterns will make your game project more likely to succeed. Each chapter of this book explores one of the most used design patterns for games. Together we discuss the problems that we are trying to solve and how a specific pattern can be of use to us. Within each chapter, we also cover the pros and cons of the pattern so you are better equipped to know when to use it. This book is not a "cook book". Using a pattern in your project isn’t as simple as copying some code that we provide. Instead of learning recipes for code, we are going to learn the fundamentals of how a game engine should be written. We will do this by looking at lots of code examples. As we said, these example, can’t simply be copy and pasted into any project. However, by understanding how these examples fit into the specific project for this book, you can implement them in any project.

What this book covers

Chapter 1, Introduction to Design Patterns, introduces the concept of design patterns and how they can benefit our projects. We also dive into learning about the advantages of compartmentalizing our code and set up a sample project that we can use to build upon in the book.

Chapter 2, One Instance to Rule Them All – Singletons, discusses the well-known singleton pattern, explaining common arguments for and against having a single instance that’s accessible globally within our game.

Chapter 3, Creating Flexibility with the Component Object Model, explores how to create a large amount of different game object types while minimizing code duplication.

Chapter 4, Artificial Intelligence Using the State Pattern, shows the usage of states to allow a game object to change its behavior and functionality due to different stimuli in your game. We discuss and apply how we can use this concept in both player behavior and artificial intelligence.

Chapter 5, Decoupling Code via the Factory Method Pattern, explains how we separate our specific game objects from our game engine.  This will allow us to reuse all or at least part of our game engine for future games.

Chapter 6, Creating Objects with the Prototype Pattern, covers another way to reduce dependencies within our game engine.  We learn how to create objects through their base classes.  In addition, we cover how to read object data from a file.

Chapter 7, Improving Performance with Object Pools, covers a way to improve memory costs in our games by reusing objects that we’ve created dynamically by making use of a manager to control what is and isn’t being used at the moment.

Chapter 8, Controlling the UI via the Command Pattern, discusses how to create reusable actions that can be utilized for UI button clicks or input devices such as keyboard or controller.

Chapter 9, Decoupling Gameplay via the Observer Pattern, explains multiple ways that classes can communicate and share data without using global variables. 

Chapter 10, Sharing Objects with the Flyweight Pattern, discusses how we can design our objects to be as lightweight as possible by separating data that can and can't be shared. We use this knowledge to create a particle system which produces smaller objects developed to simulate things like fire, explosions, and smoke.

Chapter 11, Understanding Graphics and Animation, provides a low-level explanation of how graphics and rendering work so that you are better able to implement it in your game.

Chapter 12, Best Practices, covers a number of topics that will improve your code and game projects in the future, touching on things like how to improve your code quality, use the const keyword correctly, how iteration is a great way to improve game and code design, and when you should consider adding scripting to your game.

What you need for this book

To write code, all you really need is a text editor, but for serious development you'll need to use an IDE (Integrated Developer Environment). We use Microsoft Visual Studio 2015 and C++ in this book using a Windows computer but, the concepts taught can be used within any programming language as well. For those of you that do not have Visual Studio installed, but are using Windows we do go over how to install the free Visual Studio Community version and set it up with our project in Chapter 1, Introduction to Design Patterns.

Who this book is for

This book is for anyone who wants to learn how to write better, cleaner code.  While design patterns in general do not require any specific programming language, the examples in this book are written in C++.  Readers will get much more out of this book if they are already familiar with C++ and STL containers.  The project that is included with this book was written and compiled using Microsoft Visual Studio 2015, so familiarity with that IDE will be very helpful as well.

Conventions

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, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "I’m going to update the ChasePlayerComponent class that already exists in the EngineTest project."

A block of code is set as follows:

class Animal
{
  public:
    virtual void Speak(void) const //virtual in the base class
    {
      //Using the Mach 5 console print
      M5DEBUG_PRINT("...\n");
    }
};

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

class StaticExamples
{
  public:
    static float classVariable;

    static void StaticFunction()
    {
// Note, can only use static variables and functions within 
      // static function
      std::string toDisplay = "\n I can be called anywhere! 
      classVariable value: " + 
      std::to_string(classVariable);

      printf(toDisplay.c_str());
    }

    void InFunction()
    {
      static int enemyCount = 0;

      // Increase the value of enemyCount
      enemyCount += 10;

      std::string toDisplay = "\n Value of enemyCount: " + 
      std::to_string(enemyCount);

      printf(toDisplay.c_str());
   }
};

 

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: "In order to download new modules, we will go to FilesSettings | Project Name | Project Interpreter."

Note

Warnings or important notes appear in a box like this.

Note

Tips and tricks appear like this.

Reader feedback

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.

Customer support

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.

Downloading the example code

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:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. 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/Game-Development-Patterns-and-Best-Practices. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

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 https://www.packtpub.com/sites/default/files/downloads/GameDevelopmentPatternsandBestPractices_ColorImages.pdf.

Errata

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

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.

Questions

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.