Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
C++ Game Development Cookbook
C++ Game Development Cookbook

C++ Game Development Cookbook:

Arrow left icon
Profile Icon Druhin Mukherjee
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (5 Ratings)
Paperback May 2016 346 pages 1st Edition
eBook
Mex$516.99 Mex$738.99
Paperback
Mex$922.99
Subscription
Free Trial
Arrow left icon
Profile Icon Druhin Mukherjee
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (5 Ratings)
Paperback May 2016 346 pages 1st Edition
eBook
Mex$516.99 Mex$738.99
Paperback
Mex$922.99
Subscription
Free Trial
eBook
Mex$516.99 Mex$738.99
Paperback
Mex$922.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

C++ Game Development Cookbook

Chapter 2. Object-Oriented Approach and Design in Games

In this chapter, we will cover the following recipes:

  • Using classes for data encapsulation and abstraction
  • Using polymorphism to reuse code
  • Using copy constructors
  • Using operator overloading to reuse operators
  • Using function overloading to reuse functions
  • Using files for input and output
  • Creating your first simple text-based game
  • Templates – when to use them

Introduction

The following diagram shows the main concepts of OOP (Object-oriented programming). Let us consider that we need to make a car racing game. So, a car is made up of an engine, wheels, chassis, and so on. All these parts can be considered as individual components, which can be used for other cars as well. Similarly, every car's engine can be different and so we can add different functionalities, states, and properties to each individual component.

All this can be achieved through object-oriented programming:

Introduction

We need to use an object-oriented system in any design that consists of states and behaviors. Let us consider a game like Space Invaders. The game consists of two main characters, the player ship and the enemy. There is also a boss, but that is just an advanced version of the enemy. The player ship can have different states such as alive, idle, moving, attack, and dead. It also has a few behaviors, such as left/right movement, single shoot/burst shoot/missile. Similarly...

Using classes for data encapsulation and abstraction

A class is used to organize information into meaningful states and behaviors. In games, we deal with so many different types of weapon, player, enemy, and terrain, each with its own type of state and behavior, so an object-oriented design with classes is a must.

Getting ready

To work through this recipe, you will need a machine running Windows. You need to have a working copy of Visual Studio installed on your Windows machine. No other prerequisites are required.

How to do it…

In this recipe, we will see how easy it is to create a game framework using object-oriented programming in C++:

  1. Open Visual Studio.
  2. Create a new C++ project.
  3. Select Win32 Console Application.
  4. Add source files called Source.cpp, CEnemy.h, and CEnemy.cpp.
  5. Add the following lines of code to Souce.cpp:
    #include "CEnemy.h"
    #include <iostream>
    #include <string>
    #include <conio.h>
    #include "vld.h"
    
    using namespace std;
    
    int main()
    {...

Using polymorphism to reuse code

Polymorphism means having several forms. Typically, we use polymorphism when there is a hierarchy of classes and they are related in some way. We generally achieve this level of relation by using inheritance.

Getting ready

You need to have a working copy of Visual Studio installed on your Windows machine.

How to do it…

In this recipe, we will see how we can use the same function and override it with different functionalities based on our needs. Also, we will see how we can share values across base and derived classes:

  1. Open Visual Studio.
  2. Create a new C++ project.
  3. Select Win32 Console Application.
  4. Add a source file called Source.cpp and three header files called Enemy.h, Dragon.h, and Soldier.h.
  5. Add the following lines of code to Enemy.h:
    #ifndef _ENEMY_H
    #define _ENEMY_H
    
    #include <iostream>
    
    using namespace std;
    
    class CEnemy {
    protected:
      int m_ihealth,m_iarmourValue;
    public:
      CEnemy(int ihealth, int iarmourValue) : m_ihealth(ihealth), m_iarmourValue...

Using copy constructors

Copy constructors are used to copy one object to another. C++ provides us with a default copy constructor, but it is not recommended. We should write our own copy constructor for better coding and organizing practices. It also minimizes crashes and bugs that may arise if we use the default copy constructor provided by C++.

Getting ready

You need to have a working copy of Visual Studio installed on your Windows machine.

How to do it…

In this recipe, we will see how easy it is to write a copy constructor:

  1. Open Visual Studio.
  2. Create a new C++ project.
  3. Select Win32 Console Application.
  4. Add source files called Source.cpp and Terrain.h.
  5. Add the following lines of code to Terrain.h:
    #pragma once
    #include <iostream>
    
    using namespace std;
    class CTerrain
    {
    public:
      CTerrainCTerrain();
      ~CTerrain();
    
      CTerrain(const CTerrain &T)
      {
        cout << "\n Copy Constructor";
      }
      CTerrain& operator =(const CTerrain &T)
      {
        cout << &quot...

Use operator overloading to reuse operators

There are lots of operators that are provided for us by C++. However, sometimes we need to overload these operators so that we can use them on data structures that we create ourselves. Of course, we can overload the operators to change the meaning as well. For example, we can change + (plus) to behave like - (minus), but this is not recommended as this usually does not serve any purpose or help us in any way. Also, it may confuse other programmers who are using the same code base.

Getting ready

You need to have a working copy of Visual Studio installed on your Windows machine.

How to do it…

In this recipe, we will see how we can overload an operator and which operators are allowed to be overloaded in C++.

  1. Open Visual Studio.
  2. Create a new C++ project.
  3. Select Win32 Console Application.
  4. Add a source file called Source.cpp, vector3.h, and vector3.cpp.
  5. Add the following lines of code to Source.cpp:
    #include "vector3.h"
    #include <conio.h&gt...

Use function overloading to reuse functions

Function overloading is an important concept in C++. Sometimes, we want to use the same function name but have different functions to work on different data types or a different number of types. This is useful as the client can choose the correct function based on its needs. C++ allows us to do this by using function overloading.

Getting ready

For this recipe, you will need a Windows machine with a working copy of Visual Studio.

How to do it…

In this recipe, we will learn how to overload a function:

  1. Open Visual Studio.
  2. Create a new C++ project.
  3. Select a Win32 Console Application.
  4. Add source files called main.cpp, Cspeed.h, and Cspeed.cpp.
  5. Add the following lines of code to main.cpp:
    #include <iostream>
    #include <conio.h>
    #include "CSpeed.h"
    
    using namespace std;
    
    
    
    //This is not overloading as the function differs only
    //in return type
    /*int Add(float x, float y)
    {
      return x + y;
    }*/
    
    int main()
    {
      CSpeed speed;
    
      cout&lt...

Introduction


The following diagram shows the main concepts of OOP (Object-oriented programming). Let us consider that we need to make a car racing game. So, a car is made up of an engine, wheels, chassis, and so on. All these parts can be considered as individual components, which can be used for other cars as well. Similarly, every car's engine can be different and so we can add different functionalities, states, and properties to each individual component.

All this can be achieved through object-oriented programming:

We need to use an object-oriented system in any design that consists of states and behaviors. Let us consider a game like Space Invaders. The game consists of two main characters, the player ship and the enemy. There is also a boss, but that is just an advanced version of the enemy. The player ship can have different states such as alive, idle, moving, attack, and dead. It also has a few behaviors, such as left/right movement, single shoot/burst shoot/missile. Similarly, the...

Using classes for data encapsulation and abstraction


A class is used to organize information into meaningful states and behaviors. In games, we deal with so many different types of weapon, player, enemy, and terrain, each with its own type of state and behavior, so an object-oriented design with classes is a must.

Getting ready

To work through this recipe, you will need a machine running Windows. You need to have a working copy of Visual Studio installed on your Windows machine. No other prerequisites are required.

How to do it…

In this recipe, we will see how easy it is to create a game framework using object-oriented programming in C++:

  1. Open Visual Studio.

  2. Create a new C++ project.

  3. Select Win32 Console Application.

  4. Add source files called Source.cpp, CEnemy.h, and CEnemy.cpp.

  5. Add the following lines of code to Souce.cpp:

    #include "CEnemy.h"
    #include <iostream>
    #include <string>
    #include <conio.h>
    #include "vld.h"
    
    using namespace std;
    
    int main()
    {
      CEnemy* pEnemy = new CEnemy...

Using polymorphism to reuse code


Polymorphism means having several forms. Typically, we use polymorphism when there is a hierarchy of classes and they are related in some way. We generally achieve this level of relation by using inheritance.

Getting ready

You need to have a working copy of Visual Studio installed on your Windows machine.

How to do it…

In this recipe, we will see how we can use the same function and override it with different functionalities based on our needs. Also, we will see how we can share values across base and derived classes:

  1. Open Visual Studio.

  2. Create a new C++ project.

  3. Select Win32 Console Application.

  4. Add a source file called Source.cpp and three header files called Enemy.h, Dragon.h, and Soldier.h.

  5. Add the following lines of code to Enemy.h:

    #ifndef _ENEMY_H
    #define _ENEMY_H
    
    #include <iostream>
    
    using namespace std;
    
    class CEnemy {
    protected:
      int m_ihealth,m_iarmourValue;
    public:
      CEnemy(int ihealth, int iarmourValue) : m_ihealth(ihealth), m_iarmourValue(iarmourValue...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Level up your game programming skills with insightful recipes on building games in C++
  • Analyze the less commonly discussed problems with C++ applications to develop the best games
  • Improve the performance of your games with the new multi-threading and networking features of C++11

Description

C++ is one of the preferred languages for game development as it supports a variety of coding styles that provides low-level access to the system. C++ is still used as a preferred game programming language by many as it gives game programmers control of the entire architecture, including memory patterns and usage. However, there is little information available on how to harness the advanced features of C++ to build robust games. This book will teach you techniques to develop logic and game code using C++. The primary goal of this book is to teach you to create high-quality games using C++ game programming scripts and techniques, regardless of the library or game engine you use. It will show you how to make use of the object-oriented capabilities of C++ so you can write well-structured and powerful games of any genre. The book also explores important areas such as physics programming and audio programming, and gives you other useful tips and tricks to improve your code. By the end of this book, you will be competent in game programming using C++, and will be able to develop your own games in C++.

Who is this book for?

This book is ideal for aspiring game developers who are proficient in C++ programming and are interested in developing games with C++. Some basic knowledge of game programming will be useful but is not necessary.

What you will learn

  • Explore the basics of game development to build great and effective features for your game
  • Develop your first text-based game using the various concepts of object-oriented programming
  • Use algorithms when developing games with various sorting and searching techniques
  • Exploit data structures in a game's development for data storage
  • Create your first 2D game using GDI library and sprite sheet.
  • Build your first advanced 2D game of space invaders using patterns such as observer, fly-weight, abstract factory, command, state, and more

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 30, 2016
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781785882722
Vendor :
Microsoft
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 30, 2016
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781785882722
Vendor :
Microsoft
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,180.97
C++ Game Development Cookbook
Mex$922.99
Beginning C++ Game Programming
Mex$1128.99
Procedural Content Generation for C++ Game Development
Mex$1128.99
Total Mex$ 3,180.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Game Development Basics Chevron down icon Chevron up icon
2. Object-Oriented Approach and Design in Games Chevron down icon Chevron up icon
3. Data Structures in Game Development Chevron down icon Chevron up icon
4. Algorithms for Game Development Chevron down icon Chevron up icon
5. Event-Driven Programming – Making Your First 2D Game Chevron down icon Chevron up icon
6. Design Patterns for Game Development Chevron down icon Chevron up icon
7. Organizing and Backing Up Chevron down icon Chevron up icon
8. AI in Game Development Chevron down icon Chevron up icon
9. Physics in Game Development Chevron down icon Chevron up icon
10. Multithreading in Game Development Chevron down icon Chevron up icon
11. Networking in Game Development Chevron down icon Chevron up icon
12. Audio in Game Development Chevron down icon Chevron up icon
13. Tips and Tricks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(5 Ratings)
5 star 40%
4 star 0%
3 star 20%
2 star 20%
1 star 20%
Jose M. Aug 30, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are not a beginner, but also you're not a senior C++ programmer, then this book is for you. Lot of useful code from memory storage to multithreading and networking, presenting topics like data structures, algorithms for sorting, searching, design patterns, and many things more. Of course, you won't find the same depth through all the book, but is great to have the basis of many important subjects, and lot of tips and tricks.100% recommended
Amazon Verified review Amazon
honestreview Jun 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really helpful resource and easy read.
Amazon Verified review Amazon
Otaku Oct 19, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I like the brevity of the explanations, however the kindle version I obtained is laden with a number editing oversights which is a bit annoying
Amazon Verified review Amazon
iPaul Oct 01, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The book is more of a collection of short tutorials about how to use C++ than a game development cookbook. Could be useful if you just learned C++ and trying to do your homework. Chapters like bubble sort or how to implement your own linked list have no place in a modern C++ game dev. cookbook. My impression is that the author simply repackaged his course notes from when he learned C++. There is no actual game described in the book.
Amazon Verified review Amazon
Amazon Customer Sep 01, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I do not recommend this book, style is not well for me and it's full of "to do this you need to have visual studio installed" every chapter, it gets annoying. This book is simply code examples with short comments what they do. Not what I expected at all.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.