Book Image

Procedural Content Generation for C++ Game Development

By : Dale Green
Book Image

Procedural Content Generation for C++ Game Development

By: Dale Green

Overview of this book

Procedural generation is a growing trend in game development. It allows developers to create games that are bigger and more dynamic, giving the games a higher level of replayability. Procedural generation isn’t just one technique, it’s a collection of techniques and approaches that are used together to create dynamic systems and objects. C++ is the industry-standard programming language to write computer games. It’s at the heart of most engines, and is incredibly powerful. SFML is an easy-to-use, cross-platform, and open-source multimedia library. Access to computer hardware is broken into succinct modules, making it a great choice if you want to develop cross-platform games with ease. Using C++ and SFML technologies, this book will guide you through the techniques and approaches used to generate content procedurally within game development. Throughout the course of this book, we’ll look at examples of these technologies, starting with setting up a roguelike project using the C++ template. We’ll then move on to using RNG with C++ data types and randomly scattering objects within a game map. We will create simple console examples to implement in a real game by creating unique and randomised game items, dynamic sprites, and effects, and procedurally generating game events. Then we will walk you through generating random game maps. At the end, we will have a retrospective look at the project. By the end of the book, not only will you have a solid understanding of procedural generation, but you’ll also have a working roguelike game that you will have extended using the examples provided.
Table of Contents (19 chapters)
Procedural Content Generation for C++ Game Development
Credits
About the Author
Acknowledgment
About the Reviewer
www.PacktPub.com
Preface
Index

Spawning a random item


Currently, when we load our game, set items are spawned. We need to add an element of randomness to do this, and something as simple as a switch statement is all that's needed. Where we can, we always want to add options to create random and procedurally generated content.

To randomly spawn our items, we need to generate a random number between 0 and the number of items we have, and then use that in a switch statement. As stated previously, there isn't one approach to procedural generation, so there will be other methods to doing this.

Let's add in the number generation and switch statements to choose which item to spawn. The updated Game::PopulateLevel function should look as follows:

// Populate the level with items.
void Game::PopulateLevel()
{
    // A Boolean variable used to determine if an object should be spawned.
    bool canSpawn;
 
    // Spawn an item.
    canSpawn = std::rand() % 2;
    if (canSpawn)
    {
        int itemIndex = std::rand() % 2;
       ...