Procedural Generation in Game Design
Procedural Generation in Game Design
Game Design
Procedural Generation in
Game Design
Edited by
Tanya X. Short and Tarn Adams
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts
have been made to publish reliable data and information, but the author and publisher cannot assume
responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to
copyright holders if permission to publish in this form has not been obtained. If any copyright material has
not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmit-
ted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented,
including photocopying, microfilming, and recording, or in any information storage or retrieval system,
without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.
com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and
registration for a variety of users. For organizations that have been granted a photocopy license by the CCC,
a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used
only for identification and explanation without intent to infringe.
Preface, xvii
v
vi ◾ Contents
HOW IT WORKS 60
CONCLUSION 62
Chapter 10 ◾ Worlds 97
Dr. Mark R. Johnson
BRIEF HISTORY OF WORLD GENERATION 98
WHY MAKE WORLDS? 101
Exploration 101
Expansive or Complex Worlds 102
Gameplay Variation 103
QUALITATIVE PROCEDURAL GENERATION 103
PITFALLS 225
Overgeneralization 225
Overrealism 226
Untamed Simulation 227
INDEX, 313
Preface
xvii
xviii ◾ Preface
to players also kept the game fresh for me even after years of working on
it. My experience with Spelunky also taught me how much handiwork is
involved in making algorithms that generate enjoyable levels. Using pro-
cedural generation doesn’ t mean that there’ s no human hand involved in
the design, but only that the hand is less direct in its control. It’ s similar to
how a painter might hold the paintbrush closer to the end of the handle to
create looser, more painterly brush strokes.
That intersection between handiwork and procedure, art and sci-
ence, still feels vast and wild. It took many years before the importance
of roguelikes became widely accepted. Similarly, it will take some time
before developers begin to fully realize the potential for procedural gen-
eration beyond dungeon building, for things like graphics, music, and sto-
rytelling. Thankfully, many of the creators who are thinking about those
things are in this book, sharing their knowledge and experience.
Derek Yu
I
Procedural Generation
1
Chapter 1
Integral
In the most well-known cases, the choice to make use of PCG is wrapped
up in the initial design of the game. Most of the games that make extensive
use of PCG also rely on it entirely to be the type of games they are. Games
with significant random content, such as Rogue and Spelunky , depend on
PCG to deliver their core gameplay. Games using PCG to include a vast
amount of content, such as Elite and No Man’ s Sky , are similarly dependent
3
4 ◾ Procedural Generation in Game Design
on PCG to achieve their vision. The decision to use procedural content was
integral to the decision to make that type of game.
It is vital in these cases to consider the scope of PCG involvement in
achieving the aims of the game. The amount of time it takes to produce the
majority of game content by procedural means cannot be underestimated.
This can have a massive impact on project planning. Any changes to your
project direction (which are far from unusual in game development) will
have vast implications for your codebase.
Your algorithms will need to be drafted and redrafted multiple times,
with the rest of the game’ s content built around them. Work on this
will continue throughout the project life cycle, and this should be care-
fully considered when planning resources for development. The debug-
ging and tweaking of the game’ s procedural systems will continue after
the game’ s release, and with the nature of these games, every little
change can have wide-reaching impact on every aspect of the player’ s
experience.
Holistic use of procedural content needs tight development from cradle
to grave.
Drafting Content
PCG is often used in game development to produce a large amount of
content that is then polished later. The typical example of this is an open-
world game, such as Skyrim , which has a vast explorable map. Major
sections of this are produced using procedural techniques and are then
adjusted and polished by hand later. Other examples include puzzle
games where a generator can produce hundreds of examples of solvable
puzzles, and then a human manually picks out or sorts the more inter-
esting ones.
In these cases, the decision to use PCG comes early, but isn’ t needed
from the project inception. Typically, the code used doesn’ t need a huge
amount of finesse, and doesn’ t need to be as carefully honed to fit the rest
of the project. A landscape generator for an RPG just needs to produce
some rough drafts, with the important detail that the player really inter-
acts with filled in by hand. Because of this, the project timescales are more
predictable.
The use of PCG in these areas both starts and finishes early. Once the
generator has done its job, it is locked down, and the flesh-based designers
get to work on honing the outputs to their needs.
When and Why to Use Procedural Generation ◾ 5
Modal
Some games rely little on PCG, but have a special mode of play that makes
use of procedurally generated content. This is sometimes called an “ infin-
ity mode” and is a special piece of side content to the main game. Examples
include the Ancient Cave in Lufia II and procedural maps in Rust .
Since these are separate modes, they can be created later in the develop-
ment process, perhaps released as downloadable content (DLC) after the
game’ s initial release. It can even be something the game’ s modding com-
munity produces, if your game allows them such flexibility.
A procedural mode that mimics the core game may prove to be less
resource-intensive to develop, as the designer already has a clear vision of
how the output should look and how the mechanics will work in this envi-
ronment, and many of the assets will already be in place. However, this
also tends to restrict the potential for interesting and innovative content,
leading to content that is more random than procedural. Many games that
implement this mode of play end up simply relying on waves of random-
ized enemies rather than putting the extra work into having engaging,
procedurally driven gameplay.
Segmented
Certain segments of a game can be squared off from the rest of the game’ s
design to use PCG. A linear, hand-designed game could still have proce-
dural music, for instance. A certain graphical effect could have interesting
randomized elements. A specific room in a single area of the game may
have some special procedural rules in place.
These individual elements of the game can vary widely in scope, but they
tend to be segmented from the rest of the game design. Thus, the “ when”
of using PCG comes down purely to when this feature needs implement-
ing. And because of the lack of knock-on implications from these sections,
they typically don’ t run a heavy risk of overrun on time. If there is a prob-
lem implementing PCG in these instances, then as a contingency you can
simply revert to hand-generated content instead.
Quality Assurance
One of the most prominent blockers to the use of PCG in mainstream
games, in particular AAA games, is quality assurance (QA). A PCG game
may not be guaranteed to work as intended 100% of the time. There is no
way of having testers go through every single iteration of the procedural
content. The generator may have serious bugs in 0.1% of its levels that are
never picked up until it gets released to a wide playerbase.
I have heard multiple first-hand accounts of developers making a pro-
cedural generator for a game, showing their boss how it can make 100 lev-
els in an instant, and the boss saying, “ Just send those 100 levels to the QA
team, but we’ re not having the generator live in the game.” The perceived
risk of losing control to a procedural system is too great.
The risks can be mitigated with various controls and automated tests.
Connectivity tests for level generators are vital, for instance, but one can
also include minimum difficulty tests or put in further constraints to have
a more controlled experience. This is usually good design too! However,
there is a chance you lose the variety PCG brings to the game, with over-
constrained, “ samey” levels. It’ s also a lot more work.
One area of PCG that tends to pass this QA test is quilted-content PCG
using premade blocks of content, meshed together on the fly for a varied
experience. This is how the Diablo games make their levels. But it often
produces the least varied experience, as the player gets to recognize the
content blocks and the patterns produced by the generator. Over repeated
plays, it can produce repetitive and stale gameplay.
Concern over QA is one of the reasons we see the most experimenta-
tion in this field from independent developers. Indies often have no one to
report to, little reputation to sacrifice, and are more willing to take risks.
But indies are also often the ones with the least resources and time to build
well-constrained systems or automated testing scripts.
Time Restrictions
PCG is often touted as a time-saver, but there is no guarantee this is the
case. Designing the generator may prove harder and more nuanced than
initially expected, especially in an area for which there isn’ t a lot of exist-
ing code to rely on. Work on it may also continue after completion, as
constant tweaking is needed to adapt to other developments.
It’ s important to assess how much a reliable time frame is needed for
your project. A handcrafted process takes a more predictable amount of
When and Why to Use Procedural Generation ◾ 7
time. You might hope that making a level generator will take less time to
make than hand-designing 10 levels, but you don’ t know that, and in the
end, it might be that 10 levels is just fine for your game.
If money and time are particularly restricted for your game, then think
twice about using significant amounts of PCG, and factor in plenty of con-
tingency to your budget should it not go according to plan.
Authored Experience
In many games, the designer wishes to produce a highly authored experi-
ence. This is particularly notable in story-based games, where you wish the
player to encounter various parts of the game in a linear way. These types
of games benefit less from PCG, and may be made worse if the generated
content doesn’ t fit neatly to the authored experience the developer has in
mind.
This can be made to work, though. In particular, a thorough and well-
crafted procedural game can take into account the player’ s actions and
integrate their impact into the content produced. This sort of integration
can create a far more effective feeling of an authored experience than a
traditional linear game. It also requires a lot of work and great design to
get right.
Another authored experience where PCG is unsuitable is reaction-
based games that present specific timed and placed challenges. The likes of
Super Meat Boy expect the player to fail and repeat the same content over
and over until they master that authored part of the game. They can also
include “ gotcha” moments or clever pieces of design that take the player’ s
thought processes into account, which are harder to reproduce through
procedural means.
Multiplayer
Control of game balance in PCG isn’ t always easy, but it becomes an espe-
cially difficult issue in competitive multiplayer games. In particular, the
likes of maps in real-time strategy games can present challenges, with
starting positions, resources, threats, and topography all affecting how
each player performs. A small difference in balance in a generator can give
one side sufficient advantage to win far more often. This is unacceptable in
games with highly competitive audiences.
Imbalance can be mitigated by having symmetrical maps, but this isn’ t
always desired for aesthetic or other reasons.
8 ◾ Procedural Generation in Game Design
Just Random
If you don’ t have the time and resources to make interesting procedural
content, then typically you end up with something just random. As noted
in Chapter 2, this is often boring and repetitive and doesn’ t make for a
good play experience. Bland, samey content should be avoided, and if
you’ re not able to do PCG properly, then reconsider its use in your game.
Overreliance on PCG
PCG has become a common term in game design and even in game mar-
keting, with games advertising the immense possibility spaces they offer.
But it absolutely cannot be a crutch the game solely relies on. Sheer vari-
ety, even well-designed variety, is not enough if you do not have the core
mechanics and interactions to let the player have fun with what’ s on offer.
No Man’ s Sky in particular has received criticism for promising “ Every
Atom Procedural” but ultimately falling short, causing some to accuse it
of shallow gameplay, despite a massive and beautiful universe. Procedural
content should not be relied on to make your game special, and you should
never lose sight of core gameplay experience.
Utilitarian
A few very practical reasons to generate include the following:
Unique
There are also softer, more subjective reasons to prefer generation:
involves rules, and they can be gameplay rules, as well as simple gen-
erative rules— something the player can interact and play with. This
opens up a gigantic field of new gameplay opportunities.
• Player input: Mushroom-11 uses procedural content in a truly inno-
vative way, having the player control a swarm of cells that regrow
based on simple cellular automata rules. This gives the player a new
form of gameplay through manipulation of PCG techniques. The
player must internalize the behavior of the cellular automata to con-
trol the swarm and overcome the challenges in the game.
• Unpredictable : Even the designer does not know what to expect from
the generators he or she creates. This can be scary, especially from a
QA perspective, but for a creator, it can also be thrilling. It allows you
to experience and enjoy your work in the same way as a normal end
user— something most designers never get to enjoy.
• Living system : Procedural techniques can produce living, reactive
effects. Fire, floods, lava, weather systems, populations, civilizations,
diseases, cultures, life at every level. Hand-designed content will
always appear repetitive when compared with a wild and changing
procedural system. Certain techniques, like neighbor-based decision
making, are tremendous at producing intricate and changing effects
at scale. These feel real to us, because often they are following pat-
terns similar to those that exist in the real world.
• Inhuman creativity : The outputs of PCG can be bizarre. They can
produce things no human might ever think of, from unusual level
designs to unreal animations. YouTube is awash with recordings of
buggy procedural animations in 3D games, producing horrific and
hilarious creations that astound our meat-based brains. Computers
do not think about things in the same ways we do, and sometimes
they come up with logical extremes that are wholly outside the realm
of our imagination.
• Reflections and refractions of humanity : Procedural content is almost
always based on human designed content, even if from small base
blocks. What they produce is a reflection or refraction of our own
creativity. What do we see when we stare into the abyss of Twitterbots
and novel generators? And what do these twisted shadows and
shapes have to tell us about ourselves? Combine this with a system
12 ◾ Procedural Generation in Game Design
that changes based on the player’ s input and you can develop some
thought-provoking content generation. What would a game based
on the player’ s Twitter account and followers look like?
• Inspiration of infinity : Infinity is a hard concept for us to grasp, but
playing with generators of infinite content lets us try to straddle it,
or get delightfully lost in it. A well-constrained generator will make
a dungeon level that fits tidily with your expectations, and can make
you feel the master of an infinite set of dungeons. A wild, uncon-
strained terrain generator will produce forests and fields beyond
your imagination that put you in awe of all that infinity can produce.
• Fun : Ultimately, playing with procedural generators is really quite
fun. To click a button and have a new creation brought into being. To
change a number and click the button again, and the old creation is
replaced by something quite different. To toy, to fiddle, to poke and
prod and experiment, to see what interesting and novel things come
out the other end. Dice and cards have entertained us for millennia,
but now we have computers filled with millions of dice, and we can
make them dance to our own strange tunes. Our living toys, our
endless fun, our design of designers to make more than we could
ever achieve alone. What greater than to create a creator?
Chapter 2
Managing Output
Boredom versus Chaos
Kenny Backus
Independent
but shades of gray, so it’ s actually best to merely be toward the “ prepared”
end of this “ prepared– unprepared” spectrum. There are also always excep-
tions to the rule: when you want to make a game so systematically driven
that having a clear idea of what content should live in it actually limits the
system, you should start making a generator sooner rather than later that
will actually inform the game and content design, rather than the other
way around. If you are pursuing this method wholeheartedly, you should
investigate “ novelty search,” or algorithms that focus on creating things
that haven’ t already been created in the absence of a specific objective.
From a game design standpoint, it’ s very interesting to create a genera-
tor that then actually guides your game design (which then feeds back into
the generator, now that you know what you want), but it often means you’ ll
feel painted into a corner if you end up with a design that’ s just not the
best and leads to generated content that’ s not very pleasantly surprising.
The island generation in Sky Rogue (Figure 2.1), namely, the spawning
and placement of enemies, is an example of this iterative process and grad-
ual discovery of constraints on generated content. Sky Rogue is an action
flight simulator where most of the gameplay occurs on a series of small, pro-
cedurally generated islands or island chains. When starting a new mission,
the player is sent to one of these islands, where a multitude of air enemies are
buzzing around in packs above clusters of lucrative ground targets with sur-
rounding ground defenses. The player must destroy a specifically chosen set
of ground or air targets to proceed to the next island, although they are free
to engage or ignore the other enemy targets spawned on or above the island.
the generator to add a diverse set of properties (fire damage, ice damage,
fire– ice damage, bonus vs. birds?) that can then be cleaned up or balanced
by your generator.
This puts a lot of pressure on the generator to actually understand
the game design, though: Is a sword that does 100 base damage really
equal to a sword that does 50 fire damage and 50 ice damage? If not, just
how unequal is it? Is fighting a dire wolf and a death knight at the same
time more difficult than fighting them one at a time, and by how much?
Quantifying properties like power, difficulty, or value in a way the genera-
tor can use accurately becomes a necessity, something that’ s usually left to
trial-and-error-driven iteration in handmade content.
Ultimately, it comes back to promising a pleasant surprise and carefully
avoiding predictable output. Knowing how to create a convincing illusion
of appropriate randomness is as challenging as generating content in the
first place, but simply knowing that before diving in avoids a lot of pain.
Keep in mind how your players see your generator, rather than seeing the
generator for what you know it is, and try to discern repetitive features
of content that you know is technically unique. From the right perspec-
tive, a million unique items can seem like the same item repeated a mil-
lion times. If patterns can form, find ways to break them, keep the player
guessing about what’ s coming next. If the player stops guessing, if they feel
like they can predict the output even if they essentially can’ t, you’ ve lost
the battle of human versus machine.
Beyond high-level advice, there are a lot of practical, reusable ways to
break up patterns and introduce a bit of chaos to your boredom:
have. Pure randomness always seems like a good idea when the
dice are in your favor. The statement “ t here’ s a 33% chance a mini-
boss will spawn each level” in practice is often better implemented
as “ a mini-boss will spawn every 2, 3, or 4 levels, with the highest
probability being 3.”
Chapter 3
Aesthetics in Procedural
Generation
Liam Welton
Failbetter Games
allowances for, as well as even embracing, the creative differences that are
inevitable when working with a team.
In this respect, it can be useful to imagine your procedural generation
engine as a member of your team that works alongside your other art-
ists and designers, taking into consideration its own strengths and weak-
nesses. The engine is going to be contributing work based on rules that
you have established for it. It’ ll even be granted some creative freedom,
although admittedly this is usually simulated by introducing a degree of
randomness. The procedural generation engine is a team member that can
follow hard-and-fast rules to the letter, but can fall short when it comes to
making judgments in less strictly defined areas.
It is possible to work around this, as long as you identify the strengths
and weaknesses of your procedural generation engine in advance of using
it, and plan your aesthetic design accordingly. Work out where it will need
help and grant more control to your other team members there.
FIGURE 3.1 Before (18 × 18) and after (6 × 6).
26 ◾ Procedural Generation in Game Design
the map that would conflict aesthetically could never be placed next to one
another, we made sure there were neutral, bridging regions between them
so that they would never adjoin.
Eventually, we wound up with a grid of 36 tiles, 24 of which were split
into five regions and 12 of which were located in a fixed position. Each
tile could be placed anywhere within its corresponding region of the
map, allowing for much greater variety than the earlier ruleset allowed.
Restricting tile type to only five regions, rather than subdividing them
further by specific areas, also meant our procedural generation code had a
greater likelihood of creating exciting combinations.
We also established a series of unifying rules around the use of color,
lighting, sound, and music. These are essential for any game, but we found
them particularly helpful. By adhering to stylistic rules, we could avoid
maps being generated with clashes between the atmosphere generated
by the sound and by the visuals. This, combined with the fact that the
game, by design, has long stretches of open water between inhabited areas,
meant that we were able to avoid some of the uglier issues that can arise
when using procedural generation for environment design.
THE RESULT
In the end, the tile-based approach we took to procedural generation in
Sunless Sea was successful. It enabled enough variation to keep the chal-
lenge fresh for players, while allowing us to retain sufficient aesthetic
control to craft the experience we wanted. However, the approach wasn’ t
without drawbacks. Treating each tile as a puzzle piece that could be slot-
ted into various locations meant that more time had to be taken designing
them to fit in every arrangement. We made this easier to accomplish by
providing our procedural generation engine with pieces that were visually
and aurally coherent. If you were to put each asset in a line, you would see
evolution and subtle variation, but they would all be of a piece. The color
palette is restrained and harmonious, contrast levels are consistent, and
shapes and sizes are fairly uniform.
One decision we regret was the attempt to introduce more variety by
creating handcrafted variants of each of these individual tiles and ran-
domly assigning one per play session. This was time-consuming, prone to
human error, and very difficult to debug, which taught us the valuable les-
son that sometimes it is better to accept the limitations of your approach
to procedural generation than to patch over them with manual solutions.
For Failbetter Games’ s expansion to Sunless Sea , Zubmariner , we used a
solution that attempts to accomplish a similar effect, but through proce-
dural logic rather than manual placement.
In Zubmariner , players are given the opportunity to explore underwa-
ter in a submarine. This involves creating an entire subsurface level to the
play area— and would be a daunting task if attempted by hand. Instead,
we are using the rules already established for our surface tiles and hand-
ing over even more control to our procedural generation engine. It picks
from a predefined list of atmospherically appropriate pieces of terrain and
decorations and places them in unoccupied areas of the map at a density
our artist can adjust.
In this way, we can hand over the task of decorating large areas of the
map to the procedural generation engine. We have taken the time to estab-
lish the rules it applies and ensured that all the assets it is using are well
crafted and visually coherent. Now we get to sit back and enjoy the work
that our silent, stalwart team member produces.
Chapter 4
29
30 ◾ Procedural Generation in Game Design
The aim of the modular designer, then, is twofold. Craft modules that
assemble into desirable gestalts, and design an assembly mechanism to
manifest them. The gestalts themselves are out of our direct reach, and
that’ s why it’ s a challenging problem. Of course, what counts as desirable
depends on the aesthetics of the designer. But we assume the designs that
give our system the most play are the favorable ones, especially those that
contribute to our thematic goals for the system.
This chapter sets out to develop a model for the modular paradigm. We
introduce language to help conceptualize the pieces at play, and we famil-
iarize ourselves with the underlying math. Then we suggest an approach
to designing for modularity. We examine material systems as examples,
but we don’ t get into the idiosyncrasies of specific applications, such as
level generation or dynamic puzzles. We leave those challenges to later
chapters.
FIGURE 4.1 Monsters (modules) are chosen by the dungeon populator (assem-
bly mechanism) to populate a dungeon room (gestalt).
* Technically, since we’ re allowing each monster type to be chosen multiple times, it’ s permutation
with repetition and combination with repetition .
† The number of r combinations of a set of size n with repetition allowed is [(r + n – 1)!]/[r !(n – 1)!].
32 ◾ Procedural Generation in Game Design
* Lettering the monsters a , b , c , d , and e , the following combinations comprise all the gestalts that
include two arbitrarily chosen monsters, a and b : aab , abb , abc , abd , and abe .
Designing for Modularity ◾ 33
ENABLING PLAY
What makes a set of modules and an assembly mechanism conducive to
producing desirable gestalts? As mentioned earlier, our goal is to give our
system as much play as possible. Again, by giving our system play, we mean
enabling players to explore the greatest amount of the compelling space
created by the rules of our system, within some thematic constraints. Let’ s
examine three principles of modular design that work toward enabling play.
We’ ll use examples from Sproggiwood , a roguelike game I designed and
released in 2014 with Freehold Games, to illustrate the principles in practice.
Mechanics as Shared Substrates
If certain combinations of modules assemble into desirable gestalts, then
it stands to reason that there’ s some definable relationship between mod-
ules that assemble desirably. Consider this straightforward example of
such a relationship: two pieces of equipment that each grant some bonus
when the other is worn. This design pattern occurs regularly in RPGs in
the form of set pieces. From the assembly of these two modules, we get a
desirable gestalt, in this case the equipment loadout and its corresponding
set bonus. But this relationship tightly couples the two modules, and in
doing so, it prevents either of them from assembling meaningfully with
other modules. While we gain a desirable gestalt, we lose a big swath of
our gestalt space to the null zone. For this reason, I contend that direct
relationships like this one are detrimental to the goal of enabling play.
Accordingly, I dislike the design of set pieces.
Instead, we can relate modules indirectly by using the language of our
game’ s mechanics to define them. Each mechanic acts as a substrate for
our modules to act in. For example, consider the following two pieces of
equipment for an RPG. The first piece is a lance that deals bonus damage
equal to your movement speed. The second piece is a pair of boots that
increases your movement speed by 20%. We can see how the assembly
of these two modules produces a desirable gestalt. But they aren’ t tightly
coupled, and so we haven’ t confined other potential gestalts to the null
zone. Each module can be combined with other modules that are defined
in the language of the game’ s movement mechanics to produce more
desirable gestalts. By avoiding the prescriptive design of set pieces, we give
our players more options for meaningful combinations.
The key to this approach is choosing a suitable suite of mechanics to
act as substrates. The more central a mechanic is to our gameplay, the
more play we can enable by designing modules in the language of that
34 ◾ Procedural Generation in Game Design
1 2
Orthogonality
In the context of a modular design and a set of game mechanics, orthogonal-
ity refers to the partitioning of the design into modules that don’ t overlap and
whose gestalts span the space of gameplay prescribed by the mechanics. It’ s
easy to see why that second part— spanning the space of gameplay— works to
enable play. The first part is a little trickier, though, so let’ s examine it.
When the majority of the designs for two modules overlap, the gestalts
that include either module have the potential to counterfeit each other,
meaning they replicate each other’ s place in the gestalt space and effec-
tively reduce the number of distinct, desirable gestalts. Let’ s revisit the
example dungeon room with the black jelly puddle, frog, and lily pad.
Remember that the jelly puddle spawns another jelly unless the player
walks over it within seven turns. Imagine we had designed another type
of jelly monster that leaves behind a similar puddle— say, a purple one
that spawns two jellies unless walked over within nine turns. The example
dungeon room and the dungeon room that includes the purple jelly pud-
dle counterfeit each other. They present challenges that are virtually iden-
tical. Moreover, these designs compromise each other’ s thematic identity,
muting the resonance each has with the player.
36 ◾ Procedural Generation in Game Design
• Yellow jelly—leaves behind a puddle that causes walkers to slip one tile
• Blue jelly—leaves behind a puddle that causes walkers to slip one tile,
and deals poison damage
• Red jelly—explodes in a cross pattern one turn after it dies and dam-
ages anything it hits
• Black jelly—leaves behind a puddle that causes walkers to slip, and
must be walked over within seven turns or spawns another jelly
• Purple jelly—leaves behind a puddle that causes walkers to slip, and
shoots a lightning bolt that triggers other purple puddles
• Ice jelly—explodes in a cross pattern one turn after it dies and freezes
anything it hits
Note that we didn’ t achieve total orthogonality. The yellow jelly’ s pud-
dle is subsumed by all the other puddles, and the red and ice jellies present
very similar challenges. It’ s difficult to get all the way there, both because
some overlap is inevitable when designing thematic monsters and because
spanning the space of gameplay, or even articulating the whole space, can
be challenging. However, it’ s useful to let orthogonality play a role in your
design decisions.
Designing for Modularity ◾ 37
Equivalence of Impact
An overshadowing module is one whose impact is so powerful that it dis-
torts the gestalts it gets assembled into. Similar to how overlapping mod-
ule designs can counterfeit gestalts, overshadowing modules can flatten
the dimensionality of gestalts by compelling so much action that other
modules can’ t compete. Think of the negligible effect other massive bodies
on Earth have on the planet’ s gravitational pull. No matter what the bod-
ies are or how they’ re positioned, they’ re dwarfed by Earth’ s monumental
force.
It’ s unrealistic and undesirable to expect all our modules to converge
to a single impact value, but it’ s a reasonable goal for most of our modules
to fall within a certain impact range. We can adhere to this principle by
designing modules with roughly equivalent impact values and by ensur-
ing our assembly mechanism rarely combines modules whose impact val-
ues are wildly disparate. Note that it’ s not enough for the average impact
values of our gestalts to be similar if the impact values of our modules are
distributed unevenly. This is because an outlier module can render the
gestalt undesirable even if the gestalt has a suitable average value.
For an example of an overshadowing module, let’ s look at how out-
of-depth encounters work in Sproggiwood . The dungeon populator in
Sproggiwood has a chance to produce an out-of-depth encounter, where
a difficult monster from a later dungeon appears in an earlier one. These
encounters add spice to the dungeon population mix, but they do so at
the potential cost of overshadowing the other modules in their gestalts.
The easiest way to illustrate this point is to imagine entering a dungeon
room at one-fourth your total hit points and seeing an out-of-depth mon-
ster. No matter how interesting a tactical situation the other challenges
in the room might present, the presence of the big baddie compels us to
flee (Figure 4.5). This is a principle we understand from other spheres of
design insight; an unbalanced encounter can be unfun. But it’ s useful to
consider it in terms of the effect it has on our gestalt space.
In Sproggiwood , far out-of-depth encounters are rare. We engineered
the dungeon populator to produce out-of-depth monsters at a clip that
adds spice without compromising too much gameplay. Another option
is to tweak your assembly mechanism to pair out-of-depth encoun-
ters with out-of-depth rewards. For example, a difficult monster might
guard a powerful sword. This approach still runs the risk of flattening the
38 ◾ Procedural Generation in Game Design
FIGURE 4.5 A yeti looms over the battlefield. No matter how interesting the rest
of the encounter is, we’ re forced to flee.
dimensionality of the gestalt, but it also adds a new dimension that could
be worth the compromise in the right situations.
the far future, long after an apocalypse of unknown origin, where mutations
have uplifted certain animals to human-level intelligence and beyond. In our
original design, players would find animals from several different species in
the same zone. Most of the animals would act aggressively toward the player
and ignore each other. We wanted to add interspecies conflict to give the
world more thematic texture and dynamism. Specifically, I imagined a sce-
nario where a player stumbles on a fight between a troop of baboons and a
herd of goats, two groups that often inhabit the same zones in Caves of Qud .
I also imagined that occasionally these groups would be fighting for a ridicu-
lous reason; I wanted to match the tone of the game’ s frequent forays into the
absurd (Figure 4.6). I thought, “ What if a named baboon leader was hated by
goats for some esoteric reason that no baboon or goat would normally care
about? And what if that dispute triggered a battle?”
This imagined gestalt led to the design of a faction system where animal
groups’ behavior patterns get modified by the procedural histories of their
faction leaders. When a faction leader is generated, they’ re given a small
backstory with one to three procedurally chosen factions. That backstory
determines whether the factions like or dislike the leader, which in turn gov-
erns an animal’ s behavior when it’ s generated in the same zone as the leader.
The system ultimately expanded on this idea and yielded many more
interactions than I initially conceived. Animal factions find strange allies
in each other, and players can share water with faction leaders to alter their
reputations with the factions that like or dislike the leader. The exercise of
plotting desirable gestalts gave me a kernel to design around and pushed
the design into unexpected territory.
FIGURE 4.6 A baboon leader angers goatfolk with its radical ideas about
mathematics.
40 ◾ Procedural Generation in Game Design
FIGURE 4.7 Three identical weapons for three player classes. The repetition
diluted the thematic impact of the weapons and made them feel boring.
to the player classes. For example, the farmer class got a grappling pitch-
fork that could be shot at walls to slide the player along the grid toward
the wall. Even though we lost out on desirable gestalts by confining that
effect to the farmer class, the benefit of an exciting, thematically resonant
weapon made up for it.
Ultimately, your adherence to the principles of enabling play should be
in service to your vision for your game. When the principles run afoul of
that vision, don’ t be afraid to subvert them.
REFERENCE
Salen, K., and Zimmerman, E. 2004. Rules of Play: Game Design
1.
Fundamentals. Cambridge, MA: MIT Press.
Chapter 5
Ethical Procedural
Generation
Dr. Michael Cook
Independent
we should let generators do, how we should talk about them, and how we
should let them talk about the world.
TALKING IN CODE
A procedural generator encodes a lot of different ideas and knowledge
into a tiny package of rules and procedures. Each time we run it, those
rules and procedures unpack bits and pieces of the knowledge we fed in,
and reassemble them into something new. Some of the ideas we feed into
our generator are technical, and a lot of this book is given over to the
broad and complicated technical challenges that surround procedural
generation. We’ ve already seen some of this in earlier chapters about
modular design and balancing chaos with predictability. Other ideas are
aesthetic or artistic in nature. Procedural generators encode our ideas
about how we think games should be designed: they represent what we
think a good dungeon looks like, how a good story should end, or what
makes a beautiful color scheme. They’ re little digital apprentices that we
train and then trust to finish bits of our artwork in the homes of the
people who view them.
Creating a procedural generator is a bit like making a work of art— some
of the things we put on the canvas are intentional, but other things we
paint on might be unconscious acts we don’ t give much thought to. Some
might simply be mistakes. When we tweak the maximum size parameter
of our dungeon generator, we most likely know the effects it will have on
our level difficulty, or how long our game takes to play— that’ s an example
of a conscious decision. But there are lots of ways in which we can intro-
duce accidental features to our generators, sometimes without even think-
ing. The tricky thing about this is that it can be very difficult to realize
this has happened, because generators are often quite complicated, and
are designed to generate huge quantities of content. If there’ s something
wrong in the system, it might be hard to tell without looking at thousands
and thousands of examples.
Let’ s explore an example of a system that ends up with an unexpected
feature in it. Suppose we’ re making an RPG level set in a spooky grave-
yard, and we want the player to be able to read randomized inscriptions
on each tombstone. We decide to do this using a few simple patterns, so
we write a few templates for gravestone patterns, like “ #NAME lies here,
died #YEAR.” Our templating system knows that when it sees #YEAR, it
replaces it with a random four-digit number, and when it sees #NAME, it
generates a random name by sticking a first name and a last name together.
Ethical Procedural Generation ◾ 45
Ban lists are great if you’ re working with language because they work
by filtering the output of your generator, which means they can catch mis-
takes in generators that you might not ever have predicted. The original
Elite , released in 1984, had a name generator for star systems that would
stick together small collections of letters to make long words. The develop-
ers spent some time tweaking this system to make sure it never generated
anything rude— a ban list can help by checking the output of even the
most random words and strings of letters. But they don’ t solve everything,
and data from the outside world can be a real source of danger when build-
ing experimental procedural generators. To give you an idea of why, we’ re
going to look at another game that, like Argument Champion , used online
data. This game was called A Rogue Dream , and was originally made in
2013 for the 7-Day Roguelike jam (Figure 5.1).
The principle behind the game was quite simple— the player types a
noun into the game at the beginning, and the game procedurally generates
a theme for itself so that the main character of the game is the noun the
player input. So, for instance, if the player types in “ cat,” then they control
a little cat sprite, avoiding droplets of water, eating grass, searching for
cardboard boxes, and using powers called “ Scratch” and “ Sleep.”
The way the game did this was by using a technique called “ Google
milking,” coined by researcher Tony Veale. Google milking works by
reverse engineering the language of question— asking to get information
about the world. When someone asks Google, “ Why do doctors wear white
coats?” a likely reason for them asking the question is that they believe it
to be true. They’ re looking for a reason, but the fact that doctors wear
FIGURE 5.1 Screenshot of A Rogue Dream where the player is controlling a cat.
Ethical Procedural Generation ◾ 49
white coats is considered something true— we can extract the factual part
out of the question and use it as knowledge about doctors.
The more people ask a question, the more people presumably believe
the facts of the question to be true— but how do we know which questions
are popular? Google autocomplete can tell us, because it’ s trained to give
us the most popular search queries. So if we type “ why do doctors” into
Google, the search queries it suggests are the most common things people
ask about doctors. Why do doctors wear white coats? Why do doctors say
stat? Why do doctors prescribe steroids? Our game might not know the
answer to these questions, but it can use these things to understand more
about what a doctor is.
So if you type “ why do cats hate … ” into Google, you get “ water” as an
autocompletion; if you type “ why do cats eat … ,” you get “ grass,” and so
forth. Each of these specialized queries is used by the game to generate its
enemies, pickups, goals, and ability names. A Rogue Dream is entertain-
ing to play, because unlike many knowledge databases, like ConceptNet,
Google is packed with popular culture, everyday observations, and slang.
If you choose to be a ninja, you’ ll be fighting pirates. If you choose to be a
musician, you’ ll be fighting music sensation Kenny G. If you choose to be
a nihilist, your health packs are floating clouds of darkness.
But you might be sensing a problem here, and indeed, A Rogue Dream
did not get very far in development before unfortunate things started hap-
pening. While a lot of the most generic, innocent queries produced fun
game themes, others carried more weight. If you typed in “ priest,” as the
player character, one of your abilities would be “ abuse child.” If you typed
in “ man,” your enemies were women. If you typed in “ Muslim,” your abil-
ities included “ k ill.” People don’ t just type into Google things that they’ ve
directly observed— they type in stereotypes, rumors, misconceptions,
hate speech, conspiracy theories, and worse. A Rogue Dream , unable to
tell the difference between people who see cats eating grass and people
who think French people are lazy, ends up collecting all this information
and using it as fact.
It’ s difficult to throw away work, and it’ s hard to admit an idea is bad.
A Rogue Dream was almost developed into a museum exhibit for children
to interact with and learn about procedural generation. But after weeks
of trying to filter the system, improve its understanding, limit its search
capabilities, or change its purpose, it was abandoned. Now it’ s mostly used
as an example of how procedural generators with the best of intentions can
end up being harmful— which, as it turns out, is quite useful. Hopefully,
50 ◾ Procedural Generation in Game Design
it’ s also a great reminder of why it’ s important to think about the ramifi-
cations of the systems we build from an ethical standpoint.
particular player. But we always run the risk of encountering the worst
side of human creativity with this, and that can be something that is hard
to recover from. Just because opening up our generators is potentially
dangerous doesn’ t mean we shouldn’ t try to experiment and see what new
systems and games we can build. But we need to be aware that these prob-
lems are out there, and do what we can to design our systems to limit these
bad outcomes. One way we can experiment in this area while limiting the
bad outcomes is to restrict the ways we take input into our generator. If
our generator can be given strings of words, then instead of letting our
users have totally free input, we can limit them to a set of a few hundred
words to express themselves with. If our generator uses artwork, we can
let our users snap shapes together instead of allowing them completely
freeform drawing. People will always try to circumvent whatever systems
you give them, but a few restrictions here or there will make life easier and
your generator safer.
Before we close out this section, let’ s dwell a moment longer on Tay,
because in many ways the story of Tay is a good explanation of why this
chapter matters, and why it might have an impact on your game. One of
the reasons why the response to Tay was so negative and so critical was
that once a piece of software is given bad patterns of behavior, the people
who see it repeat those patterns don’ t think about who taught them to it.
They only focus on what the software is doing. If our generator starts pro-
ducing offensive or other kinds of bad content, people won’ t blame Twitch
chat— they’ ll blame our generator. It’ s a totally reasonable response, and
something that should motivate us to do our best to be responsible in what
we build, who we let it talk to, and where we let it do its work.
how to promote games in particular: advice about who you should talk to,
what you should talk about, and how you should phrase it. Even if you’ ve
never read a thing about promotion, you’ ll probably have noticed common
patterns in the way other people talk about their games or describe them
in stores. It’ s important to summarize things, to focus on the most impor-
tant points, to get across the essence of what it is that you’ ve made, and to
emphasize what makes your game special. What sets it apart? What makes
it unique and worth talking about?
Procedural generation is still a powerful selling point for video games.
Steam has a tag dedicated to it, and many curators recommend games
solely for the presence of procedural generation in them, but games with
generators have been popular for a very long time. “ The heart of Diablo is
the randomly created dungeon,” states the very first page of the original
Diablo design document, “ providing a new gaming experience every time
Diablo is played.” Even though it can feel like so many games have proce-
dural generation these days, people are still interested in it. So it’ s natural
for it to come up when talking about games.
It’ s also very easy to get carried away when describing something amaz-
ing that you’ ve created and are proud of. So when we talk to people about
procedural generators, often we say things that express how excited we are,
without thinking about what they really mean. Let’ s go back to that state-
ment from the Diablo design document for a second: “ a new gaming expe-
rience every time Diablo is played.” What does that actually mean? Does
it mean the game mechanics change? If you’ ve played Diablo , you’ ll know
that’ s definitely not the case— you’ re clicking on zombies and casting spells
no matter what happens. Does it mean the levels change? Well, sort of. They
look different and have different layouts. You couldn’ t memorize a level and
run it twice, certainly. But you’ re always going to the same places— the same
caves, the same villages. They are shaped differently but painted the same.
That might sound unfairly harsh on Diablo , because we know what
they really mean by “ a new gaming experience.” It’ s a euphemism, like
a lot of language about procedural generation is: “ limitless gameplay,”
“ infinite replayability,” “ endless variety.” These are all phrases we see used
to describe algorithms that are usually doing the computer equivalent of
shuffling a deck of cards and dealing you a new hand. Over time, we’ ve
grown so used to these turns of phrase that we probably don’ t think much
about the language any more— we instinctively know what the person
speaking them means, so we don’ t think about how they sound to people
who are less familiar with these ideas.
Ethical Procedural Generation ◾ 53
Relying on people to “ k now what we mean” when we talk about our
work isn’ t a very good idea. People might learn over time, but all we’ re
really doing is passing the problem on to a new community of people who
will make the same mistakes. More importantly, as this book shows, new
ideas are coming out of the procedural generation world every day. When
we try to explain or sell these ideas to people, there will be hardly anyone
who knows what you mean. You’ ll be deciding how people understand
your work, and what expectations people have when they buy your game.
A good example of this is the idea of “ uniqueness” in procedural gen-
eration. A lot of games try to count how many different dungeons or items
their game has, and use it to illustrate how big their procedural generator
is. The 2009 shooter Borderlands proudly stated the game’ s 17.5 million
guns as a key part of its marketing campaign— it even managed to find
its way into the Guinness Book of World Records with this award. But if
we made a copy of a gun in the game and added one point to its dam-
age, most people wouldn’ t consider the two very different except in the
most legal, technical sense. Even if we kept adding damage points until it
felt different, we’ d probably end up in a situation a little bit like Diablo ’ s
dungeons— they’ re distinct from one another, but not unique.
What’ s wrong here? We’ re not specifically lying; we’ re just being a little
misleading or unclear with how we’ re talking about the game. It prob-
ably comes from a good place, from a feeling of excitement and positiv-
ity the developers have about their game. When we put a big number in
front of someone, though, we’ re leaving it up to them to guess at what
percentage of that number will be interesting, useful, fun, or relevant. If
they’ re familiar with procedural generation in games and its limitations,
they probably won’ t mind! But if they’ re less experienced, or perhaps
you’ re offering something new, then there’ s more of an opportunity for
misunderstanding.
That doesn’ t mean we can’ t be passionate and excited about our work,
of course! It just means that we should think carefully about what we say
and write about what we make. Sometimes it can be as simple as changing
the kind of language you use. In Spelunky , the game tells you “ the walls
are shifting” as a new level is generated. It’ s a small and elegant phrase,
but it tells you everything you need to know: the levels are being shuffled
around; they aren’ t entirely new, but they’ re different to what you just saw.
It doesn’ t promise too much, and it slots neatly into the game’ s theme.
Another approach is to think more carefully about what makes your pro-
cedural generator fun. In many ways, advertising millions of guns or billions
54 ◾ Procedural Generation in Game Design
of levels doesn’ t really make much sense— the average player will probably
only see a few thousand. So what is it that makes our generator cool? What
does it do that makes us smile or want to see more of what it produces?
Maybe it actually produces a lot of rubbish, and maybe that rubbish is what
makes the rare discoveries of something good so wonderful and exciting.
Instead of avoiding these ideas, we can play into them and build our game to
be more strongly based around these ideas of rarity and surprise.
Everyone will have their own idea of how to talk about their procedural
generation, what kind of language they feel comfortable using, and what
story they want to tell people about their game. Don’ t feel like you need
to take everything we’ ve discussed here at face value, but do bear some
of these ideas in mind the next time you tell someone about a procedural
generator.
THE FUTURE
One of the great things about working in procedural generation is how
fresh and unexplored most of the field is. Although games have had pro-
cedural generation for many decades now, we’ ve spent a lot of that time
doing the same things over and over. We’ re getting really good at them
now, but there are a lot of things that people have never even thought of
yet, let alone actually attempted. This book will give you a lot of inspir-
ing ideas to consider and experiments to try, and hopefully inspire some
things that we’ ve never seen before!
With that excitement of pioneering comes the responsibility of being
the first people in a strange new land. It means we should tread a little
more carefully in case something unexpected happens, and that we should
be prepared to think in new ways and break old traditions if the situation
demands it. It also means that the things that we do now, the problems we
decide to solve, the issues we consider important— these become examples
that are set for the people who come later. All the ethical topics in this
chapter do matter, even if they seem trivial right now, because by valu-
ing these issues, we make them valuable for the generations of procedural
generation enthusiasts who will follow us.
Each reader will have a different response to this chapter, agreeing with
some things, ignoring others. All that really matters is that you’ ve thought
about these things long enough to decide what they mean to you, and what
you want to do in response. We hope you’ ll bear some of them in mind as
you enjoy the inspiring chapters in the rest of this book, and as you build
generators of your own in the future.
II
Procedural Content
55
Chapter 6
Level Design I
Case Study
Chris Chung
Independent
OVERVIEW
What does a suitable level for Catlateral Damage look like? Since the game
is a cartoony simulation of a realistic scenario (mischievous house cats
making messes), the levels should be simplified versions of somewhat real-
world interior locales. Each locale is a one-floor interior space divided
into rooms that serve specific purposes. For example, a standard house
should have a bedroom, bathroom, kitchen, and living room, and each
room should contain certain objects that are appropriate for the room
(Figure 6.1). Levels should have lots of different physics objects for the
player cat to interact with in places where the player can reach. Therefore,
furniture should be spread out around the rooms at tiered heights (so they
act as platforms for the player) and covered with objects. An easy way to
think about levels is that each one is a building divided into rooms that
are filled with furniture with physics objects on top. Objectives should
obviously be achievable within a reasonable amount of time for all
generated levels, too.
Generating levels happens in three steps. First, a big rectangular area is
cut up into smaller rectangles for rooms with open doors between them.
Then, each room has appropriate furniture placed within it according to
the type of room (e.g., the refrigerator is only placed in the kitchen). Finally,
the physics objects that the player will interact with are placed on top of
the furniture. Once the level generation is complete, the level’ s objective
and time limit is generated based on the makeup of physics objects that
were placed. When everything is ready, the player is placed in one of the
rooms and can start making a mess!
FIGURE 6.1 Standard bedroom from the first level of the game.
Level Design I ◾ 59
THE RULES
The rules of the procedural level generation system were designed around
the core mechanics of the game (enhanced, cat-like, first-person shooter
movement mechanics and knocking around physics objects) and what
ideal locations for a destructive cat would be. A couple of limitations were
decided on early on: levels will only be interior spaces (buildings), and
each one will be a single floor. Constraining levels to interior spaces sim-
plified the level creation process and made levels feel nicely contained.
Outside gameplay was not the intended direction for this game; indoor
spaces seemed like they would be more fun. There are also the additional
considerations of what the boundaries of an exterior space would look
like, how to limit it without making it feel too constrained, and if there
would actually be enough objects to knock down. Focusing on a single
floor was entirely to keep level creation simple, specifically to not have to
handle generating additional floors and the placement of stairs.
With the building limitations decided, the rooms that fill the building were
considered next. There should be at least one room in a building, they should
take up space based on their intended function, they should be able to limit
how many doors are connected to them, and each one should know what fur-
niture is allowed inside of it. For the sake of simplicity, only functional rooms
(e.g., bedrooms, kitchens, and bathrooms) are put in buildings; spaces like
entryways, hallways, and closets are not included due to their specific place-
ment requirements and typically small sizes. The room rules all exist to make
the level feel more believable rather than completely random. Being able to
specify how much space each room should take up allows the system to cre-
ate more suitable rooms; living rooms, kitchens, and dining rooms should be
fairly large, while bathrooms should be quite small. Limiting the number of
doors connected to a room restricts private rooms (bathrooms and bedrooms)
to only one door while allowing public rooms (living rooms and kitchens) to
have multiple. The list of furniture allowed in each room is vital for conveying
the purpose of each room to the players while they are playing in the level.
While the building and room rules exist mostly for aesthetic reasons,
furniture rules exist primarily for gameplay reasons. Furniture should be
placed in a visually interesting way, but the main concern is to not hinder
the players’ movement or block their completion of the objective. Typically,
a real room layout addresses both of these since furniture is usually spread
out around the room and does not block other functional aspects of the
room or other furniture (e.g., room doorways and wardrobe doors). The
60 ◾ Procedural Generation in Game Design
HOW IT WORKS
The rules of the procedural generation system are made up of several pieces of
hard-coded data. The game takes this data, adds some randomness, builds a
two-dimensional (2D) floor plan (Figure 6.2), and creates the 3D space. There
is one data file for each level type that specifies how large the level is, what
rooms are in the level, what textures to use for the walls, floor, and ceiling, and
more. The generation code uses a squarified treemaps algorithm to take the
big rectangle space and divide it up into smaller rectangular spaces (as close to
squares as possible) with the values specified in the level’ s data file.
Each room in each level also has an associated data file. These files con-
tain the list of furniture that can be placed within the room, with some
information, like the maximum number of each type of furniture to be
placed, the probability of the furniture being chosen, if the furniture
Level Design I ◾ 61
should be placed along a wall, and if the player will spawn there at the
beginning. The furniture objects themselves consist of a model, physics
colliders, an invisible rectangular bounding box (to prevent overlapping
with or being placed too close to other furniture), and some rectangular
surface area objects where physics objects can be placed.
In order for the system to know what physics objects to place, there
is a script attached to the surface objects on each piece of furniture that
contains the list of physics objects allowed on it, along with corresponding
probabilities and rotation information. These surface objects are just rect-
angles on different areas of the furniture (e.g., the shelves on a bookcase)
within which physics objects are placed based on the information included
in the script. The generation code uses a rectangle packing algorithm to
place the rectangular boundaries objects within the surface areas.
Once all physics objects are placed, the procedural system records
and tallies all the physics objects in a dictionary and decides what the
primary objective, secondary objective, and a bonus object that is worth
more points will be. These are always a percentage of the total number of
the objects in the level so the objectives are all attainable. The time limit
for the level is simply calculated by multiplying the primary objective by
a time estimate of how long each object takes an average player to knock
down. Through testing, it was found that it took about 1.4 seconds for
players to knock over 1 object on average, so an objective of 150 objects is
given a time limit of 210 seconds, or 3 minutes, 30 seconds.
62 ◾ Procedural Generation in Game Design
CONCLUSION
Overall, the procedural level generation system built for Catlateral Damage
creates varied levels that both look natural and are enjoyable by players of
all skill levels. The system not only creates desirable outcomes, but also
has some flexibility for creating handmade content within the ruleset. For
example, it’ s possible to group related furniture (e.g., a dining room table
with chairs) or an arrangement of physics objects (e.g., a row of books) to
be placed all at once.
Feedback from players indicates that most people don’ t notice that
the levels are procedurally generated. This could be both good and bad,
because although the system creates levels that are good enough for the
player to assume they are handmade, they may also assume there is a lack
of content (nine static levels rather than nine types of levels that are gener-
ated procedurally).
The system also isn’ t perfect. There are rare instances where furniture
placement in some rooms is off, like when washers and dryers and the sink
block the toilet in small, thin bathrooms. Minor polish items, like adding
a permanently closed front door, and bigger functions, like multiple floors,
would have been nice to have given more time and/or programming expe-
rience. Even so, this system works great for a silly and casual game like
Catlateral Damage !
Chapter 7
Level Design II
Handcrafted Integration
Jim Shepard
Independent
STANDARD DUNGEONS
Goal : Expand standard “ room and hallway” gameplay to include areas
that make the best use of Dungeonmans ’ position and motion-based player
powers and help the game’ s dynamic enemies shine.
Room data : The data is stored simply as text files, with ASCII charac-
ters representing tiles one to one (Figure 7.1). While the blocks of data are
x × y bound rectangles, the actual room data may contain an irregular
shape. This is important, as the process of placing and layering the rooms
is much more interesting with nonrectangular shapes.
63
64 ◾ Procedural Generation in Game Design
1. External room walls are not included, as the game adds those as part
of the area gen code.
2. Data does not include enemy spawns or treasure locations. I didn’ t
feel those were necessary for the game since the area gen code does
a pretty good job of packing the rooms, and I didn’ t want treasure
locations to feel stale. The standard dungeon is the bread-and-butter
adventure area, and these locations would be seen often, so treasure
locations shouldn’ t be static.
Standard dungeon area gen : The area gen code builds out a dungeon
using a time-tested algorithm that extends new dungeon content from
existing areas. This is an iterative loop that continues until you reach a
desired room count or simply run out of dungeon space.
Starting environment : Define the size of your playfield, and define each
tile as unused space . This is not the same as an empty floor tile; this is a
block of undefined protodungeon, a blank slate ready for expansion.
Then, place down a starting room somewhere in that playfield. Generally,
this room includes the stairs back up, unless you’ re feeling cruel. With a
single room full of walls and floor tiles, you’ re ready to begin.
from the list of handcrafted areas, and then place the room against
the candidate along any given alignment.
3a. If the room fits, excellent. Add a door at the candidate’ s old position, and
recalculate your new candidates given the new shape of the dungeon.
3b. If it does not fit, that’ s ok. Don’ t place anything; just go back to Step
1 with your existing collection of candidates and rooms. It is possible
to dynamically carve up rooms to fit, but there are two drawbacks.
The first is that you naturally end up with more simple rectangular
areas, and the second is that you lose whatever design value went
into building the rooms in the first place.
4. Once you’ ve placed a room, convert any unused space tile that is
adjacent to a floor tile into a wall (Figure 7.2).
Take note of the second room fitting into the empty space around the
first. Even though the data is stored in a rectangular format, building
Step 1 Step 2
Step 3a Step 3b
Step 4
empty space into the data allows us to fit together rooms in a more
interesting fashion.
Once this is done, you can optionally go back and spice up the
environment a bit, such as
• Find walls that are between two rooms that don’ t have doors
nearby, and add one. This creates the possibility of circular
routes, which are excellent at reducing backtracking.
• Find doors along long empty walls and add a second (or third)
door adjacent, to create a wider opening and prevent easy funnel-
ing of enemies into narrow areas.
• Secret doors! A staple.
The handcrafted rooms for standard dungeons exist to provide
shapes that are fun places to fight in. A mixture of large areas and
small, twisting paths and grand hallways, tight clusters of rooms and
open arenas with cover. You will want to make lots of them, as the
player will see them often, and you want your combinations to have
great variety (Figure 7.3).
CRYPT GENERATION
Goal : Similar to the standard dungeon generation, we want to arrange
handcrafted areas procedurally to build the level. However, the areas are
very specific in shape and size, with the ultimate goal of creating tight
catacomb-style areas interspersed with chambers for breathing room.
Room data : Each room is a 7 × 7 block, with indicators for exits: north,
east, south, and west. The rooms themselves have additional data for treasure
locations, as well as statues, to help sell the creepy crypt-like environment.
These rooms will be placed out on a grid where exits match. They won’ t all
be solid rooms— as you can see (Figure 7.4), some of the edges have multiple
loose openings, which when aligned together make for areas that appear to be
larger rooms, endcaps, or even the occasional open atrium. In Dungeonmans ,
these rooms are sorted into four lists, one for each cardinal direction. This
means some rooms appear in more than one list, and that’ s fine.
Step 1: Place a starter room. This is a random room tile with at least two
exits. From here, we can run the code shown at the end of the chapter
until we’ re satisfied (or dissatisfied!) with the results.
Level Design II ◾ 67
Step 2: Pick a room placed in the level that has an open exit. Note the
direction of that exit (i.e., north) and then draw from a list that has
available exists in the south.
Step 3: Place that new room perfectly adjacent to the first. Recalculate
rooms that have exits, and return to Step 2.
68 ◾ Procedural Generation in Game Design
Step 4: Once you have no rooms with available exits, you can evaluate the
dungeon and see if you like the layout. For example, in Dungeonmans
a crypt is invalid if it doesn’ t contain enough total room placements.
In this case, it’ s tossed out and we start over from Step 1.
Crypt areas feel markedly different from standard dungeons, and this
feeling is complemented by both the art in the crypt and the enemy styles:
hordes that pressure down a hallway, and lots of ice enemies with control-
ling powers (Figures 7.5 and 7.6).
BEST PRACTICES
Here are some pertinent points gleaned over the development process of
Dungeonmans .
Keep the data simple : Fast iteration was super important for these
areas, as was the ability to create a multitude of them quickly. Simple
text files managed in a simple text editor, loaded with a simple process.
Level Design II ◾ 69
Dungeonmans is a tile-based game, and text files fit perfectly. Use the sim-
plest possible data format for your project.
Keep the data lean and purposeful : Don’ t feel obliged to fill out every
detail of your handcrafted areas, especially if they are being used as ran-
domized pieces of area generation. Rely on your procedural systems to
populate them with creatures, treasures, and traps. Too many specifics
in your encounters will allow players to recognize every threat in an area
upon entry, which is probably not desirable. If you do place specifics, make
sure you’ re doing it for the right reasons.
Don’ t write an editor : Stopping your development flow to build a new editor
by hand is the surest way to get lost in the weeds. Text files are easy to manipu-
late, and you can do so in Notepad, which may be nature’ s perfect fruit. If your
game requires more complexity, first double-check that it actually does, and if
so, look into one of the many already existing tools for data manipulation that
are quick, clean, and well tested. Don’ t pour time and energy into a compli-
cated system that will cause more frustration than it is worth.
{
DetermineDungeonWidthAndHeight();
PlaceStarterRoom();
RoomCount = 0;
GoalCount = 20;
NumberTries = 0;
70 ◾ Procedural Generation in Game Design
Candidate c = GetRandomCandidateFromJellybeanBag();
TestRoom room = GetCopyOfRandomRoomFromData();
//don’
t actually place the room here, just
position it
//and check for overlap with the existing rooms
if( !TryPlaceRoomAdjacentToCandidateInOpenSpace(c,r
oom, out location) )
{
//oops we didn’
t succeed
//delete the room if you aren’
t in a GC
language ^^
continue;
}
ActuallyPlaceRoom(room, location);
RoomCount++;
}
//now you can fiddle with the layout by introducing doors
//laying out traps and secrets too!
//then fill it with monsters
}
{
//During loadtime sort the room data into four lists
based on N, E, S and W exits.
DetermineDungeonWidthAndHeight();
RoomCount = 0;
Level Design II ◾ 71
GoalCount = 40;
NumberTries = 0;
PlaceRoom(nextRoom, location);
RoomCount++;
}
//If we didn’
t make enough rooms, start over
if( RoomCount < GoalCount )
{
Cleanup();
Return E_DungeonInvalidTryAgain;
}
//Salt dungeon to taste
}
Chapter 8
Evan Hahn
Snowed In Studios
• Architecture
• Object placement
• Enemy placement and spawning
ARCHITECTURE GENERATION
We used a divide and conquer approach to generate our architecture. A
complete building or dungeon will typically be complex as a whole, but
fairly simple when decomposed into small individual sections.
The approach starts by determining the bounding area of the structure,
which will then be divided into smaller regions using a recursive process.
These regions provide a starting point where an algorithm can decide the
high-level layout of the individual rooms and how they should be con-
nected. Finally, the individual blocks and objects that will produce the end
result will be placed using a number of techniques.
In total, there are seven main steps to this process:
4. Place connections.
5. Assign region types.
6. Make adjustments.
7. Generate the regions.
FIGURE 8.3 Recursive splitting at depths 0, 1, and 2, and the final result.
Occasionally, we would also stop dividing early in order to get a bit more
variety and larger regions.
The approach used to choose the splitting axis will affect the result.
Some simple approaches to dividing the region include:
• Split along a random axis : Generates the most variety, but it is the
most unpredictable and sometimes produces undesirable results.
• Always split the shorter axis : Generates long narrow regions. This
provides boring results if used alone, but it works well with hybrid
solutions to provide more variety in region shapes.
• Always split the longer axis : The regions generated with this approach
tend to be similar in size with somewhat square aspect ratios.
FIGURE 8.4 Hybrid splitting approach using weighted random selection and
early termination.
FIGURE 8.5 Example of skimming regions from the perimeter before later gen-
eration steps.
FIGURE 8.6 Final result of a building generated using top-down region removal.
78 ◾ Procedural Generation in Game Design
adjacent visited regions if possible, and then removed the regions that
weren’ t visited (Figure 8.7).
The process of removing regions in this step can occasionally cause
regions to float and become disjointed. These disjointed regions will be
detected and removed when we process the region connections in Step 4.
Step 4: Place Connections
This step is responsible for connecting the regions we created in Step 2. To
enable this process, we tracked and maintained all the possible connecting
edges that regions shared after a split. This produced a graph where each
region was a node that could be connected to zero or more other nodes
(Figure 8.8). Each connection also carried information about its bound-
ing region to make block and door generation easier later on (Figure 8.9).
This graph provided a straightforward way to ensure that players
would be able to visit every region we generated without needing to break
through walls. To place the connections, we did a random traversal over
FIGURE 8.7 Final result of a generated mine shaft using traversal-based region
removal.
FIGURE 8.8 Visualization of the region nodes and their connecting edges.
Level Design III ◾ 79
FIGURE 8.9 Graph formed using the region nodes and their connecting edges.
FIGURE 8.10 Region graph formed after random traversal. The traversal in this
example was biased to favor horizontal movement.
the region graph, and assigned a weighted random connection type over
each edge that was traversed (Figure 8.10).
This traversal can be configured to achieve different results. For
instance, by changing the probability of choosing vertical versus horizon-
tal connections, we were able to control the predominant axis a player
would be traveling on to get through the structure.
After the traversal is complete, it will be possible to detect any
disconnected regions that may have been produced by the region removal
in Step 3. Any region that was not visited by the connection traversal will
not be connected, and can be safely removed during this step if desired.
The connection types that are assigned will guide the generation pro-
cess in Step 7. Some of the types we used in Windforge include
• Regular door
• Small opening
• Empty connection
• Trap door
80 ◾ Procedural Generation in Game Design
• Boss door
• Treasure door
• Treasure room
• Boss room
• Entrance room
• Hub region
• Trap region
• Place the boss room near the treasure room, so that you must travel
through it to get to the treasure.
Entrance
Storage
room Treasure
room
Boss Boss
treasure room
room Trap
room
Generating the region contents is the most involved part of this pro-
cess. This part is responsible for the background pattern generation, object
placement, and platform placement. We managed the complexity of gener-
ating all this by further dividing the region into subregions (Figure 8.12).
This subdivision approach is similar to the region splitting covered in
Step 2. This time around, the subdivision was more flexible and open-
ended. We had a number of subregion types. Some of these types would
divide themselves into other types, which could also be divided. We also
had types that produced custom procedural patterns or structures, such as
background decorations and stairs.
In addition to pattern generation, we used these subregions to guide
platform and object placement. This worked well to ensure that the plat-
forms and objects matched their background decorations, and it helped to
82 ◾ Procedural Generation in Game Design
FIGURE 8.12 Final result of a region divided into subregions (left) and the same
region with outlined subregions (right).
make the placement patterns more regular. Finally, as long as the selected
objects were small enough to fit the dimensions of a subregion, we were
able to guarantee that our objects would not be overlapping each other.
DISCUSSION
The techniques presented here were designed to seamlessly generate archi-
tecture in a larger procedural world. Many aspects of the game design
guided the development priority of these techniques.
For example, Windforge is a very open-ended game where the player
has the ability to easily create and destroy structures, as well as a variety
of ways to traverse difficult terrain (e.g., by using grappling hooks and
flyable airships). With this in mind, we put less emphasis on puzzle gen-
eration and platform placement than would likely be required in other
games. Instead, our priority was to provide interesting places to explore
with enough variety for a large open world.
The design of this approach made it relatively easy to extend and add
new generation techniques as needed to create landmarks that feel unique
and distinct from each other. We were also able to generate a variety of
structure types just by changing the approaches used for certain steps.
For example, changing how regions were removed in Step 3 allowed us
to generate results suitable for dungeons, mines, small towns, and more.
Most of the architecture was generated on the fly each time a new
area was visited. However, there were a few areas where it was more cost-
effective to manually change the result. We did this with the major towns
of the world and a few areas that required complicated quest-specific
setup. These areas were created by using the usual generation techniques,
and modifying them as needed.
Chapter 9
Cyclic Generation
Dr. Joris Dormans
Ludomotion
* https://www.rockpapershotgun.com/2015/07/28/how-do-roguelikes-generate-levels/
83
84 ◾ Procedural Generation in Game Design
CYCLES
The idea of using cycles for level generation arose during a research work-
shop on computational modeling in games,* and was inspired by previous
research in architecture, urban planning, and hypertext structure. In the
real world, branching trees are rare. In most cities, buildings, and parks,
you can go around in circles. Cycles are also very dominant in handcrafted
levels. Simply google dungeon maps for tabletop role-playing games and
look for cycles in the most interesting ones. In fact, this is one way I har-
vested many of the patterns discussed below.
In Unexplored , cycles are created by connecting a starting point and a
goal by two paths instead of one. Figure 9.2 illustrates how nesting these
cycles often is much more effective in creating dungeon levels than simple
branching.
There are many different ways of using a cycle. Both paths from the
start to goal can offer different challenges to the player. Or maybe if one
path is much shorter, it can be much more dangerous, or simply much
harder to find. One path may actually only be traversable in one direction,
creating a quick route back to the starting point (e.g., after the player has
found a key). So far, I have identified a fair number of these types of pat-
terns, which are discussed in more detail in the “ Patterns” section.
* http://www.birs.ca/events/2016/5-day-workshops/16w5160
Cyclic Generation ◾ 85
11
2
10 1
6 3
9
12
4
8
7
(1) You enter the level at a platform in the center of a huge chasm. (2) The door on the north is barred. The
only open route is south. (3) Across the lava, you can spot the platform at 6, but you can not really reach it.
(4) You can continue on or check out platform 6, which you might have seen earlier. (5) As you cross the
bridge, it collapses. (6) If you make it to the platform, you are trapped there facing a giant rat. The chest
contains a scroll of teleportation, which allows you to escape. (7) This door is also barred. (8) The narrow
pathway is guarded by a patroling kobold spearman. (9) This section is protected by a sleeping goblin
spearman. You can sneak past easily. But did you spot those triggers that set off an alarm? (10) Similar
section. A trigger might wake up the goblin bowman. (11) Giant ants protect this area, but it also has two
levers operating the doors at 2 and 7. (12) After visiting 11, you can now make your way to this platform
and take the staircase down to the next level.
Key
Lock
Paths are the base structure of most level generators. Goal
The create treelike levels, often which only one solution.
Key
Lock
Start Goal
Start
Danger
Secret
Goal
In unexplored, cycles are used to create better flow
and to present players with alternative solutions.
steps. In fact, I assume that all successful level generators do so. However,
the advantages of multiple steps get hugely enhanced by using different
types of models during the process. Unexplored initially uses graphs to
represent level structure, as graphs are much better to retain structural
information over distances. For example, Figure 9.3 shows one such
graph showing connected rooms, containing obstacles, locks, and
keys.*
At this stage, all nodes in the graph are deliberately generic. The exact
nature and properties of most obstacles, locks, keys, and rooms are defined
during later stages.
Unexplored manipulates graphs using transformational graph gram-
mars. These grammars consist of rules that loom for particular pat-
terns in a graph and suggest ways how these graphs can be transformed
Bores Bores
Bores
Obx Obx
Obx
Lock
Lock Start
Goal
Key
Key Obx Bores Obx
Obx Bores
Obx
Obx
PATTERNS
Graph transformation rules allow Unexplored to implement a number
of design patterns. These patterns are common structures found across
games. For example, adding a secret shortcut to a long and dangerous level
is one such pattern. Each pattern has its own positive and negative effects;
88 ◾ Procedural Generation in Game Design
2: goal
1: lock
0: goal 1
1: key
0 1
0: ∗ 1 0: ∗ 2 1
Start Goal
Lock
Key
in this case, the shortcut might be rewarding for players that take the time
to explore thoroughly, but it can also bypass a large portion of an other-
wise interesting level. However, the important point is that through trans-
formational graph rules, the level generator is able to manipulate these
patterns directly: it can make deliberate decisions about their use in order
to maximize their positive effects and minimize their potential negative
effects.
For example, most of the time, Unexplored starts a level by adding a
starting point, a goal, and two paths. The first path, called a , initially
leads from the start to the goal, while the second path, b , leads from the
goal back to the start. Based on the relative and absolute lengths of a and
b , a number of cycle patterns can be applied. For example, when a is short
and b is long, it can place a locked door at the goal, and place the key at
the end of b just before a spot where the player can cut back to the main
path. This creates a level where players first encounter the locked door,
and when they do find the right key, they do not have to go far to reach
the door it unlocks. Obviously, this requires that the player cannot reach
b from the cycle’ s entrance straightaway, although it might be interest-
ing if they can already see b and the key. Figure 9.8 lists a couple more of
these patterns.
IMPLEMENTATION
Of course, the devil is in details or, in this case, the implementation. Graph
transformation and model-driven engineering are powerful methods, but
to make them work in the way we wanted, we still had to add a couple of
things. The most important addition to the graph transformation rules
are attributes attached to nodes and edges in the graph. For example, a
room node can have an attribute that specifies the room type or theme.
The graph transformation rules in Unexplored can read and write to those
attributes. In this way, the generator can activate a different transforma-
tion rule for rooms that are marked as a “ shrine,” “ armory,” “ workshop,”
and so on.
Attributes turned out to be really important in generating lock-and-
key mechanisms. For Unexplored , simply adding keys and locked doors
was not going to work. There are several game elements that allow players
to push ahead early and often involuntarily: they can jump in chasms to
the level below, use a scroll of descend to similar effects, or use a scroll of
teleportation to teleport to a random location in the level. As the objective
90 ◾ Procedural Generation in Game Design
a Monsters
b Traps
Start Start
Secret
S
b
Goal Goal
Lock
a
Goal
Start Start
b Valve Key
a Patrolling monster
b
Short a, short b Patrolled cycle
Key a
Lock b Lock
Start Start
Lock a Valve Valve Valve
Key b Key
Double key cycle Key behind valve
Some
monsters
Start Start
Visible Many
Goal Goal
monsters!
Dramatic cycle Dangerous route
Lock
Start Start
Danger?
Visible? Visible!
Key Reward
Simple lock and key Gambit
of the game is to get to level 20, retrieve the Amulet of Yendor, and make
your way back up, this means that many of the lock-and-key puzzles need
to be solvable in two directions.
A simple solution would have been to make all locked doors operated
by levers and simply make sure there is a lever on both sides of the door.
However, lock-and-key mechanisms can get boring very quickly, espe-
cially when there is little variation to their design. One design objective of
Unexplored is to use as many game mechanisms as possible as lock-and-
key mechanisms. For example, a potion of resist fire can serve as a key to
a barrier of lava the player needs to cross. Unfortunately, the potion has a
temporary effect, and you are never quite sure when the player will drink
it, and it definitely will no longer work when the player is returning to the
surface.
Using attributes to mark the structural function of different locks and
keys proved to be a very useful way to avoid deadlocks and create variety
in lock and keys at the same time. For example, locks can be marked as
“ conditional,” indicating a lock for which the player must have a key to
pass. The most typical conditional lock is an indestructible door that can
be opened only with a particular key. An example of a nonconditional
lock would be a room with turrets controlled by a lever. If the player has
not found the lever, he or she can still risk running through the room.
Nonconditional locks have the advantage of being traversable in two
directions automatically, and it is often easier to involve different game
mechanics in their design.
mapping that reveals secret doors or a potion that protects you against fire
damage can act as keys for those doors, making it easier to cross the lock
in both cases.
TILEMAPS
Another problem we ran into during the implementation of these techniques
in Unexplored , but also in other games using similar ideas, is how to transform
94 ◾ Procedural Generation in Game Design
graphs into tilemaps. The problem is a generic one: during the initial stages of
the generation process, graphs are used to represent the abstract structure of
the level. Graphs are good for this, as they can include edges to represent the
structural relationships between nodes. These relationships include adjacen-
cies, but also which key unlocks what lock, what enemy patrols which rooms,
and so on. However, at one point the generator needs to build a topological
representation detailing the exact locations of wall, doors, keys, and enemies.
In Unexplored , levels are represented as tilemaps.
Unfortunately, there is no standard solution to this problem. For
Unexplored , we solved the issue by first creating a graph that is laid out
as a grid and stored the topological information in the nodes’ attributes
(Figure 9.9). All graph transformations are then performed on this graph.
This way, when the generator needs to make the transition from graph
to tilemap, there are no issues in mapping the graph onto a two-dimen-
sional tilemap. Initially, individual tiles correspond with nodes and edges
directly, but the resolution of the tilemap is then increased to allow for
Enemy Key
Key Enemy
nem
Enemy Enemy
Enemy
Enemy Start
FIGURE 9.9 Graph grid layout that any dungeon level starts from.
Cyclic Generation ◾ 95
DISCUSSION
This chapter does not include every detail of implementation. For exam-
ple, before even one dungeon level is generated, a plan for the dungeon is
generated that specifies what themes, monsters, locks, and keys to use on
each level. However, the general idea behind cyclic dungeon generation
should be clear. The implementation in Unexplored relies heavily on the
use of transformational grammars operating on graphs and tilemaps, but
it is not hard to imagine that other generation techniques could also be
used to generate dungeons based on cycles instead of branching paths.
For Unexplored , the advantages of cyclic dungeon generation are many.
We have found that levels based on a couple of cycles are the most effec-
tive. Two to five cycles give each level a distinct and recognizable shape
and character. This presents the player with a nice, but manageable navi-
gational challenge. With just a handful of cyclic patterns, the number of
possible combinations is still huge. Adding more cycles just seems to clut-
ter the level.
The reason cyclic dungeon generation works well is that as a structure,
cycles are able to express so many more interesting patterns than paths
do. There is no reason to assume that this advantage is unique to cycles
alone. Structures like T-joins or parallel, symmetrical branches might be
able to achieve similar results in addition to, or independent of, cycles, but
so far cycles are the most powerful and expressive structure we have come
across.
In addition, cyclic generation is not restricted to the generation of
sprawling dungeons alone. In fact, the research workshop from which the
ideas behind cyclic dungeon generation emerged tried to come up with a
good way to generate parks or meditative gardens. In such environments,
cycles are also very useful: most people prefer a walk or hike that does
not involve any backtracking. Similar ideas can be applied to open game
spaces and world maps. Cycles can be drawn around obstacles such as for-
ests, lakes, swamps, and mountains, with dangerous shortcuts connecting
two sides of the cycle and prominent sites on locations where two cycles
intersect. There are many opportunities that cyclic map generation offers
that remain unexplored— for now.
Chapter 10
Worlds
Dr. Mark R. Johnson
Independent
Alternatively, for games that don’ t need entire planets and certainly
don’ t need entire solar systems, galaxies, or branes, world generation can
readily be separated into components that function perfectly well in their
own right— one might choose to generate a nation, or a smaller-than-a-
world area of terrain, or cities, towns, fortresses, districts, individual
buildings, the floors within those buildings, and so forth. Although these
smaller examples are arguably not quite the creation of worlds (unless
the building were some truly towering megastructure of the sort found
in Halo or Dark Souls ), all these are still concerned with the creation of
unique spaces for the player to experience, and it is the grander ends of
this spectrum of practice we’ ll look at here.
This chapter closely examines three elements of procedural world gen-
eration. First, it offers a brief history of world generation with a range of
examples, and we’ ll seek to identify a timeline of sorts and some of the
commonalities of world generation up to the present day. Second, it delves
deeper into the design rationales behind the development of world gen-
eration and the desired gameplay such algorithmic realities are intended
to foster. Lastly, in looking to the future, the chapter explores in depth
my fairly unusual work in this area, in which I have been broadly uncon-
cerned by the creation of physical and spatial “ world” characteristics of
the sort outlined above, but instead with the development of what I have
termed “ qualitative procedural generation” and its implementation and
deployment in a world-building context. By this, I mean the procedural
creation of cultural practices, social norms, religious beliefs, ways of
speaking and behaving, and the like, and their physical instantiations and
reproductions within a game world, intended here as a contrast to previ-
ous world generation focuses upon the genesis, variation, and delineation
of procedural in-game spaces and places. In doing so, the chapter gives
an outline of the past, present, and future of procedural world generation;
brings our attention to some of the core philosophies behind these prac-
tices; and examines what exactly it is that makes exploring a procedural
world such a distinctive pleasure.
biospheres and tectonic plates tend to move a tad slower than social and
political life) but sometimes including shorter-term physical processes,
and on a range of scales from the grand and abstracted worlds of geo-
politics and economies to the microsocial elements of individuals and
conversations, or animal tracking and plant gathering. Players are then
actively invited to engage themselves in these systems and experiment
with the extent to which they can be adjusted, interfered with, turned to
one’ s advantage, and made the center of intriguing emergent phenomena
whereby the player alters one system and sees a knock-on effect in another.
These two rationales therefore produce very different worlds, require very
different forms of procedural generation, and result in games with very
different design objectives.
Exploration
In a nonprocedural game, exploration as game mechanics can only ever be
truly and fully present on the first-ever playthrough of a game when the
player has no prior knowledge of the single fixed game world. Although
games do mitigate this in various ways, such as the difficulty of progres-
sion and the narrative obtuseness of the Souls series, it is only in proce-
dural worlds where exploration can be consistently fresh game mechanics.
This takes many forms. In strategy games, exploration is essential for the
player who needs to discover the location and disposition of enemy posi-
tions and forces, the distribution of land and ocean and therefore what
units and technologies should be pursued, the location of particularly
valuable resources, and so forth.
In games like Minecraft , and even more so in “ pure exploration” games
like Proteus , exploration for its own purpose is a central game mechanic
and a focus of the play experience, centered around the discovery of
102 ◾ Procedural Generation in Game Design
Gameplay Variation
Procedural worlds push increased gameplay variation on the player. This
point is somewhat related to the first in this list, but is distinct— generating
a new world each time a game is played does add replay value, but it also
has the intriguing side effect of forcing gameplay variation and encourag-
ing players toward new forms of play.
If a game of the sort procedural world generation is often used in (strategy,
exploration, roguelike, etc.) was only ever played on a single map, it would
quickly become comparatively simple to divine the strongest strategies and
omit any aspect of the game’ s design that didn’ t fit into that strategy.
By contrast, using procedural world generation forces players to some-
times experiment with parts of a game’ s design they might ordinarily
not use. A player might be planning to execute a particular strategy in
Civilization , for example, but then finds the generated world is covered
with oceans and therefore necessitates the construction of a strong navy
for any chance of victory, encouraging the player toward playing with naval
units and naval strategies he had perhaps never previously employed. A
world might be devoid of a particularly crucial resource in a playthrough
of Dwarf Fortress , which means certain structures or weapons can no lon-
ger be produced (or can no longer be produced in any kind of quantity),
encouraging the players to think outside their traditional in-game rou-
tines and patterns to find new ways to achieve their goals.
Generating in-game worlds of sufficiently high variety is therefore a
way to gently nudge players toward exploring the full scope of a game’ s
possibility space, instead of falling back on well-tried and well-tested tac-
tics and strategies every time the game is played. The combination of these
three elements— the use of exploration as a central game mechanic, the
size and complexity of procedural worlds, and the ability for procedural
worlds to encourage players out of their comfort zones and into the cre-
ation of new choices and decisions— makes playing in procedural worlds
a very distinctive experience, and one that cannot ordinarily be offered
(more than once, anyway) by their handmade cousins.
nations into numerical values of the sort that the Civilization series does,
perhaps allow the player to walk between cities of two nations. The player
would see how the artifacts of one culture bleed into the other (and vice
versa), or how much linguistic and cultural exchange there is between the
two, how well-patrolled the border is, and how people from each land talk
about those from the other. This is a classic “ show, don’ t tell” approach,
and one that can only really take place at a particular scale— when deal-
ing with a world-level strategy game, of course individual cities cannot be
explored and depicted, as that would take away from the main focus of
the game.
When controlling a single-player character walking through a gener-
ated world, however, the possibilities open up for portraying a complex
sociological and cultural system in everything the player sees and discov-
ers, rather than just offering a little textual description or numerical value
to this effect instead.
Key to this system is the intersection between all the different elements
the game generates. A particular religious belief about the nature of the
afterlife may affect the colors on book covers; a particularly powerful
house might influence the design of all the weapons and armor manufac-
tured in a nation; the flora and fauna of a particular region might influ-
ence the designs of the sigils of important families; a past war, ancient but
not forgotten, may influence how people from one culture respond to the
player who happens to be from that long-resented foe; the geographical
location of a city might affect the religious beliefs that spring up there,
connected perhaps to the seas or the mountains nearby; and so forth.
Systemic procedural worlds hinge in part upon the interactions between
large numbers of complex systems that have to be uncovered by the player,
but these systems need not be entirely quantitative and reflect only the
flow of trade or battle or some abstracted notion of culture— instead, these
systems can be qualitative in nature and reflect the beliefs and practices of
procedurally generated peoples, and lose none of that desired complexity
in the process. Indeed, if anything, quite the opposite is the case— so many
players of procedural games find their complexity to be one of the most
important selling points (the popularity of Dwarf Fortress and Aurora 4X
is a testament to this), and these layers of sociocultural detail only add to
the granularity and detail of the player’ s world-exploring experience.
At this point, one might ask, what is the value of such systems?
Generating spaces offers an area for play, and many games with complex
generated systemic worlds already have a massive wealth of interactions
106 ◾ Procedural Generation in Game Design
for the player to engage in. What value does this kind of qualitative pro-
cedural generation bring to the procedural generation of entire worlds?
As above, part of the enjoyment of exploring procedural worlds lies in
uncovering their complexity, and yet the forms this complexity has taken
to date are only the smallest fraction of forms that real-world complexity
adopts. Incredible detail and nuance can be added to procedural worlds
through these sorts of techniques, especially when the overwhelming
majority of procedurally generated worlds, regardless of their size, are
beset by remarkably large numbers of AI actors speaking the same lan-
guage, building similar buildings, or having few differences beyond the
flags they wave and the procedural histories they share.
The second answer lies in the use of these systems for gameplay— it is
obvious how a complex trade system can be used for gameplay, but what
about a complex cultural system? A complex cultural system allows for
the player to explore the world through means other than walking around
it. It allows for a game to be based around the discovery of in-game cul-
tures and to develop “ cultural knowledge” as a crucial skill for a player to
be successful; it allows for the player to attempt to fake their cultural or
religious origin as a form of covert or espionage gameplay; it allows for the
player to make informed judgments about their travels in the world, based
on their knowledge of allied and feuding countries. Similarly, it allows
the player to make judgments about what options should be selected in
what conversations, based on their acquired knowledge (acquired through
investigation and learning, not through direct exposition) of the disposi-
tions of the world’ s various peoples.
Qualitative procedural generation is a major future step in the genera-
tion of procedural worlds, both for the sake of the complexity and for the
sake of innovative gameplay.
Chapter 11
Puzzles
Danny Day
QCF Design
107
108 ◾ Procedural Generation in Game Design
Puzzle-Spaces
Algorithms are great at churning out puzzles that are variations on a
theme, puzzles that come from a large and reasonably uniform puzzle-
space. If a puzzle-space is the abstract space populated by every single
puzzle that could emerge out of a set of gameplay rules, then a puzzle-
space can be
• Large if it contains many puzzles with distinct start and goal states
• Small if the number of distinct start and goal states is few
• Shallow if each distinct start state has exactly one corresponding
goal state
• Deep if a single start state has multiple viable goal states, or vice versa
Desired Outputs
Often, the primary role of a procedural puzzle generator is trimming
down a larger puzzle-space into a subset of possible puzzles that differ
along axes that can be easily randomized. A functioning game usually
requires several different types of puzzle to give players a complete experi-
ence. It’ s common to find that you’ ll either have multiple generators that
operate on different “ areas” within the puzzle-space, or parameters that
move their sampling around within the puzzle-space itself.
One of the most important things a generator needs to do is ensure that
it produces puzzles that are actually solvable! It does nobody any good to
produce a sea of starting states with no guarantee of at least one corre-
sponding goal state for players to reach. Without a goal, you’ re not gener-
ating puzzles and you’ re certainly not respecting the player’ s time. Thus,
our first generation requirement is solvability .
Puzzles ◾ 109
Heuristics
All the above-mentioned generation paradigms stand to benefit from
specific game-relevant rules: heuristics. We can certainly generate viable
Puzzles ◾ 111
• You could detect a pattern of where players click first when playing
and make sure those squares are guaranteed clear of mines for the
next X puzzles.
• You could offer to suggest the player’ s first move as a guaranteed
safe move, or even perform the least information-revealing move for
them at game start.
• You could simply replace any mines discovered when you detect the
game state to be discontinuous, repositioning the mine in a way that
won’ t invalidate any of the revealed game information.
In Sudoku puzzle generation, solvers are often used to calculate the dif-
ficulty of the resulting puzzles based on heuristics that provide a difficulty
rating for specific solving techniques. It’ s worth noting that this heuristic
is a postgeneration calculation; if you want a specific difficulty Sudoku
puzzle, you’ d keep generating puzzles until one was produced (presum-
ably keeping the discarded puzzles in buffers for their relevant difficulties
to prevent needless duplication later).
a great thing for puzzle gameplay, but it’ s great for the tension and desper-
ation that drives players to tell stories of their exploits in roguelikes. The
design goal of Desktop Dungeons was to condense those moments down
into short, but intense sessions. It achieves this by riding that desperation
line really hard— it constantly feels like you’ re not going to succeed in any
given run. Until suddenly you do, and it feels great!
Desktop Dungeons is, like most roguelikes, a resource management
sim at its core. The resource model in the game is all about trading off
differently earned currencies against each other to keep ratcheting up
the power level of your character (which is basically shorthand for the
amount of resources you can bring to bear at any one moment). Playing
the game is an exercise in spending health and mana to earn experience,
which increases your health and mana pool. Except you’ re also spending
black space (unexplored regions of the level) to regain health and mana.
But then you need to hunt for enemies in the black space; maybe there’ s
a better target just around the corner? And that’ s completely ignoring
other complexities, like gold, items, the gods, piety, conversion points, and
inventory space.
Everything trades off against everything else, often in ways that aren’ t
atomic actions (and have multiple side effects)— you have to feel the
resource economy on an intuitive level rather than strictly plan your
gameplay responses. It’ s that sort of responsive play that makes Desktop
Dungeons a roguelike.
We attempt to train players to keep trying, even if they feel they might
have already lost— in practical terms, the puzzle-space is generally so
deep that there’ s a large buffer for nonoptimal actions in large numbers
of potential solution paths for any given generated dungeon. But this care-
fully herded optimism is completely shut down if the player gets stuck in
a dungeon that’ s actually unsolvable. When a player dies in a run, they
need to feel that they could have done better, not that their attempt was
pointless from the start.
Guaranteeing Solvability
During Desktop Dungeons ’ long alpha, it became clearly important that
any run is solvable. But, given how the game was generating levels, we
couldn’ t guarantee solvability in any of the usual ways:
pickups and interactive items in empty spaces. Finally, we’ d add the player
starting point and clear walls in a 3 × 3 space around that. Then it was go
time. Good luck!
That worked surprisingly well, but it could (and did) generate com-
pletely impossible dungeon layouts by “ blocking the player in” with ene-
mies that were too high level to kill. In the resource parlance of the game,
player progression was blocked by experience having health and mana
costs too high for a low-level player to pay. It didn’ t happen as often as
players assumed it did, but the sheer fact that impossible layouts could
happen lent credence to players’ feelings of unfairness when faced with a
difficult but possible dungeon.
Generating Hope
In the end, we didn’ t change away from random start-state generation.
Adding layers of heuristics to the generation systems produced encourag-
ing results. We also added more terrain generation methods that produced
different overall dungeon layouts for variety.
The first heuristic attempted to keep the available resource costs near
player starting positions within acceptable bounds by introducing a mini-
mum distance threshold to enemy spawns. Higher-level enemies that
spawned too close to the player start location kept rerolling their positions
until they were far enough away. Note that we didn’ t also apply maximum
distances, so lower-level enemies could still spawn far from the player’ s
starting position. Our focus wasn’ t on making sure “ easy” enemies didn’ t
cost a lot of exploration; rather, we wanted to make sure players were free
to spend exploration if they needed to. This had the predictable effect of
slightly depopulating the area near the player starting location overall, but
this meant that helpful pickups were more likely to spawn in easy-to-reach
locations, so we didn’ t try to correct that.
Minimum spawn distances for enemies definitely helped address the
issue of experience blocking, but we found that player win rates actually
went down during the Desktop Dungeons beta after the change. It turned
out that the sparse enemy numbers around player starting locations
meant that players were running right past low-level enemies in search
of more pickups, wastefully spending exploration that could have replen-
ished their health and mana after fights. The optimism for exploration
was something we wanted to encourage, but we needed players to at least
have a couple of lower-level fights to encourage good usage of exploration
regeneration.
116 ◾ Procedural Generation in Game Design
truly impossible dailies. That’ s a success rate I’ m more than happy with!
Players seem more hopeful about the game as well; reviews of the full
game don’ t mention unfair dungeons when that was a regular feature in
writing about the alpha.
CONCLUSION
Procedurally generating puzzles can both produce endless possibilities for
your players and create novel arrangements that inspire hand-designed
puzzles. Generating puzzles successfully requires a pronounced under-
standing of the puzzle-space you’ re exploring.
Defining your generation needs via a deep or shallow puzzle-space, how
many viable solution paths you require, whether solvability needs to be
guaranteed, and whether your puzzles are continuous is extremely helpful
at a conceptual level. The final generation approach you take depends very
much on the interaction between player actions and the information your
game presents.
It’ s usually best to start with a naï ve approach: learning what makes
a bad puzzle is just as important as producing good ones while you’ re
starting to explore a new puzzle-space. You can always layer on heuristic
complexity later as you understand your game’ s requirements and player
limitations better.
A system that covers more of your puzzle-space is always preferable to
one that is incredibly specific: it’ s easier to prune out undesirable puzzles
than it is to coax an overly specific algorithm to produce variety.
Chapter 12
Procedural Logic
Ben Kane
Independent
BACKGROUND
First, a few words about Keep Talking and Nobody Explodes , because it’ s
a weird game with some weird restrictions. It’ s a cooperative game about
defusing a bomb, but the twist is that only one player, known as the Defuser,
is actually playing a video game. The Defuser sees a randomly generated
bomb, with wires, buttons, symbols, lights, labels, and even a serial num-
ber. To defuse it, he or she must solve a series of puzzles and cut the correct
wire, enter the right sequence, push the button at the right time, and so on.
119
120 ◾ Procedural Generation in Game Design
The Defuser, however, has no idea what the correct solution is. For that, he
or she needs the help of other players, called the Experts.
The Experts have access to the manual, which is a document featur-
ing instructions on how to solve all possible cases for these puzzles. The
manual is a static document, available for free at www.bombmanual.com.
It’ s up to the Experts to obtain a copy of this manual, by either printing it
out or viewing it on something like a computer, phone, or tablet.
The gameplay hinges on player communication, with the Defuser relay-
ing information about what he or she sees, while the Experts sift through
the manual and figure out the solution based on the details that have been
described to them. Once they find the answer, they relay it to the Defuser,
who cuts the wire and saves the day— or explodes.
The communication is where the fun lives, and all of our design deci-
sions are made in favor of fostering interesting communication. Players
should be placed into situations where they need to talk with each other,
trip on their words, get confused, and make mistakes. We use this singu-
lar focus to evaluate design throughout the rest of this chapter.
The main motivation to generate the rules, however, was to ensure our
manual and the game itself would stay in sync. We discovered early on
that creating a manual, well, manually is an extremely error-prone pro-
cess, and the results are difficult to verify. Since a large part of our game
involves players attempting to learn the rules, misinterpreting those rules,
and making mistakes, we had to be absolutely sure that the manual was
correct and accurately reflected the logic of the game’ s code. This was
vital during development when the game was both undergoing frequent
changes and being exhibited at conferences in order to get player feedback.
To enforce the desired synchronization, we took a data-driven approach.
The rules could be expressed and stored as data, which could then be used
to generate a manual from templates and would be executed by the game’ s
logic. The key here is that both the manual and the game would be work-
ing from the same data, and thus we could have some assurances that the
two would be in sync (Figure 12.1).
Trivial Case
In the Morse code puzzle, the Defuser must observe a blinking light and
describe the dots and dashes to the Experts. The Experts then use actual
Morse code to determine which letters the dots and dashes correspond
to. They then look up the word spelled out in a table and finally relay the
associated frequency back to the Defuser. It’ s a tricky puzzle for players to
FIGURE 12.1 Diagram of how generated data is used by both the manual and
the game.
Procedural Logic ◾ 123
(...) (...)
execute, but generating the rules is straightforward. The rules are simply
the mapping of code words to frequencies (Figure 12.2).
To generate these rules, we just need to construct this mapping. We
first author a list of possible four- or five-letter words to be used. Then we
randomly associate each word with one of the response frequencies. And
that’ s all there is to it!
It’ s worth noting that we could have overdesigned the solution here and
tried to take into account how similar the Morse code representations of
words would be in order to cause more difficulty. In practice, we found
that players had ample difficulty communicating already, and our design
goals would not be better served by increasing complexity.
Countable Problems
Puzzles have properties, such as color of wires, that vary from bomb to
bomb, which keeps the game replayable. For some puzzles, the possible
varieties are limited, and thus are easily enumerated. The Complicated
Wires puzzle is one such case, but the rules are presented as a set-set
Venn diagram, and the challenge is interpreting the diagram quickly
(Figure 12.3). The four-set Venn diagram means there are four differ-
ent properties that must be examined in order to determine whether to
cut a given wire. This is a small set of possibilities: each property can
be either true or false, so there are 24 = 16 states. Creating the rules is
a matter of randomly assigning a “ cut” or “ don’ t cut” solution to each
of the states.
Of course, that would make for a fairly trivial puzzle. Our design goal is
to foster interesting communication between the Expert and the Defuser,
so instead we add a bit more depth by making the solution require some
additional information. For instance, a solution could be “ cut if the bomb
has more than two batteries on it.” Despite being a fixed instruction (i.e.,
something that can be printed in a manual), it will result in dynamic
124 ◾ Procedural Generation in Game Design
S S
S
C P
C P S D
D
D B
P B
B
• If there is more than one red wire and the last digit of the serial number is odd,
cut the last red wire.
• Otherwise, if the last wire is yellow and there are no red wires, cut the first wire.
• Otherwise, if there is exactly one blue wire, cut the first wire.
• Otherwise, if there is more than one yellow wire, cut the last wire.
• Otherwise, cut the second wire.
Generating Rules
To generate sets of rules for a puzzle, we author various types of queries
and solutions, and then combine them procedurally. The result is a sur-
prisingly expressive system that can create rules, such as those shown in
Figure 12.5.
Generating rules is more involved than simply randomly drawing from
a pool of possibilities, however. Since the rules make up the logic of the
game, and inherently impact how players will need to communicate, we
needed to keep our design goals in mind when creating our generation
algorithms. Let’ s take a closer look at how a rule is made.
If there is more than one red wire and the serial number is odd, cut the last red wire
Rule
Query
true or false for a given puzzle during gameplay. The query has a textual
representation that can be used within the generated manual and is also
tied to logic in the game that evaluates the question.
Figure 12.6 is a simplified example of a query template that asks a ques-
tion about how many batteries are on the bomb itself.
Note that this template can be used with different values for “ battery-
Count,” so we can easily generate several queries from this single template.
The manual will be populated with the text in the query, substituting in
the appropriate values within a range we define. The game will execute the
function called “ MoreThanXBatteries,” using the chosen “ batteryCount”
(say, 1, 2, or 5) to evaluate the answer. And because both the manual and
the game will use the same generated data, we can achieve our goal of
keeping the two in sync.
Solution
Better Queries
Queries are the building blocks of the game’ s logic, and they represent
questions that players will need to ask one another during gameplay. Since
fostering interesting communication is the primary design goal, creating
interesting queries is a vital part of the design process. The next sections
are a few additions we made to the query generation process.
Compound Queries
Rules can have several queries associated with them, creating more spe-
cific questions that are less likely to all be true. Complex queries take
longer for players to resolve and are more likely to cause confusion and
mistakes during communication, both of which are desired outcomes for
us as designers. A compound query can look like this:
If there are more than two red wires and the bomb has a parallel
port …
Query Contexts
Some queries reference the bomb itself, asking questions about its serial
number or how many batteries are attached to it. These have gameplay
ramifications, as the Defuser must search around the bomb to determine
the answer. However, the answer applies to the bomb itself, and thus any
other rules that make a similar query are going to be less effective, as the
128 ◾ Procedural Generation in Game Design
Defuser will be able to recall the answer rather than searching for it. For
this reason, we make sure that our queries are never based solely on prop-
erties of the bomb itself, but rather involve at least one query that is specific
to a given puzzle module. Otherwise, the solutions to multiple puzzles on
a bomb could degenerate into a single bomb-level query, which is neither
difficult nor satisfying for players.
In practice, this entails adding some information when authoring a
query so that we can classify it as being “ puzzle specific” or “ bomb spe-
cific.” The rule generator in turn can take this information into con-
sideration and generate rules that better support our desired gameplay.
Like many improvements, this is not without cost. A more complex rules
generator takes longer to implement and maintain, so any such addition
should be weighed carefully.
Better Solutions
For players, figuring out which solution applies to a puzzle is the chal-
lenging part of the game. Executing the solution is meant to be straight-
forward. After all, this is a game about teamwork and communication, so
that’ s where the challenge should lie. For this reason, a solution directs a
player to take a single action, like cutting a wire. However, in a puzzle with
six wires, that amounts to just six solutions. We needed a way to introduce
more variety.
Our compromise was to introduce a bit of logic into the solutions
themselves. As long as a solution unequivocally corresponds to one and
only one action, it will work within our rule framework. That means that
instead of just saying “ cut the last wire,” we can do things like “ cut the last
red wire.” It’ s a subtle difference, but in practice, it successfully results in
more communication and opportunities for errors.
In order to do this, however, we need to make sure that there is a red
wire to cut. This is where the query comes back into play. Recall that a
query is essentially predicate logic, and so when authoring a query, we
can recognize that the query being “ true” gives us information about the
puzzle itself. For instance, consider this query:
If this query is true, then we can be assured that there is a red wire to
cut. The rule generator is informed of extra bits of information like this
from the query and uses it to expand the pool of possible solutions. This
Procedural Logic ◾ 129
added complexity to rule generation is worth the extra variety that it pro-
vides, not to mention it makes rules that feel more cohesive as the query
directly relates to the solution.
ignore the earlier portions of the list. Procedural generation alone won’ t
be enough to solve this design problem.
Instead, the puzzle design makes use of many such lists, and the scenario
where one or two are degenerate search cases is not a problem. Players are
quick to identify these and feel a degree of mastery in their knowledge. If
we were to try to “ fi x” this problem with a more involved procedural gen-
eration algorithm, we would actually be working against our own design
goals. It’ s important to keep in mind that more sophisticated procedural
generation is not the solution to every problem.
If there is more than one blue wire and there are no blue wires, cut
the blue wire.
This is not an acceptable rule. Logic purists may argue that it’ s simply
a rule that can never be satisfied, but in practice, most players will be con-
fused in a way that is undesirable. Rule validation is one approach that
could be taken to address this situation: generate a rule, check if it makes
sense, and keep generating rules until you get one that does. Inefficiency
aside, it’ s not a trivial task to verify whether a rule makes sense. Bombs,
and their puzzles, have randomly generated states with billions of possible
combinations, so exhaustive testing is intractable. We would require a bet-
ter understanding of what is valid and what isn’ t in order to prove whether
a rule is acceptable.
Instead, we recognize which combinations have the potential to be
invalid and remove them from the possible query or solution pools. The
general reasoning is that we wish to avoid compound queries that ask dif-
ferent questions about a single aspect. In the example above, there are two
queries that both relate to how many blue wires are present. To prevent the
situation from ever occurring, we simply remove all “ blue wire” queries
from the query pool as soon as we select one of them.
The keen reader may notice that this approach will also remove some
valid combinations. For instance, you can no longer generate valid com-
pound queries such as
If there is more than one blue wire and less than five blue wires …
Procedural Logic ◾ 131
CONCLUSION
Procedural generation can be a valuable tool during development for con-
tent creation, even if that variety isn’ t exposed to the end user. The content
you create is limited only by your ability to model the data, so even things
like logic can be generated if you have reason to do so.
We tried to keep our core design goal of fostering interesting commu-
nication in mind throughout our project. That pushed us to expand our
procedural generation logic in cases where it would support our design,
such as creating more sophisticated queries and solutions. Perhaps more
importantly, it kept us from getting carried away with overengineering the
generation algorithm to squeeze out every last valid combination when a
simpler culling approach worked just fine.
Procedural generation is fun, but shipping a game is more fun. Always
keep sight of your design goals and ensure that your procedural genera-
tion is in service of those goals.
Chapter 13
Artificial Intelligence
Dr. Mark R. Johnson
Independent
133
134 ◾ Procedural Generation in Game Design
roguelike game Dungeon Crawl Stone Soup , for example, many bosses and
high-end enemies are given a selection of “ spells,” from which (in some
versions of the game) they choose randomly each turn. This is designed
to provide unpredictable challenge, but also to balance the game’ s more
difficult enemies through giving them a selection of stronger and weaker
spells. This allows bosses to deploy deadly attacks without being game-
theory optimal and using their strongest attack on every turn, which
would result in enemies that were far more challenging (although also far
more predictable) and far less interesting.
Players can also assign spurious intention and agency to simple and
semiunpredictable AI patterns. In early roguelike games, monster AI was
rarely more complex than “ wander around, and then when the player is
sighted, pursue them by the most efficient path possible.” Players, however,
often thought that a far more complex monster AI was at work, and that
monsters would deliberately show up at the worst possible time for the
player. What was happening, of course, was that monsters that appeared
(whether through random movement or active pursuit) at moments where
the player character was safe, well rested, and at full health were rarely
remembered, since those resulted in trivial fights.
By contrast, if the player had just fought a brutal battle and was at
death’ s door, and then two other monsters come around the corner,
that becomes an event the player will remember for a long time and may
subconsciously blame on the monster’ s decision making, instead of the
unlucky vicissitudes of fate or the eventual outcome of a tremendously
simple follow-the-player AI routine.
The unpredictability and predictability of AI can therefore readily
become interwoven and confused even without the role of PCG. PCG’ s
inclusion in the design processes leads beyond these concerns of player-
side understanding of AI actions toward a range of designer-side questions,
focused on how AI should be programmed to respond well in procedur-
ally generated spaces and settings, and how the player will engage with
such AIs.
Once again, there is the question of the extent to which all combat
scenarios can be predicted, and therefore factored into the AI design pro-
cess. Movement and combat thus both pose comparable design questions
centered around the extent to which designers can predict all possible
PCG scenarios— or rather, the elements of all scenarios, which the AI then
identifies— and the extent to which the game’ s PCG and AI systems can
thereby become closely integrated. If this integration is low, unusual out-
comes will leave the AI unable to make a sensible choice about its actions,
resulting in the AI either freezing, defaulting to a simplistic option, or
selecting a bizarre option for the current scenario; however, if this inte-
gration is high, players will see procedurally placed AI characters behav-
ing well in procedurally generated spaces, irrespective of the nature of the
space and the condition of the character, and thereby behaving compara-
bly to convincing AI in an equivalent handmade game.
AMBIENT BEHAVIOR
Ambient behavior refers to AI that carries out certain actions even when
the player is not nearby or engaged with the AI actor. Perhaps the current
and most fascinating exemplar of ambient behavior is the science fiction
roguelike game Cogmind , in which the player is placed in a world contain-
ing large numbers of robotic “ species,” many of which ordinarily ignore
the player and go about their business without being concerned by the
player’ s actions, unless the player attacks them, interrupts their routines,
and so forth. This poses a challenge for designers because the AIs must be
able to “ go about their day” on any possible map, necessitating the devel-
opment of a system that can identify points of interest for each AI actor
when the map is generated, and build up a completely unique spatial and
temporal schedule for that actor each time a level is generated. Equally,
however, it affords opportunities for creating game spaces that feel deeply
alive and lived in, even if they had only actually been generated a split-
second prior, and therefore performing a kind of visual trick on the player
ordinarily only possible in handmade games with AI actors who have been
given meticulously thought-through handmade schedules for their days.
EMERGENT PHENOMENA
Emergent phenomena refers to situations where sets of simple behaviors
lead to often unanticipated sets of more complex behaviors. The clas-
sic roguelike NetHack perhaps contains the most illustrative examples
of emergent phenomena. NetHack contains a range of in-game systems
138 ◾ Procedural Generation in Game Design
CONVERSATIONS
One of the most interesting aspects of AI in PCG games is the generation
of speech and conversations appropriate to a procedural world. Ultima
Ratio Regum (URR ) development is focused on a complex conversational
AI rather than a complex combat, movement, or ambient AI, as conversa-
tions are fundamental to how players of URR engage with the game’ s AI.
We can reasonably split generated conversation elements into two cat-
egories— the PCG of the actual words that the AI actors speak, and the
conversation system itself.
The procedural sentences spoken by URR ’ s AI characters consist of a
range of elements, which draw on procedurally generated dialects, and
also the specific opinions and current mood of the person doing the speak-
ing. World generation in URR includes creating a unique dialect for every
in-game culture, of which there are ordinarily roughly 40, consisting of
large feudal nations, smaller tribal nations, nomadic nations, and perhaps
someday independent city-states (Figure 13.1).
Dialects
Generated dialects consist of several components.
First, the game selects a group of consonants, vowels, and syllables, from
which all “ invented” words for that dialect (such as the names of places and
people) will be constructed— this is a reasonably standard technique for
Artificial Intelligence ◾ 139
Conversation System
In addition to the dialect and subsequent sentence generation system
outlined above, URR also deploys a particular kind of conversation
system. The player chooses from dozens of topics— artworks, history, ide-
ologies, religions, monasteries, travel, animals, and books— and the list
of potential questions in each topic grows as the player learns more about
those topics.
Upon learning about a new artistic movement in poetry, any NPC can
be asked about that movement; upon learning about a particularly bloody
war fought 80 years ago, any NPC can be asked about that war; or upon
learning about a reclusive hermit who might hold a crucial clue to the
player’ s victory, any NPC can be asked about the location and disposition
of that hermit. Crucially, of course, none of these elements were fixed in
world generation— all these conversation options have emerged through
the game’ s PCG.
The conversation system is therefore designed specifically to take
advantage of the fact that these are AI actors within a procedurally gener-
ated game. URR adapts immediately to whatever new output of the proce-
dural generators has been created and identified by the player, whether it’ s
a painting, a person, or a piece of history, and allows the player to start a
conversation about an effectively infinite number of topics.
Similarly, while sentences are constructed from many elements, an AI
actor is always able to put together an appropriate reply to any topic asked.
This yields a PCG response to a PCG question, even if that response is
only to express a lack of interest because you are asking them about a piece
Artificial Intelligence ◾ 141
CONCLUSION
Whether your actor navigates terrain, attacks, or sociopolitical debates,
their ability to detect and adapt to changing circumstances is key to their
satisfying performance in a procedurally generated game. The question is
often not how many verbs the AI needs, but rather what types and com-
binations of input it can react to, and what elements of its reaction can
be generated and will yield interesting outcomes. When trying to make a
world that feels alive and unique, PCG developers must consider the val-
ues they want their world to express, and move from this into developing
their characters’ strategies, speech, and desires.
Chapter 14
143
144 ◾ Procedural Generation in Game Design
Commentary
Spawn by Timer is a good spawn technique when you want to test the
player’s skill, aptitude, or general power level. The enemies appear whether
the player is ready or not, making this a good technique to use when the
approximate power level of the player is fixed and relatively the same for
everyone. Factors such as level-ups, gear, or player skill can cause the
effectiveness of the player to vary considerably, making Spawn by Timer
quickly lose its appeal.
Procedural Enemy Waves ◾ 145
Levels that use Spawn by Timer are often crafted for a specific diffi-
culty by a designer—if the player is a bit stronger, each wave becomes too
easy and the player can be left bored. If the player is a bit weaker than the
designer anticipated, then the player quickly becomes overwhelmed.
This latter problem is extremely common when using Spawn by Timer.
Suppose you have waves of five monsters. Based on the designer’s playtest-
ing, it takes 15 seconds to defeat a wave, so the waves are set to be 15 sec-
onds apart. If the player is even 20% weaker than the designer anticipated,
then each wave might take 18–19 seconds to defeat. Just 15 seconds into
the fight the player might still have one enemy at full health when wave
two spawns. This combination of enemies might be so challenging to the
player that they have three monsters alive when wave three spawns. This
effect can “snowball,” causing the player to become farther and farther
behind the intended difficulty until completely overwhelmed.
Whether this snowball effect and sensitivity to player power can be
beneficial or detrimental depends on the design goals of the level. If the
strength of the player character is well known and it is the designer’s intent
to test whether the player has reached a certain level of mechanical profi-
ciency with the game’s controls and strategy, then a Spawn by Timer event
would be very appropriate. On the other hand, if the goal is to provide a
cool experience for the player regardless of their gear or skill level, then
the snowball effect is inappropriate and a different spawning technique
should be used instead.
The Starcraft holdout missions are a good example of Spawn by Timer.
On a typical Starcraft level, the power of the player is relatively well known
and the goal is to test the player’s ability to play strategically in order to
win or lose.
Some players may be so quick and adept at killing the enemies of each
wave that there is a possibility they clear a wave before the next wave is
ready to activate. In this situation, the designer has two choices:
1. Delay until the timer elapses, allowing the player a breather. This
approach not only is simpler to implement but also rewards the
player for finishing early. However, this approach also risks disturb-
ing the pacing or boring the player, as they will have no enemies to
fight until the next wave is spawned.
2. Set up your level so that the next wave triggers on a timer, but
should the player clear the wave early, then the next wave triggers
146 ◾ Procedural Generation in Game Design
Key Characteristics
• Good if you want to test whether the player has mastered certain
game mechanics
• Sensitive to the player’s current power level
• Can lead to snowballing
• Allows precisely designed pacing
Commentary
Spawn on Completion presents some amount of challenge to the player,
but with some flexibility to adapt to how well the player is doing. The dif-
ficulty of each wave can be calibrated by the designer without the difficulty
of one wave affecting the others. Unlike Spawn by Timer, if the player
struggles with one of the waves (but manages to complete it), it won’t have
a disproportionately adverse effect on subsequent waves.
Spawn on Completion is used in the World of Warcraft raid zone “The
Battle for Mount Hyjal,” in which players repeatedly confront 10 waves
followed by a boss fight. The approach allows a mix between testing play-
ers for a minimum gear or skill level and still keeping players engaged the
entire time.
Since the difficulty of each wave does not directly affect the challenge
of other waves, Spawn on Completion can also be a way to test the power
of the player when there are multiple vectors on which to measure player
power. For example, if a spaceship game allows players to excel with mis-
siles, laser beams, and shields, then three different waves might test the
player’s abilities along these three different vectors. If the player is strong
or weak against one vector, then the player will find that wave to be par-
ticularly difficult or easy; however, the player still needs to demonstrate
sufficient proficiency along each vector to complete the level as a whole.
One cautionary note: Waiting for the previous wave to be completed
before the next wave spawns can sometimes lead to a behavior in which
the player deliberately avoids killing the last monster to “drag it out” and
allow health, resources, and cooldowns to recover. This can be mitigated
somewhat (but not entirely) by combining this spawn technique with a
Spawn by Timer and allowing either condition to cause the next wave to
spawn. Doing so introduces the risk of introducing the snowball effect
that Spawn by Timer is susceptible to, but the two techniques are very
often combined successfully.
One often desirable characteristic of Spawn on Completion is that it is
readily apparent to the player that the enemies are coming in waves. This
can be very exciting, as it allows alternating periods of tension and release
as the waves come in.
Key Characteristics
• Good if you want to be somewhat adaptive to how powerful the
player is but still want to have minimum performance requirements
148 ◾ Procedural Generation in Game Design
Commentary
Continuously Escalating Total is a good technique to use when a dramatic
arc is desired. Because enemies are continuously replacing themselves, the
fight needs to end based on a criterion other than “defeating all the ene-
mies.” The most common is reaching a kill total or a time limit.
With aggressive tuning values, Continuously Escalating Total can be a
fun spawning technique to use for a bonus level or other minievent. Since
the number of active enemies is continuously increasing, the player never
truly “beats” the event. In this context, the event instead becomes a test to
measure how far the player can get.
In many games, gauging the player’s power level is difficult due to
the number of factors that contribute to player success. This makes
Continuously Escalating Total a good spawning technique to use when
the player’s power level may vary widely due to either play skill or charac-
ter progression. Early on, the player might play a Continuously Escalating
Total level and find they could survive 30 seconds, and then later in the
game, when they have grown in skill or character progression, they are
able to play the same level but survive for two minutes. This provides a
tangible benchmark of how far they have come.
A variant of Continuously Escalating Total is used in Diablo III for the
Cursed Chest events. The goal of the Cursed Chest events is not for the
player to either defeat the enemies or die trying. Rather, the design intent
is for the player to always kill enemies, but for the event to be a test of how
many enemies the player can defeat. The player has exactly one minute
to kill as many enemies as possible, and the faster the player can kill the
enemies, the faster they spawn.
A cautionary note: Depending on the exact mechanics of the game and
the presentation of the results, overreliance on Continuously Escalating
Total can become exhausting for the player. Constantly growing in inten-
sity until you are ultimately overwhelmed can be exciting, but as designers,
we should be cautious when we require players to maintain this excite-
ment cycle for extended play periods.
An interesting property of Continuously Escalating Total is the rela-
tionship between player power and how long the event takes based on the
completion criteria:
Choosing the right completion criteria based on the needs of your game
is an important decision for effective use of this spawning technique.
Key Characteristics
• Adapts to being fun and challenging for both low-end and high-end
players
• Good at allowing players to measure themselves along a continuous
spectrum of progression rather than being a binary pass–fail check
• Can be mentally exhausting to do for a long period of time
Global currentWave = 0;
Function UpdateTick()
{
CurrentHealth = SumOfHealthOnCurrentWave();
MaxHealth = SumOfMaximumHealthOnCurrentWave();
HealthPercentage = CurrentHealth / MaxHealth;
Commentary
Hitpoint Progression is a good system to use when you want the player
to experience a continuous stream of enemies that is always presenting
a challenge but has some ability to adapt to how well the player is doing.
Similar to Spawn on Completion, Hitpoint Progression gives the designer
the ability to create some waves that are particularly challenging or the-
matic, or stress different vectors of player power while ensuring the player
doesn’t get overwhelmed if they are below the designer’s expected power
level.
If the player is doing well, enemies spawn faster; if the player isn’t doing
well, enemies spawn slower. For this reason, Hitpoint Progression is a
good system to use when a high variance in player power is expected due
to skill or character progression and the designer wishes to create a dra-
matic encounter that is likely to be fun and engaging for the widest pos-
sible audience. By the same token, Hitpoint Progression is a bad spawn
technique to use when you wish to test player performance.
Key Characteristics
• The most adaptive of the four spawning techniques
• Not good for measuring player power or skill
• Good for creating a dramatic combat experience
152 ◾ Procedural Generation in Game Design
CONCLUSION
Changing even what seems like the smallest element of your procedural
algorithm can result in highly varied player experiences. Timers, comple-
tion, continuous escalation, and hitpoint progression are only four of the
many possibilities of spawning enemies. The correct spawning technique
or combination of techniques can be selected on grounds of intensity,
challenge, pacing, exploitation, balance, or other factors, depending on
your gameplay’s unique needs.
Chapter 15
Generative Artwork
Loren Schmidt
Independent
I n the early 1950s, Desmond Paul Henry found a World War II bomb
guidance computer at a military surplus store. Fascinated by the move-
ment of the analogue computer’ s mechanical components, he altered it
in such a way that instead of expressing its processes as bomb-targeting
information, it drew pictures. Its inner workings were superficially sim-
ple, on an algorithmic level not dissimilar from pendulum-based drawing
machines. But Desmond Paul Henry’ s drawing machines have made some
of the most deeply beautiful human computer art. And they achieve all
this with great lightness and elegance.
Henry’ s machines draw with energetic, organic lines: there is a slight
flutter to the weight, the edges undulate gently like bone ridges or rippling
skin. They feel deeply appealing on a human level.
Much of today’ s digital art (especially if you work in games) has a fixa-
tion on fidelity and technical showiness. It is hard not to think this way:
beyond the immediate appeal, visual fidelity is often seen as an indicator
of artistic merit. This is a complicated topic, and one that I don’ t have
space here to dissect properly. Let it suffice to say that
153
154 ◾ Procedural Generation in Game Design
Your art is valuable and valid no matter where you are coming from.
This section aims to arm you not with new technical tools, but with gen-
eral techniques and modes of thinking that are useful in addressing the
human side of generative visual art. It is designed to help you quickly apply
these concepts to any generative work (including games), so please apply
them wherever they are useful in your own life.
TECHNIQUES
Scope is not quality; it is a separate axis : When finishing up or fine-tuning
a project, one might be tempted to try and “ improve” it by adding fea-
tures (Figure 15.1). The generated tree gets tiny animated flowers; the sky
gets heat haze and atmospheric scattering. This may seem natural, but it is
not: making your project flashier and adding technical tricks is increasing
scope, not quality. Instead, try taking a step back. What does your piece
feel like, and how does that differ from how you want it to feel? Are your
proportions good? Could you tune it better? What is the weakest part of
the piece? Could it be improved by removing anything?
Thinking in terms of processes : We are usually taught to evaluate algo-
rithms in terms of whether they work. But I’ d argue that there is another
more important metric here that largely goes neglected. Are your algo-
rithms emotionally relevant to your project? Code is a rich and complex
language, and there are many different ways to write the same process.
Your individual decisions are a powerful expressive conduit. Also be
aware that sometimes dissonance or distance can subtly insert itself when
the algorithms do not feel the way you thought they would, when the tools
you are using are not in harmony with your goals. If you find this happen-
ing, can you alter your algorithms or your goals so they are better in tune?
Symmetry and structure : Working digitally, one of your great strengths
is the way iterative processes naturally tap into human perception. Humans
have a strong natural response to symmetry, and engage automatically in
pattern-detecting behavior. A few shapes with some symmetry applied
can quickly start to look compelling (Figure 15.2).
Mark making : Consider the ways you are making marks. This might
mean drawing pixels to a screen, rasterizing vectors, or drawing poly-
gons in three-dimensional (3D) space (Figure 15.3). This might mean
adding letters to a string. Certain tools have a very distinct fingerprint:
for instance (as of 2016), much visual work done in JavaScript or Unity
is highly recognizable as such. Perhaps this esthetic cast works in your
favor. But if you find yourself fighting against it or wanting to try out other
Generative Artwork ◾ 155
possibilities, consider how your marks are made. Perhaps you can use the
built-in functions in an unconventional way, and come up with something
that works better for you? Similarly, experimenting with writing your own
low-level drawing routines can open up a wide range of mark-making pos-
sibilities not available in tools by default (this can be a technically or com-
putationally intensive thing to do).
Postprocessing : Postprocessing can mean a number of things, but here
let us consider it to mean altering your output after it has been created.
Conventionally, there is little breadth in these techniques. In the realm
of real-time 3D, for instance, postprocessing is largely limited to a few
standbys: vignettes, motion blur, color correction, and screen space ambi-
ent occlusion. But even built-in tools often have a lot of untapped breadth.
And if you write your own postprocesses, there are many other expressive
options available. For instance, if you modify diffusion and pattern-dith-
ering algorithms such as Atkinson or Floyd– Steinberg by feeding them
unconventional diffusion kernels, you can create a wide range of effects,
such as the one depicted in Figure 15.4. It’ s also worth noting that there
need not be a rigid boundary between creation and post effects. There is a
lot of interesting potential for feedback between the two.
PERCEPTION OF INTENT
Searching for the intent of the creator is a natural human way to interact
with any artifact. One may ask: Who made this? What was their process
like? What were they feeling? Sometimes people deliberately turn this capac-
ity off or deemphasize it when looking at digital art. As mentioned above,
humans are avid pattern detectors. Repetition and pattern can be beautiful.
Sometimes one might make an elegant, crystalline algorithm and wish to
Generative Artwork ◾ 157
MARK MAYERS
create a dynamic sky system, which is critical for setting the mood of scenes.
Nonorganic meshes in the scene are generated through fractals and proce-
dural meshes. For instance, the black obelisks present in every scene of the
game are created by recursively cloning a simple cube in a pattern.
These individual systems combine to compose the “ universe” of Desolus ,
a complex world created from simple algorithmic rules. This process of cre-
ation emulates the natural world, as the universe operates by a set of laws
that humans can ostensibly describe through science. However, it is the art-
ist who interprets what he or she finds most beautiful about these universal
laws.
Chapter 16
161
162 ◾ Procedural Generation in Game Design
freedom making the art toys, and I spend more time enjoying the wildness
of the generativity and less time worried about gameplay issues.
Art toys are also a good way to explore new kinds of generative meth-
ods (algorithms suitable for generativity), or to try out old favorites in a
new context. I’ ve repurposed the particle-based techniques we used to cre-
ate Spore planets to also make interactive drawing tools that come to life.
Lindenmayer systems (L-systems) can create nice trees for game back-
grounds, but they can also be used to make surreal flowers for a flower-
arranging app (Figure 16.1). Context-free grammars can construct dungeon
levels and Mario platforms, or can build music and poetry. Flocking algo-
rithms can move nonplayer characters (NPCs) for combat, or can power a
choreography generator. I’ ve written a popular blog post on different gen-
erative methods you might want to try, “ So You Want to Build a Generator,”
but I can’ t think of a single algorithm that couldn’ t be turned to making art,
so keep your eyes open for new potential procedural paintbrushes.
One of the reasons I love making art toys with procedural content
is that, in games, the generated content is often invisible (like artificial
intelligence [AI] movement) or in the background (like sky textures and
trees), but it’ s always serving the purposes of the gameplay. The gameplay
is always the star, and the PCG plays a supporting role. What if the user
were interacting directly with the content generator? What if the user were
controlling the generator, giving it feedback, or exploring and curating the
FIGURE 16.1 Art toy by Kate Compton, where the user iteratively breeds new
procedural flowers, generated with an L-system and an evolutionary algorithm.
Generative Art Toys ◾ 163
things it made? Suddenly, the focus is on the generator itself; now it’ s the
star of the show and the center of attention! As someone who loves build-
ing generators, this is a pretty delightful situation.
A user who uses a well-made art tool will often forget about the tool’ s role
in creation altogether, which is not a bad outcome! Saying “ I’ m really good
at this” is a much more powerful feeling than “ this generator is good at this.”
Conveniently, a user who takes to social media to share their skill at a creativ-
ity is also symbiotically promoting the app, too! Call it the Minecraft effect:
when the users feel creative and powerful, both the users and the apps win.
KASPAROV’ S CENTAUR
Isaac Karth
Today, new AI and generative tools are creating art. A neural network can
transfer the style of one image onto another or change the composition. A
photograph can be made to look like it was painted by Van Gogh or Renoir.
This isn’ t the first time artists have dealt with new technology. Generative
tools have strong parallels with early photography. As photography strug-
gled to establish itself as a medium in its own right, some painters reacted
by embracing Impressionism. Impressionism took inspiration from the more
candid subject matter that photography allowed, but it also embraced the
subjective visual aspects that photos had trouble reproducing.
Likewise, in the wake of his historic loss to IBM’ s Deep Blue, chess grand-
master Garry Kasparov became interested in a new way to play chess. In
1998, he played the first game of “ advanced chess” against Veselin Topalov:
each player used a computer as a partner.
This cyborg play style, sometimes called “ centaur chess,” created bet-
ter players than individual humans or machines. Like the centaur, the
human– machine collaboration lets each half of the combination overcome
166 ◾ Procedural Generation in Game Design
the weaknesses of the other. The human is still playing the game, but the rote
work has been automated, freeing the player to express themselves.
An artistic metaphor for this is the generative artist Strangethink’ s Joy
Exhibition . Joy Exhibition is a little VR art gallery, where the only painting
tool is a collection of billions of procedurally generated paint guns. Each gun
has a distinct and weird pattern. These paint guns are a microcosm of PCG
and centaur art.
Interestingly, impressionist paintings seem to work particularly well for
style transfer. Something about the loose brushstrokes appears to make it
easier for the machine to generate a cohesive result. The future of game and
art generation likely has similar discoveries lurking, waiting for the right artist
to put the pieces together.
Inputs
Inputs can be anything from simple keyboard input or scroll wheels, to
touchscreen and mouse-dragging or tablet pens, to full body tracking
with a Kinect or 3D tracked VR hand controllers.
One of the important considerations here is to consider the “ width” of
the data pipeline. A keyboard produces very sparse data: binary keypress
events, spaced out over several seconds. A mouse provides a continuous
feed of X , Y coordinates, two dimensions of data recorded continuously
over time. A hand tracker like the Leap Motion records the joint positions
and rotations of wrists, hands, and fingers. If wrists move freely in 3D
* http://www.galaxykate.com/arttoys/arttoy-cards.pdf
Generative Art Toys ◾ 167
input
input drawings on input output
global wind speed persistent kinect projection on/in
surface living being
outputModifier
inputModifier output input
interactors and
viewers aren’t the on a dress at a projection on face tracking
same species fashion show very small
screen
space, and each finger joint has about one-and-a-half degrees of freedom
(rotation plus a bit of side-to-side motion), a hand produces 50– 100 data
points per sample, a huge pipeline of information to process!
Very high degrees of freedom (like skeleton tracking) require con-
tinuous feedback to the user to help them understand the system. The
Treachery of Sanctuary , a triptych art installation by Chris Milk that
uses the user’ s shadow as input, does a spectacular job at this. As the
user raises their arms, they see their fingers’ shadows extend into large
feathered wings, and lowering the arms retracts the wings. As they flex
their fingers in and out, they see the feathers fan in and out at the same
rate. This continuity (temporal and physical) of the generated shadow
gives a great stream of feedback to the user, and the gallery patrons, even
children, instantly understand and begin playing with their shadow.
Contrast this to many other body-tracking apps: while Treachery of
Sanctuary uses the entire continuous pipeline of input to generate the
shadows, other apps try to detect “ pose” occurrences, compressing the
rich pipeline of data into a series of discrete binary events spaced out over
time: the same spacing and discreteness as keyboard input. Good user
interface (UI) feedback is often an issue with these apps, perhaps because
they’ ve discarded 99.99% of the user’ s input before they start. But genera-
tivity like that shown in Treachery of Sanctuary suggests that this need not
be the case.
168 ◾ Procedural Generation in Game Design
Gestural Curves
Hands are rarely still. They wave and flex, clench and open. Each joint
moves along an invisible animation curve through space, and we can
record those curves as well. Google’ s Tilt Brush takes this approach,
recording the curves of motion and then reskinning them with different
Generative Art Toys ◾ 169
strokes or using them as paths for additional actions (see the “ Rendering”
section later).
Rendering
We have inputs and a way to transform those inputs into progressive layers
of different kinds of data structures.
Wait, wasn’ t there supposed to be some art in this art toy? Certainly the
most memorable part of any art toy is the visual results of the interaction.
Drawing is often defined as “ making a mark on a surface,” but what
does it mean to make a mark, and what is the surface? For an exhaus-
tive ontology of digital drawing tools, I recommend Alvy Ray Smith’ s
FIGURE 16.3 Hand-tracking image. On the left, hands are tracked as arrays
and acceleration. Even drawing these forces creates interestingly emergent pat-
terns. On the right, velocity and acceleration are drawn additively, with subse-
quent hand forces overdrawing each other to leave a trail of movement over time.
170 ◾ Procedural Generation in Game Design
“ Varieties of Digital Painting,” but for the purposes of this chapter, here
are the basic concepts that you can use to build a rendering method:
Canvas : This may be a buffer or a series of composited buffers. If we
are playing in 3D, or with vector graphics, it may also be a scene graph or
list of renderable shapes. Regardless, it’ s a way of recording what we will
render to the screen.
Mark : A semipermanent element or action. It might read from the can-
vas, as a “ blur” brush has to sample the pixels underneath before redraw-
ing them, or a “ fill” command paints outward until it encounters an edge.
It is constructed, it is added to the canvas, and (because we aren’ t working
in reality), it may morph or flow or change or be deleted. For a traditional
digital paint program like MS Paint, the canvas is a simple pixel buffer, and
most marks just write a color into an area of the buffer, or start a function
that recursively writes color into expanding areas until a stop condition is
reached. The buffer is never erased, only added to. An Illustrator graphic
has no persistent buffer as its canvas, but instead has a scene graph. If the
scene graph is changed (a mark is added or a color is changed), then the
scene graph renders itself onto a temporary buffer and onto the screen.
Additive versus parametric rendering : In additive rendering, there’ s a
buffer that gets added to and evolved each time, based on the previous
state of the buffer. Nothing is ever discarded; it’ s just built over, which
mathematically looks like this for some buffer with five marks or actions
being made on it: final buffer = ƒ e (ƒ d (ƒ c (ƒ b (ƒ a (buffer))))). Parametric
rendering is rendering without a buffer memory. Each time, it renders
the whole finished product from scratch, doing whatever subrendering or
compositing it needs to do along the way: final buffer = ƒ (a , b , c , d , e . … ,
initial buffer). But the boundary between these two is surprisingly flexible.
In a buffer-based drawing engine like Processing or HTML canvas, I may
have a scene graph that I want to redraw each frame. I can “ erase” the
buffer before drawing each time (setting each buffer pixel to a background
color), and thus achieve parametric rendering. Or I can choose not to clear
the buffer, and each parametric rendering will be made on top of the pre-
vious rendering. This technique leaves the past trails of a moving object
visible, which can be good for inexpensive trail rendering, notably used in
the Windows Solitaire win animation and the Microsoft 3D Pipes screen-
saver. There’ s also an interesting middle path, where the previous render-
ing is partially obscured. I often draw a partially transparent rectangle on
top of the previous rendering, leaving the trails visible, but fading out over
time in an attractively veiled way.
Generative Art Toys ◾ 171
The two competing VR drawing apps, Oculus Medium and Google Tilt
Brush , seem similar at first, with identical inputs, and both using a ges-
tural curve model to record their marks. But under the surface, one is an
additive and the other is a parametric rendering, and this changes their
interaction. Medium uses voxels, a 3D version of the pixel buffer. The user
can “ mark” more voxels into space, or write over previous voxels (or write
over them with blank space to erase). But one can’ t go back and edit an
earlier mark, other than by undoing to the point it was made. Tilt Brush
is fully parametric, where each stroke is stored as a vector and then “ ren-
dered” into the scene graph (which is later rendered onto the screen in
3D). This allows modification of previous strokes, and more interesting
ways of rendering strokes as animated curves or particle effects or pat-
terned ribbons.
Advanced and indirect rendering: Tilt Brush and Medium are both
intended (if unintentionally) as tools for good artists (note how their pro-
motional materials show famous Disney animators and illustrators using
them). They want to be flexible enough for anyone to build anything, so
they kept their rendering very directly related to the input. If you’ re build-
ing a smaller art tool, for more flexible users, the mapping from input to
output can be much less direct. Flexibility and control can be sacrificed for
generativity and power, and that can be a good thing!
Remember that the rendering being described here doesn’ t mean the
final rendering to the screen, but the way that the abstract model turns
into a mark.
One very common parametric approach to rendering is to have an
array of numbers, a “ string of DNA,” which is rendered into some physi-
cal form. For an animated flower prototype, I turned an array of 30 float-
ing-point numbers to a set of rules for a flower-generating L-system. This
rendering process had several advantages. The space of the flowers was
interesting and varied, but also continuous. This allowed me to perform
an evolutionary algorithm on the flowers responding to the user input of
selecting their favorite. I could also “ lerp” between new values over time,
mutating the flowers according to time. I also was able to hook the values
up to a music analyzer, which morphed them in time to music, and then
hooked it to a Leap Motion Controller, so that each hand position would
generate a different flower.
This is the powerful part of this “ input– model– rendering” model of art
toys. Once you have it built, you can begin switching out new inputs or render-
ing methods, generating new, playfully strange art toys with each variation.
172 ◾ Procedural Generation in Game Design
You can also use time as an input parameter for any parametric ren-
dering. Rendering at frame 2 will be slightly different than at frame 1 or
0. If your parametric functions are continuous, rerendering frames (or
rebuilding scenes) will create the effect of a smooth animation. The art
game Panoramical is a lovely example of this. The user sets nine different
two-dimensional (2D) sliders, creating 18 different parameters. Time is
added as a 19th. Each of the many levels is a different parametric function
to interpret those 19 parameters into music and a 3D scene of geometric
objects. Changed over time, it creates an animated soundscape that is con-
trollable by the user.
Another engaging way to interpret models is to have simulations or
other algorithms using them as inputs. Any graph or set of points can be
turned into a Voronoi diagram or Delaunay triangulation. From there, it
could be rendered as a 3D mesh or as paths of connectivity for simulated
agents to move along. Models and inputs can create forces that act on the
elements in the world, rather than being elements themselves. The classic
art installation Text Rain (Camille Utterback and Romy Achituv, 1999)
drops text from the sky on a projection, and the users create barriers with
their shadows that it can flow down or puddle upon. Art toy users could
also create wind, gravitational wells, water currents, or any other force to
move renderable elements. Imagination (and simulation power) are the
only limits.
match their drawing to the given still life or landscape and judging them
accordingly. But this art toy doesn’ t allow the user to draw directly, only
by pressing keyboard keys to activate surprising and frustrating glitch-art
filters, making the automated judgment a silly and surreal metric.
Another art toy that gives the player control over curation but no cre-
ation is Picbreeder , an online tool to browser neural network– generated
images and “ breed” new ones. Although the users’ only interaction is
clicking on the ones they like, users still show pride in finding unusual
ones in the space and showing them to other users.
Sampling
In order to produce sound, I used a sample-based synthesis approach.
The basic premise is that you create and record samples from your instru-
ments first to use as a basis for all the audio. Another approach would
be to synthesize all your audio in the engine, which, although possible,
requires a greater knowledge of audio synthesis and audio programming.
Furthermore, synthesizing complex audio can put a big strain on your
CPU. A sample-based approach gives you all the power of your existing
instruments, synthesizers, and sound effects (SFX) libraries, and is sim-
pler to understand and implement.
If you’ re familiar with audio hardware or software, you may be familiar
with the concept of a sampler. A sampler plays back short audio files while
simultaneously modulating them to produce modified versions of the base
sample. For example, the most basic sampler can play a sample at differ-
ent speeds, which also modifies its pitch. Even this basic functionality was
enough to start building my procedural audio system. But first, a little bit
of music theory.
175
176 ◾ Procedural Generation in Game Design
Pitch
Western music contains only 12 notes, which are then repeated over about
11 octaves, beyond which the notes become imperceptible to the human ear.
These 12 notes are C, C#, D, D#, E, F, F#, G, G#, A, A#, and B. In some cases, we
might call C# (pronounced “ C sharp” ) a D flat, F# a G flat, G# an A flat, and
A# a B flat, but for our purposes this doesn’ t matter. In fact, the names of the
notes are completely irrelevant and can sometimes be more confusing than
helpful. For example, octaves start on C rather than A, and there is absolutely
no correlation between any of the sharps (or flats) with their corresponding
nonsharps (or nonflats), that is, A# and A. The names of the notes are just
names, nothing more. Octaves are used to represent how high or low a given
note is. That is, an A4 (that’ s A on the fourth octave) is just a higher-pitched
version of an A3, which is consequently higher than an A2, and so forth.
Now that you understand the selection of notes you have at your dis-
posal when making music, it’ s important to understand what a note actu-
ally is. A note is a wave of sound created by an object that’ s vibrating at a
given frequency. So when a speaker plays an A4, for example, it’ s because
the speaker is vibrating at 440 Hz, which travels through the air until it
reaches your ears. The important thing to note here is that every note in
Western music corresponds to a specific frequency. Table 17.1 is a lookup
table of note frequencies by name and octave.
So what does this mean? First, every note in every octave has a spe-
cific pitch. Second, the ratio between a note and its neighbors is always
the same (as is the ratio between its neighbor’ s neighbors, its neighbor’ s
neighbor’ s neighbors, etc.).
From any note, you can multiply its pitch by the same known value
and land squarely on a neighboring note. This is the key to sample-based
synthesis. For example, if you loaded a recording of a C3 note from a piano
into a sampler, you could play it back as any other note from that same
piano within limits.
What limits? A basic sampler modifies the pitch by playing back sam-
ples at a different speed. As a result, there’ s only so far you can stretch a
given sample before it sounds terrible. How far you can stretch a sample
depends on the sample itself, but you don’ t expect to go beyond a couple
octaves up and down. If you need a wider range, you could use multiple
samples, one for every other octave range, for example. Using this infor-
mation, you can emulate an instrument playing any note in any octave
using only a handful of samples.
Audio and Composition ◾ 177
Implementation
Most of the instruments in Skipping Stones are actually just basic sam-
plers. Each one is loaded with a sample of a C note in some octave (usually
C3), and when it plays, I modify the pitch in order to play the desired note.
Skipping Stones was built in the Unity engine, which allows you to set the
pitch of an audio source as a floating-point number. So in this case, a pitch
of 1 means play at normal speed, 0.5 is half speed, 2 is double speed, and so
forth. I created a lookup table of pitches by calculating the ratio between a
note and its neighboring note and multiplying forward until I had enough
range.
Therefore, playing an instrument with a pitch of 1 will give me a C
(because that’ s the pitch of my original sample), whereas playing an
instrument with a pitch of 1.059463 will give me a C#, a pitch of 1.122462
will give me a D, and so forth. Additionally, since all my instruments are
loaded with a sample in C, I know that the same pitch across all my instru-
ments will produce the same note.
At this point, you’ re able to start building basic instruments, so it’ s a
good time to start working on your procedural composition engine.
just be the style of a composer whose style you admire. I did this by adding
extra rules that could be triggered randomly, or using a statistical model.
Beat
The first thing you’ ll need is a way to keep all your notes on beat. In Skipping
Stones , the player skips stones across a lake to create music. Every bounce
generates a part of the composition. Our bounces were physically driven,
based on the force and angle of the throw, so we couldn’ t be sure that a
stone would bounce on beat to the music. As a result, the music sounded
more like a cat walking across a piano than actual music. So in order to
fix this, I wrote a metronome system to keep time. When a stone hits the
water, it submits an event to the internal metronome, which in turn sub-
mits an event to the audio system to play a given instrument when the
next appropriate beat occurs. If you’ re familiar with metronomes, you’ ll
know that after you set the beats per minute (BPM), it’ ll tick once on each
beat. But in order to make interesting music, you need to play notes in
between beats as well. So in order to stay rhythmically correct in between
beats, you’ ll want your metronome to keep track of half beats, quarter
beats, eighth beats, sixteenth beats, and so forth until you’ re satisfied with
the result. Depending on how you’ ve built your metronome, an easy solu-
tion is to double your BPM for every beat division you’ d like to add. For
example, for our purposes 180 BPM is the same as 90 BPM if you consider
every tick of the metronome as a half beat instead of a whole beat.
My metronome implementation was based around the InvokeRepeating
function, as shown below:
InvokeRepeating( “ ProcessAudioSources ” ,(60/
bpm),(60/bpm));
This was a quick and accurate way to implement a consistent beat. You
may be tempted to try using multithreading (or in the Unity engine, using
“ Coroutines” ), returning a call to WaitForSeconds(), but in practice, this
is prone to drifting off beat over time. InvokeRepeating is a function that
schedules a call to another function, in this case ProcessAudioSources,
after a given time and then repeatedly calls that function again after
another given time. So in this case, I’ m calling a function called
ProcessAudioSources on every tick, as determined by my BPM. Put sim-
ply, ProcessAudioSources fetches a list of any queued audio and plays it
back. In my particular case, it also fetches the next available audio source
Audio and Composition ◾ 179
(because we operated with a limited number of audio sources that can play
at once) and applies any volume, pitch, or filter values before playing.
In Skipping Stones , the length of a note was controlled by the length of
the sample in almost all cases. However, it would be fairly straightforward
to add a simple envelope to audio sources. The purpose is to have proce-
dural control over your note lengths; that is, are they whole notes, half
notes, quarter notes, and so forth? This is done by dynamically lowering
the volume of an audio source after a given amount of beats, and turning
it off once it reaches zero.
Scale
Here I cover some basic principles of music theory so that we can encode
them into our composer. My goal is to provide as little information as pos-
sible in order to get started, so I take some shortcuts. It’ s also important to
understand that the “ rules” of music theory were developed over centuries
of observation and experimentation, which is to say that it is not a science.
Music theory should be thought of more as guiding principles to lead you
toward something that’ s generally accepted as “ sounding good.”
The purpose of a scale is to provide structure by telling you which notes
you’ re “ allowed” to use, that is, out of the 12 notes in Western music,
which ones are OK and which are off-limits. For our purposes, you prob-
ably only need to understand the purpose of a scale and how it works, and
then let the computer do the rest.
Most of the scales used in Western music are just a variation on the
major scale, so I’ ll focus on that one. The major scale is seven notes long,
but we can’ t say exactly which seven notes until we’ ve chosen a root note.
For our purposes, the root note is simply the first note of our scale, and
choosing it is entirely up to us, or the algorithm.
Steps
It’ s important to understand the difference between whole steps and half
steps in music. A half step means moving one note forward, whereas a
whole step is two notes. First, I’ ll remind you of the order of the notes used
in Western music:
C C# D D# E F F# G G# A A# B C
E as our root note, how do we know the rest of the notes that comprise our
scale? We’ re going to start on E, make seven steps forward, and every note
we land on is part of our scale. In the case of the major scale, the seven
steps are whole, whole, half, whole, whole, whole, half. So, referencing the
note order above, that would give us
E F# G# A B C# D# E
And that’ s our E major scale, which composers refer to as the key of E
major. But this isn’ t a book on music theory. For us as procedural design-
ers, it’ s more important to understand how we got here, so that we can
encode it into our composer. We’ ll want to encode other scales as well, as
they can have a big effect on the perceived mood of the music. It’ s impor-
tant to experiment with different scales and root notes while you’ re trying
to find the right mood, and make sure to take note of anything you find
particularly beautiful.
In Skipping Stones , I usually pick the root note at the start of the game,
and change when the time of day changes. In general, the root isn’ t some-
thing you want to change very often unless you know what you’ re doing.
The major scale is generally considered happy sounding, and our game
aims for a moody atmosphere, so we mostly use the minor scale. When the
game starts, or when we start a new composition, I make an array of notes
by cross-referencing my scale tables (pictured below) with my pitch table
(Table 17.1) and my chosen root note.
int[] Major = {2, 2, 1, 2, 2, 2, 1 };
int[] Minor = {2, 1, 2, 2, 1, 2, 2};
int[] PentatonicMajor = {2, 2, 3, 2, 3};
The pentatonic major scale is a great example of a scale that doesn’ t have
this property. The pentatonic major scale is just the major scale, but with
the fourth and seventh notes removed. As a result, any sequence of notes
sounds good, but it’ s impossible to build a sense of tension and release.
A quick example rule you could deduce from this is that whenever you
play the fourth or seventh note in the major scale (which produce the most
tension), you’ ll want to follow it up with the root note (which releases
the most tension), but ultimately this is a stylistic choice and you should
experiment for yourself to determine what sounds good to you.
At this point, you can start to experience your procedural composer in
action, which means you can start to experiment with it and build stylistic
rules that appeal to you and your game.
Chords
Chords are simply notes that sound good when played together. Chords usu-
ally consist of three notes, but they don’ t have to. Here’ s my quick and dirty
guide to constructing chords. Once you know your scale, start on any note
in the scale. This is your chord root. From here, take the note two up (in the
scale), and finally the note two up from there. So, for example, the first, third,
and fifth notes of a scale make a chord, as do the second, fourth, and sixth, or
the third, fifth, and seventh. Now you know how to construct chords.
Depending on the scale you’ re using, the interval between those notes
can differ, and this will change the mood of the chord. For example, the
chord made of the first, third, and fifth notes of the major scale is a major
chord, and as a result sounds more uplifting. By contrast, the chord made
of the second, fourth, and sixth notes of the major scale is a minor chord;
therefore, it has a moodier sound.
This is the most basic way to construct chords, but there are ways to
modify a chord to give it different voicings. For example, normally the
root note is the lowest note of a chord, but this doesn’ t have to be the case.
Let’ s say we have a C major chord, played C3-E3-G3, where 3 represents
the octave in which the notes are played. We could play this same chord as
E2-G2-C3 or G2-C3-E3, which are known as the first and second inver-
sions, respectively. Notice we’ re playing the same notes, but the resulting
sound has a subtle difference.
Earlier I said that every four stones made up a single musical section, but
actually that’ s not true. The player had the ability to throw two stones
simultaneously, and would then have to wait for one to sink before he was
able to throw again. The first stone controlled the primary instrument.
This is the stone that generated the musical structure. The second stone
controlled our accompanying instrument.
The accompanying instrument didn’ t have as many rules associated
with it as the primary instrument. Because of its generally softer and
dreamier quality, nearly anything it played sounded good, as long as it
supported the primary instrument. In order to do this, it operated in the
same key as the primary instrument, and would sometimes make vague
mentions of the motif or play short arpeggios, but otherwise, it was free
to explore the music however the random number generator felt it should.
CONCLUSION
I could have continued to improve the composer of Skipping Stones , but we
had to end the project. While working on it, I found that every addition to
the engine made an enormous impact on the quality of the music it pro-
duced. If you’ re willing to learn some music theory and experiment, I’ m
certain you could build a more impressive procedural audio composer.
To this end, I recommend that you seek books that give concrete and
practical ways of applying music theory. I’ ve found Improvise for Real by
David Reed to be one of these books, but you’ ll need access to some kind
of instrument to get the most out of it. Another excellent read is Making
Music by Dennis DeSantis, which focuses on giving solutions to actual
problems when making music. Not every problem will apply to procedural
composition; however, many of the ideas are directly applicable.
It’ s important to understand that the beauty and expressiveness in the
Skipping Stones audio engine didn’ t come from just the procedural com-
poser, but also the instruments designed by our human composer to work
within the engine. As in other aspects of procedural game design, we must
find a balance between authored and algorithmic elements, and the two
must collaborate in order to achieve the best results.
III
Procedural Narrative
185
Chapter 18
while Dwarf Fortress and Crusader Kings 2 utilized complex world build-
ing and simulation to create a player-guided form of storytelling.
This chapter, alternatively, focuses specifically on the generation of
sequential stories that occur successively within a game world, similar to
quests in role-playing games or episodes of a television series. Relationships
and character attributes are used to drive a custom story grammar that
generates the actual story content, which in turn can impact the relation-
ships and characters of the game world. Grammars were chosen as the
representation for story in that they are relatively simple to author, under-
stand, and implement. Some disadvantages to grammars is that the results
tend to be highly structured and, at worst, could be perceived as repeti-
tive. This chapter is divided into several sections, starting first with an
introduction to grammars and story grammars. Second, we provide the
representation used for both the game world and story. Finally, we present
the design of the actual grammar rules, and discuss ways to improve the
generation process.
A → C
1.
A → B
2.
B → CC
3.
These are more formally called rewrite rules , where the symbol to the left
of the arrow is the pattern that, if it exists in our string of symbols, can be
rewritten to the symbol on the right-hand side of the arrow. For example,
Story and Plot Generation ◾ 189
if we start with the string A , we can rewrite that same string as either C ,
using rule 1, or B , using rule 2. Furthermore, we can rewrite the string B as
CC using the third rule. Therefore, strings C , B , and CC are all valid strings
that can be made with the starting symbol A . While this may seem limited,
if we add a fourth rule, say, C → A , then CC can be rewritten as AC , CA , or
even AA , which in turn could become AB , and then ACC , and then ACA ,
and so on. Using only rules 1– 3, we are always guaranteed to reach a point
where the string can no longer be rewritten for any starting symbol; with
the fourth rule, we can now expand the starting string A infinitely.
While the string grammar above may seem interesting, it doesn’ t have
any explicit story “ content” yet. However, while the symbols above are only
strings, there is nothing that prevents symbols from being actual story con-
tent, such as story events or structures. Early story structure research actu-
ally proposed that grammars could be developed to represent every story
structure in existence. Such a magical (likely fictional) grammar has yet
to be found; however, grammars have still found use for modeling struc-
tured types of stories, such as children’ s fairy tales (see Vladimir Propp’ s
“ Morphology of the Folktale” for such an example). Imagine instead that
we were to create a simple grammar for creating sidequests in role-playing
games, which are also typically highly structured. We might break down
the potential events of a given sidequest into its own set of symbols, say
[Journey ], [Encounter ], and [Discovery ]. Next, we create a set of rules:
1. [Journey ]→ [ Journey ][Encounter ]
2. [Encounter ]→ [Encounter ][Encounter ]
3. [Encounter ]→ [Discovery ][Journey ]
Now, with these three rules, and starting with a [Journey ], we can
get quests like [Journey ][Encounter ][Discovery ][Journey ][Encounter ] or
[Journey ][Encounter ][Encounter ][Encounter ]. The next step could then be
to write to expand our set of rules and symbols, which take the abstract
quest structure we just developed and turn it into a more concrete set of
actions and events. Consider the following new rules and symbols:
1. [Journey ]→ [Go to town ]
2. [Journey ]→ [Go to the forest ]
3. [Encounter ]→ [Fight a goblin ]
190 ◾ Procedural Generation in Game Design
4. [Encounter ]→ [Fight a dragon ]
5. [Discovery ]→ [Find gold ]
6. [Discovery ]→ [Find weapon ]
Applying this set of rules to our previous examples gives us much more
specific quests, such as [Go to town ][Fight a goblin ][Find gold ][Go to the
forest ][Fight a dragon ]. We still don’ t need to stop there, and could create
a new set of rules and symbols to state what possible dragons could be
fought, what weapons could be found, and so forth.
In implementation, grammars are often used as procedural content
generators by taking one or more symbols as a starting set and then ran-
domly applying a number of valid random rules until either a point is
reached where no more rules can be applied or a certain number of rules
have been applied.
One advantage to the two grammars discussed in this section is that
they are visually easy to understand and reasonably straightforward to
implement. One disadvantage to the grammar-based approach is that by
keeping the grammar entirely dependent on itself, we avoid any mean-
ingful connection with the game world. Most stories are structured
around characters, and in particular conflicts between these characters.
Essentially, without tying the grammar more directly to the characters
of the world, we can’ t hope to have stories that meaningfully involve the
game world in the generated story. As such, we will want to create a new
form of grammar that operates simultaneously on both a story grammar
and a representation of the social game world. In this way, each rule con-
tains both a social pattern and a story pattern, followed by a change to
both the story and the social world.
GAME WORLD
One of the driving assumptions of this investigation was the idea that
stories are based around character relations, and specifically about con-
flicts between characters. The role of the story then surrounds the resolu-
tion of conflicts one by one, usually with one major conflict driving the
entire plot. Therefore, interesting stories can only meaningfully occur as
the result of an interesting set of characters and relations. This means we
should first aim to model the game world in such a way that all this infor-
mation is made explicit. Within this particular investigation, we chose to
model the characters and their relations as a social network— essentially,
Story and Plot Generation ◾ 191
as a directed graph where each character is a node, and the edges represent
the relation of one character toward another. We define each character as
minimally having a unique ID and a set of attributes, which are essentially
a set of key– value pairs for each character, where the keys are the same
for each character, with only the value being different. “ Name” and “ age”
might be two examples of keys, where each character is expected to have
a name and age, but their actual names and ages will likely be different.
Likewise, we will define the relationships between characters in a similar
way, with each relationship containing a set of keys and values. “ Trust”
and “ friendship” may be two such keys. It is also useful to keep each edge
one directional, meaning that the relationship one character feels toward
another may not be the same as the relationship that character feels for
them. As a disclaimer, this is by no means the only way to have a model
of characters and relationships, but such a structure is intuitive and rela-
tively straightforward to author and implement. Likewise, similar rep-
resentations of characters and relations are relatively common, and seen
frequently in role-playing games and interactive fiction.
We assume a dynamic game world, in the sense that we expect that
the relations and even the attributes will change over time. In fact, given
that the core of the stories we are creating is related to characters and
conflict, it is arguable that a dynamic game world is necessary to repre-
sent the changes needed to construct interesting stories. It is also a lack
of dynamism that many players note (and lament) in a lot of branching
choice-based narratives or story-rich video games.
The very simple social model shown in Figure 18.1 will be used as
the basis for our subsequent examples in this chapter. Here, we have a
Western-inspired social world comprised of three nonplayer characters
(NPC) and the player. Each character has four attributes: a name, number
of bullets, money, and a certain level of gambling skills. There are three
types of relations: the money owed, the level of trust, and the affection
level between characters. For clarity’ s sake, we do not show all relations
between all characters in the world.
STORY MODEL
For our model of story, we will break away from the linear model used in
traditional story grammars and instead adopt the directed graph model
more commonly seen in interactive fiction and hypertext. Essentially,
in this model discrete sections of the story content form the nodes, with
edges indicating different branches of the story that a player can select. In
192 ◾ Procedural Generation in Game Design
001 002
Name: Ennio Name: Miller
Bullets: 0 Bullets: 2
Money: 50 Money: 15
Gambling skills: 1 Gambling skills: 2
Owes: 10 Owes: 0
Trust: 2 Trust: 3
Owes: 3 Affection: 0 Affection: 5
Trust: 5
Affection: 2
000 003
Name: PLAYER Name: Clint
Bullets: 6 Bullets: 2
Money: 10 Money: 1
Gambling skills: 3 Gambling skills: 5
this model, the actual story experienced by the player relates to the path
they take from one of the starting nodes of the narrative to one of its ter-
minal nodes. It should be noted that by doing this, we are now technically
working with a graph grammar rather than a string grammar. This means
that rather than just rewriting one symbol into one or more different sym-
bols, we are instead rewriting nodes in a graph with new graph pieces.
RULE DESIGN
Now, given both our models of game worlds and story grammars, we can
begin to create a new rule structure that makes use of both. We’ ll start by
dividing the types of rules we want to make into two categories, which
we’ ll call initial rewrite rules (IRRs) and secondary rewrite rules (SRRs).
We’ ll define the IRRs as the set of rules that give us a basic story skeleton
with which to work, and the SRRs as rules that rewrite and expand the
story skeleton. Essentially, our process to build a story will be to apply one
IRR to get our initial story, and then apply a number of SRRs to progres-
sively make the story more complex. One advantage to this approach is
that we always ensure that at every step of the generation we have a com-
plete story; that is, even if we only apply one rule, we still have a story.
For the IRRs, we only care about searching for patterns in the game
world; that is, when designing the IRRs, the main question to ask is “ What
Story and Plot Generation ◾ 193
interesting stories can arise out of the possible patterns in our social
graph?” Returning to our Western example from before, we can see that it
is quite possible for someone to owe more money than they currently have.
Thus, we can use this need for money as the main conflict for a possible
story. Following the example of many typical Westerns, we can envision a
potential story where a character in debt tries to win back their earnings
in a poker game. Given that in many cases we want to involve the player in
the story, a possible IRR may look like that shown in Figure 18.2.
Put simply, the pattern on the left of the arrow is the game world pat-
tern we’ re searching for; in this case, we are looking for a situation where
there is a character X who has less than 5 money and owes more than
that to another character, Y . If this pattern exists in the game world, then
we can initialize the story on the right, in which character X plays poker
against the player and takes whatever winnings they have to character Y .
We use the circle with the dotted line to indicate possible starting points
of the story, whereas the plain circle marks the possible ending points of
the story. In this case, there is only one start and one end to the story in
question. Looking Figure 18.2, we can see such a pattern existing between
Clint and Ennio, so it is valid for us to generate the above story with Clint
taking the role of character X and Ennio taking the role of character Y .
When designing an IRR, it is usually advised to use relatively simple
game patterns, such as using only two characters and their relations. The
reason for this is twofold. First, it can be quite costly performance-wise
to search a large graph for very complicated patterns, and it is a non-
trivial search to implement. Those familiar with performance issues in
X challenges
PLAYER
X Y
to poker
Money < 5 Owes > 5
X takes
winnings to Y
X Y X cheats at
Trust > 2 poker with Y
Story pattern
X wins all
X playing poker money from B
with B
we end up with a list of SRRs that could end up with our card game ending
in a violent duel, but those same rules could be used to duel wagon rob-
bers in the desert, or to catch people cheating at sharpshooting contests.
Ideally, there should always be more SRRs than IRRs, with many different
possibilities for all potential story events.
In terms of the actual application of SRRs, in practice it was reasonably
effective to first search for all valid SRRs, and then choose one at random
and apply it. This process could be repeated a fixed number of times for
each story. As an alternate approach, one could continuously apply SRRs
until there are no more valid SRRs to apply. However, it is easy to design
SRRs that may be applied infinitely and can break the generation. As such,
even if the designer is very cautious, it is still good practice to cap the gen-
eration process after a certain number of rule applications.
If we go back to the IRR defined above, we may want to have X take the
winnings of poker to Y , only if X actually won money in the poker game
(e.g., if the poker game was a minigame). In this case, we may want to have
the story branch at the two possible results, with a new second event that
X leaves defeated if they didn’ t win at poker. Likewise, we would want to
reduce the trust toward characters who attempt to cheat a specific charac-
ter at poker, and so forth. This adds an extra level of complexity to design,
in that the designer must consider each possible arrangement of precondi-
tions that could occur in the story. In practice, it is often good to run a pass
through a generated story and assert that each event has its precondition
met, taking into account any postconditions that are also applied.
METRIC-GUIDED GENERATION
In this section, we discuss a brief and slightly more technical alternative to
the application of SRRs. Previously, we stated that simply selecting valid
SRRs at random and applying them was a valid way to generate stories,
and this is still true. Interestingly, though, since we are calculating all
valid SRRs, it is quite possible to be more selective about which SRRs we
choose. Essentially, if we define certain features we would like to see in the
resulting story, we can prioritize which valid SRRs we choose based on
how we want the final story to be structured. We may, for example, want
to prioritize player choice, and so we prioritize valid rules that add one or
more branches to the resulting story. Likewise, we may want our Western
to be filled with shoot-outs, and thus we prioritize any SRRs that add gun-
fighting events. Conversely, if we want to keep characters alive longer, then
we may want to avoid actions that involve their death. (It is morbidly easy
to end in Shakespeare-like scenarios where all characters have murdered
each other.)
As a more complex example, imagine we kept track of all the post-
conditions resulting from each individual story. This means we know all
changes to the game world that occurred as the result of a story that the
player directly experienced or influenced. Now imagine we prioritized any
valid SRR whose game world pattern is met due to the changes the player
has made in previous stories. In essence, this means that when we generate
stories, we prioritize stories that occur as a result of something the player
did in the previous story. This adds a great deal of causality between stories
and helps the player to feel that their interactions are valid. For example,
if the player chooses to duel with someone and loses all their bullets, and
then we prioritize the generation of a story where the player is held up and
Story and Plot Generation ◾ 197
can’ t defend themselves, then the consequences of the previous stories can
affect all the subsequent stories. This, on top of a simulated game world, is
another way to keep the stories interesting, because even though the types
of stories generated may be similar, the context out of which those stories
are being generated is dynamic, ever changing, and sensitive to all the
actions taken by the player.
CONCLUSIONS
Story generation is by no means an easy task, and to date there are relatively
few games that have focused on story generation as one of their main fea-
tures. By consequence, story generation presents an interesting alternative
to the traditional means of authoring stories, by allowing the author to
focus more on the structures and rules that guide the player story, rather
than try to tie them to a particular story created by the author. And this
seems relevant, especially with an increased level of criticism toward the
minimal effects players typically have on the stories and worlds in game.
As the horizons of what a game is expand further and more experimental
works gain serious interest, it seems that games can be used not just as a
way to tell stories, but also to challenge traditional storytelling methods.
By focusing on experimental and generative elements, designing stories
becomes an exploration into how stories may be formed, opening that up
to the player, as opposed to simply telling them a good story through audio
logs and journals.
Chapter 19
Emergent Narratives
and Story Volumes
Jason Grinblat
Freehold Games
MOTIVATION
In April 2015, I was fortunate enough to join a live stream that featured
Nick Scratch, Austin Walker, and Cameron Kunzelman—members of a
group of streamers called Stream Friends—playing my roguelike game,
Caves of Qud.* Caves of Qud is set in a far-future, postapocalyptic Earth
populated by mutated animals, robots, and sentient plants. The Stream
Friends were cooperatively playing as a single character, and they had
just descended into the depths of the game’s first dungeon, a shale cavern
called Red Rock. As they paraded into the darkness, they stumbled on a
pack of aggressive, humanoid hyena creatures called snapjaws. Carefully,
they assessed the danger of the situation. They scanned their surround-
ings for corridors to use as choke points, boulders to hurl at the snapjaws,
and anything else that might help them survive.
At this point, Nick noticed that one of the snapjaws looked different
than the others. He moved his cursor over it and examined its description,
discovering that it was a named snapjaw faction leader (Figure 19.1). Its
name was Ugo, and it was known as the “calloused tot-eater.” Its descrip-
tion also included details about procedurally generated relationships it had
with some of the game’s other factions. It turned out that Ugo was loved
* https://www.youtube.com/watch?v=4ewMeqsjtTI
199
200 ◾ Procedural Generation in Game Design
* Bogost, Ian, Persuasive Games: The Expressive Power of Videogames (Cambridge, MA: MIT Press),
ix.
202 ◾ Procedural Generation in Game Design
voice, and mood. The expressiveness of the narrative form, then, lies in the
author’s faculty to leverage those elements in their stories. On account of
their uncontrollable nature, do emergent narratives occupy a space inac-
cessible to the author or designer who seeks to express not just something,
but something in particular?
I argue that there is room for authorial voice in procedural systems
that enable emergent narratives, although the designer’s role diverges
from that of the traditional author. In procedural design, it’s possible to
insert elements like themes and mood into both the rules of generative
systems and the handcrafted atoms that get procedurally combined. The
result is less precise than the traditional story but richer in other ways.
Whereas the author crafts a storyline that traverses narrative space, the
procedural designer crafts a story volume* that contains numerous adja-
cent stories exploring similar themes or invoking a similar mood. It’s
important to note that a story volume doesn’t enclose an arbitrary lump
of narrative space. Instead, it encloses a family of emergent stories, all
of which are begotten by a set of carefully curated system parameters
(Figure 19.2).
For example, with Caves of Qud, while we didn’t anticipate the pre-
cise story of Ugo, we did want our players to explore certain themes
present in his story. For one, we were interested in how we (as humans)
relate to our morphology. The exploration of what drives a sentient
mollusk’s beliefs taps into that theme. We were also interested in a
world where the social structures are built on the scarcity of resources
we take for granted. The streamers’ defiant act of water wasting only
resonates in such a world. By observing the inhabitants of that world’s
relationship with water, we get some insight into our own relationship
with it.
Consider the story volume constructed by another game that leans
heavily on procedurality yet manages to maintain a clear voice. Red Hook
Studios’s 2016 dungeon crawler Darkest Dungeon explores the psychologi-
cal stresses of dungeoneering. When you lead an adventuring party of
procedurally generated characters from your gothic manor into the rotted
Weald, the outcome is undetermined. The narrative that emerges is your
own. However, the game’s systems—such as the afflictions your characters
accrue from traumatic events—constrain the space of possible narratives
* Project Horseshoe Group Report, “Generative Systems, Meaningful Cores,” “Story Volumes
Rather than Storylines” section, http://www.projecthorseshoe.com/reports/featured/ph15r3.htm
Emergent Narratives and Story Volumes ◾ 203
Storyline
Story volume
FIGURE 19.2 Single storyline contrasted with several storylines that share
themes and comprise a story volume.
to those that explore the effects of trauma and evoke the mood of hope-
lessness. Even success stories are premised on overcoming your afflictions
rather than avoiding them altogether.
* Parker, Felan, “The Set-Up, the Tilt and the Aftermath: Role-Playing the Caper-Gone-Wrong Film
in Fiasco,” http://www.academia.edu/4530327/The_Set-Up_the_Tilt_and_the_Aftermath_Role-
playing_the_Caper-Gone-Wrong_Film_in_Fiasco
Emergent Narratives and Story Volumes ◾ 205
tables from the Tales from Suburbia setting. These are relationships from
the Work and Crime categories.
Work Crime
1. Business rivals in a dying industry 1. Drug manufacturer and dealer
2. Service worker and client (restaurant, bank, 2. Gambler and bookie
janitorial)
3. Professional supervisor and employee 3. Th
ieves (shoplifters, burglars, car
thieves)
4. Tradesman/homeowner (lawn care, 4. Small-time vandals, ne ’ er-do-wells
plumbing, HVAC)
5. Salesman/homeowner (siding, drive 5. Embezzler and company accountant
resurfacing)
6. P rofessional/client (pastor, doctor, lawyer, 6. Organized crime figure and wannabe
banker)
can formulate it as a broader theme. Then you can envision narratives that
explore other aspects of that theme. Finally, you can develop systems that
enable player stories within your desired story volume.
With Caves of Qud, we started with fond memories of our Gamma
World campaigns. Gamma World is a tabletop role-playing game origi-
nally published by TSR in 1978. It’s set in a pulpy, postapocalyptic North
America that’s been transformed by nuclear fallout into a bizarro ecosys-
tem of mutant flora and fauna. As teens, we at Freehold Games played
Gamma World extensively. Over the course of our gaming sessions, I role-
played as, and interacted with, teleporting tortoises, psionic pelicans, and
parasitic fungi. These experiences were absurd, hilarious, and wonderful.
They served as our primary inspiration for Caves of Qud.
Guided by our intuitions, we transposed the simplest of these expe-
riences to Caves of Qud by designing mechanics that enacted them. For
example, we wanted to let the player play a character with a carapace,
wings, telepathy, or all three. So we designed a character creation sys-
tem that includes mutations, which combine to produce morphologically
diverse characters. As we started to explore more complex social interac-
tions, and systems that could mimic them, we examined our intuitions
around what made these interactions compelling. For instance, why did I
enjoy the thought of a mollusk bristling at a challenge to its beliefs?
After much meditation, we concluded that the kernel of these interac-
tions is our relationship with our morphology. When I’m imagining how a
mollusk might respond to a social exchange, I first imagine how I might
respond as a human. Then I extrapolate by imagining how the morpho-
logical differences between mollusks and humans might inform their
interactions. I go through a process of anthropomorphizing the mollusk,
and then deanthropomorphizing it. All the while I’m implicitly examin-
ing how my own morphology informs my interactions.
This formulation helped us envision how other creatures’ morphologies
might inform their social exchanges. As we went further, it helped us start
to parameterize these exchanges and design a system to reproduce them.
We followed a similar process for the theme of scarcity. Originally, the
idea to use water as currency came to us as a play on familiar roguelike
mechanics, hunger and thirst. Then, we started to tease out the ramifica-
tions of our idea. In particular, we observed how roguelikes are some of
the few games to accurately model our utter dependency on water. We
realized our extension to the mechanics could be used to explore the social
dynamics that emerge from that dependency.
Emergent Narratives and Story Volumes ◾ 207
Ultimately, these examinations led to the design that produced the net-
work of relationships between Ugo, mollusks, antelopes, freshwater, and
the player. The narrative that unfolded from these relationships, along
with all the other narratives that unfold from its variations, comprise the
story volume articulated by our design.
Poetry Generation
Harry Tuffs
Independent
209
210 ◾ Procedural Generation in Game Design
Now, this is hugely impressive for many different reasons. This repre-
sents the struggle toward true artificial intelligence (AI). AI that can learn
and adapt, AI that actually understands grammar rather than being told
by a programmer to generate text in a way that obeys grammatical rules.
Poetry Generation ◾ 211
In almost all respects, this is much more impressive than anything I’ ve
done. One area that it doesn’ t impress, though, is the quality of the poetry.
See, my proc gen poems are bad. But not that bad.
By qualification, I am not a computer scientist. I am an English literature
graduate, giving me an appreciation for— and understanding of— poetry,
and I think this helped when it came to coding a proc gen engine that
created the stuff. I went into the process with a different perspective, I
suspect, than most computer scientists might have had. One of my biggest
priorities was to categorize my word database not only by rhyme, lexical
category, and meaning, but also by number of syllables.
See, meter is important in poetry. Especially in the kind of premodern-
ist poetry I wanted my engine to write. And while I wasn’ t quite up to the
task of categorizing each word by which syllable was stressed, I could at
the very least ensure that the number of syllables was taken into account.
And just like that, I had a way of ensuring my proc gen poems had
appropriate cadence. It made an immediate difference, and I suspect I’ d
never have thought about it if I approached this as a computer science
problem rather than a poetry problem.
So what’ s the takeaway from this? Real-world knowledge of what you’ re
trying to generate can be helpful at worst. At best, it can cause you to
totally reevaluate your approach. If you don’ t have three years of college
study on hand, a week or two of intense research will probably do the trick.
Let me take you through my process of poetry generation, top to bot-
tom, beginning with a terrible admission: I originally didn’ t intend to gen-
erate poetry at all.
Part of the premise of A House of Many Doors was that the player
character would collect memories and experiences in the course of the
story— A Moment of Melancholy, say, or a Horrifying Ordeal, or a Droll
Recollection— and spend them to write poems. It was essentially just a
way to collect experience points and level up. I created a system to generate
the poems’ titles, and then told the player, ‘ You wrote a poem!” The poetry
itself was left to the imagination.
Then, in the run-up to the ultimately successful Kickstarter, I carelessly
mentioned that the game allowed the player to write generated poetry.
This caught people’ s imaginations like wildfire. With trepidation and
excitement, I realized I’ d have to actually generate proper poems.
I’ d already been interested in doing this, but I was under the impression
that it would be a waste of time— I didn’ t realize that so many people were
actually interested in the idea.
212 ◾ Procedural Generation in Game Design
So I suppose if I had any one piece of advice it would be, embrace bad-
ness, as long as it’ s funny or interesting or both. Your proc gen system
might be very complicated and probably took a lot of work, but it will occa-
sionally produce bad results. If you can make sure those are funny– bad,
rather than frustrating– bad, you’ ve already won.
Chapter 21
Characters and
Personalities
Emily Short
Independent
INTRODUCTION
When we talk about procedurally generated character and personality,
there are several things we might mean by that:
This type of system finds the best way to perform predefined character
traits, allowing a character to demonstrate a depth of responsiveness that
we could not accomplish purely through writing. However, the characters’
essential traits have been chosen by the game writer or by the player dur-
ing a character creation process.
215
216 ◾ Procedural Generation in Game Design
This type of system can verge on story generation, since in some cases
narrative events might arise from the dynamic interaction of characters.
Highly simulation-focused systems such as The Sims can produce emer-
gent (if not always consistent or well-formed) stories when characters with
conflicting personalities are put in the same household, for instance.
In this chapter, we focus primarily on realization and creation tech-
niques. Character description has a number of applications in game
development and procedural art—in fact, it is the kind of procedural char-
acter work I have had the most call for over the course of many different
text-based game projects. However, autogenerating a character descrip-
tion often uses many of the techniques already outlined in this book. We
might, for instance, use a context-free grammar to build up a paragraph
about a character, drawing on a preexisting corpus of character traits.
Character realization and character creation, on the other hand, require
some additional techniques.
SOURCE MATERIAL
In discussing these issues, I’ll be referring to examples from several of my
past projects.
In When in Rome 2, the player has to encounter, identify, and subdue an
alien life-form. The game selects the alien type randomly at the beginning
of each play session. Different behavior rules correlate with different alien
traits, so the player can learn about the alien by watching how it interacts
with its environment. When in Rome 2 is available at http://ifdb.tads.org/.
Versu is a game platform that Richard Evans (Black & White and Sims
3) and I developed together. Versu modeled characters as agents with inde-
pendent desires; each agent would choose the action they most wanted to
perform out of a list based on the current social situation. Although this
system is no longer under production and the games written with it are
not available, it has been fairly extensively documented. More information
about Versu is available at versu.com, including papers for both lay and
academic audiences about the underlying system and the toolset that we
used to create new content.
Characters and Personalities ◾ 217
Blood & Laurels was the final game I wrote for the Versu platform, and
it was released as a stand-alone app for the iPad. (It is no longer avail-
able due to incompatibilities with recent versions of iOS.) Blood & Laurels
was set in a fictional version of ancient Rome, and was a story of intrigue
and conspiracy to overthrow the emperor. The story had a preauthored
branching narrative structure, but within each scene the interactions were
highly procedural, allowing characters to share information and flirt with
and fight, betray, and poison one another before moving on to a fresh
scenario—a sandbox embedded in a preauthored structure.
The Mary Jane of Tomorrow is a game about training a robot to exhibit
some personality traits (enthusiasm, courtesy, and knowledge of partic-
ular subject matter) and suppress others (ennui and knowledge of other
subject matter). Because the player can assemble traits in almost any com-
bination, this project relied heavily on text generation techniques to real-
ize the robot’s evolving speech patterns. The game can be found at http://
ifdb.tads.org/.
REALIZATION
For most of my projects, procedural realization has meant choosing what
to say, and then how to say it.
Choosing what to say might be dictated by the needs of the plot in
a story-based game—for instance, we might know that a particular
NPC needs to set a quest during the course of the next scene. We
might also choose dialogue in response to a question from a player,
or as part of a social interaction that we’re modeling.*
If our character doesn’t speak English or isn’t primarily engaged in
social interactions, this might translate instead into choosing what to do
and how to do it: for instance, in When in Rome 2, a meat-eating alien
from a low-gravity planet might choose to steal and eat a salami, but have
difficulty eating the salami because of its low strength.
Selecting Dialogue
Versu modeled characters who had their own unique dialogue around cer-
tain topics and ideas. Versu’s conversation rules then controlled transitions
* There’s a great deal more to say about dialogue modeling than fits into this chapter, especially as it
isn’t our primary focus here. My blog at emshort.wordpress.com contains a number of posts in the
“conversation modeling” category that deal with particular approaches.
218 ◾ Procedural Generation in Game Design
The robot crosses her legs. “If thou wishest it, yea!”
You can also transform generated text after it has been constructed. In
Versu, we had a “drunk character” filter that would create slurred speech
for a character after they’d drunk too much, by converting s- to sh- and
doing other similar conversions. Simple as it was, this effect was a dra-
matic favorite with players.
Stutters, word repetitions, sentence fragmentation, and self-interrup-
tion can also add to the performance, communicating that a character is
nervous, confused, lying, or in some other state of distress.*
CREATION
Realization and creation are not independent of one another. A system
that allows dynamic character creation often needs realization techniques
in order to present that character in an interesting way.
But dynamic character creation introduces further constraints, espe-
cially if we intend the player to interact with a character in different ways
depending on the character’s strengths. In this case, designing our vocab-
ulary of character traits becomes a subset of game design, since we are
now in essence constructing a gameplay system with character features as
elements of that system.
Such a system relies on a robust selection of combinable character traits,
skill sets, or behaviors that are
• Mechanically significant
• Easy to communicate to the player individually
• Likely to combine in interesting and evocative ways
Orthogonal
When we say that traits are orthogonal, we’re saying that they apply to dif-
ferent aspects of the character’s life and therefore can be combined freely.
A person’s height is orthogonal to their strength: a person could be tall
and strong, tall and weak, short and strong, or short and weak, without
any inherent contradiction.
On the other hand, if we chose traits such as flirtatious–standoffish
and outgoing–shy, we might find ourselves generating characters who
are both flirtatious and shy. It might be difficult to realize that character
convincingly, since the qualities describe overlapping aspects of a person’s
behavior.
If we really wanted, we could still use those traits, but include a rule
during generation that any generated character who was both flirtatious
and shy should be discarded and rerolled (or restrictively generated in the
first place). However, it’s often easier and more productive to avoid these
problems initially by rethinking the trait axes until we come up with some
that are genuinely orthogonal. For instance, instead of flirtatiousness, we
might measure a character’s interest in romance, giving us a romantic–
aromantic axis to pair with our outgoing–shy axis.
Then we might generate romantic and outgoing characters who would
behave flirtatiously, romantic and shy characters who were hesitant day-
dreamers, aromantic outgoing characters who wanted to be friends with
everyone but date no one, and aromantic shy characters who standoffishly
kept to themselves.
Each of those combinations is interesting and plausible, so we’ve maxi-
mized the descriptiveness of our procedural system.
Mechanically Significant
If a game is heavy in story or meant to be played only once, the fiction
probably carries quite a bit of weight with the player, coloring her experi-
ence of the entire game.
The more the player encounters different scenarios built with the same
ruleset, the more the fictional layer abstracts away unless it is supported by
mechanical content as well. An NPC with an aggressive facial expression
222 ◾ Procedural Generation in Game Design
Easy to Communicate
The more complicated the trait, the less likely it’s going to come across to
the player. Some traits also don’t read well in particular stories because
there are few opportunities to exercise them.
In our Versu stories, a character who was habitually unpleasant to high-
ranking men didn’t read clearly to players: he appeared in a story where
most of the other male characters were rich, and therefore he just seemed
generally surly. There weren’t enough cases where the player could see him
interact with lower-ranking men and perceive a pattern.
Meaningful in Combination
If you present a player with a character description made up of three emo-
tional styles (say, aggressive, friendly, and passive) and three hair colors
(blond, brunette, and black-haired, perhaps), you’ve created a system in
which there are 3 * 3, or 9, possible total combinations.
However, the player will experience this system more as if there were
only 3 + 3, or 6, possible combinations. Because hair color and emotional
style are largely irrelevant to one another, you don’t get a dramatically new
play experience by making a blond aggressive character as opposed to a
black-haired aggressive character. Once players have seen each emotional
Characters and Personalities ◾ 223
style and each hair color, they’ll feel, correctly, that they’ve exhausted the
system.
Making your elements mechanically significant will help with this, of
course, because then a black-haired aggressive character will (somehow)
play differently than a blond aggressive character. But it’s also productive
to think of elements that resonate with one another as symbols, so that a
pair together takes on a meaning that wasn’t inherently there in the indi-
vidual elements.
RECURRING STRATEGIES
• The content of the next beat of dialogue is chosen based on the needs
of a prewritten narrative; it’s specific to this one moment and will
never be repeated.
• The emotional content of that beat is chosen based on character rela-
tionships built up via gameplay.
• The text, voice, or graphical rendering of this dialogue and emo-
tional content is determined by the character’s traits and behavior; it
reflects some ongoing realities.
Fred: Miss Bates is a fool. She would not stop talking about turtles
at supper.
Callbacks create perceivable consequence: the player can see how ear-
lier events have affected the current state of the system.
PITFALLS
Overgeneralization
A piece of character generation or character behavior code is rarely as
completely universal as one might hope, especially across different genres
or lengths of story.
Versu was designed as a platform for many different stories, and indeed
for many different types of story. The initial suite of stories released were
a murder mystery and a ghost story set in Regency England and reflected
a Jane Austen–derived environment, with characters in some cases lifted
from her books directly and in some cases adapted from similar behavior.
The second set of stories were shorter office comedies set in the modern
day.
We anticipated (correctly) that we would need to create different behav-
ior sets to account for these different genres of story, since a character
226 ◾ Procedural Generation in Game Design
flirting in a modern office setting would likely say things that would be
considered wildly scandalous in the Regency setting.
The less obvious challenge was that we also needed our social actions
to have different impact depending on context. The office comedies were
meant to be farcical, with social situations that rapidly escalated into
more and more ridiculous problems, and gameplay took place over per-
haps half an hour. The Regency stories were meant to be more serious and
dramatic, with character relationships evolving over closer to an hour of
playtime and through many different scenes. The models we developed
for how a character might react to an insult in one were wrongly tuned
for the other.
Multiplying NPC reaction numbers by a scaling factor did not always
resolve this problem, because the Regency social practices were designed
with the idea that characters would spend some time sending social sig-
nals and then confirming that those signals were actually intended. In
the office comedy, by contrast, we needed characters to over- rather than
underinterpret what had been said to them—to start throwing pies right
away, rather than politely trying to clear up any misunderstanding.
In practice, any system of procedural character realization designed for
narrative is likely to be tightly bound to the underlying story genre and
gameplay system. A system created for one context may not easily transfer
to another.
Overrealism
For Versu, we developed a model of the social practice of conversation. It
procedurally expressed ideas about conversation flow taken from stud-
ies of real-life conversational pragmatics: rules such as “it is a violation
of social norms to fail to answer a question you’ve been asked” or “it is
socially normal to keep talking about the same topic that is already under
discussion” or “if there are several conversational partners available, peo-
ple are more likely to respond to those with whom they have the strongest
relationship.”
The latter rule turned out to be realistic but ill-suited to a game. In early
testing of the system, we found that players complained because when
they entered a room, the NPCs in that room might respond to the player
briefly but then go back to talking to one another. When we investigated,
we found that the system was behaving as specified: the player just hap-
pened to be playing a relative stranger walking in on two close friends. The
scenario of the friends acknowledging the newcomer just long enough to
Characters and Personalities ◾ 227
Untamed Simulation
In one of the Versu office comedy scenarios we worked on (but never
published), the story included a meeting where all the characters came
together to work on an advertising strategy. In testing, I was taken aback
when two of the characters, who had been flirting all game long, had sex
in the middle of the meeting, in front of their coworkers.
To some extent, this outcome was the fault of not having enough rules
in the simulation: we hadn’t added strong enough controls to indicate that
it was a severe social violation to participate in such intimate behavior in
front of other people, or in a work setting. But it was also a manifestation
of a problem we frequently faced in general, in which the simulation gen-
erated outcomes that damaged the intended behavior of the story.
For Blood & Laurels, we solved this problem by adding scene-by-scene
constraints. In each scene, we would specify which characters were allowed
to die, leave the room, or have sex—those being the extreme points that we
felt could derail the narrative.
In some games, this doesn’t matter. For sandbox games and roguelikes,
there is no pregenerated narrative to destroy; it’s to be expected if all the
dwarfs die in Dwarf Fortress, or if the Sims in Sims 3 are trapped in a
doorless bathroom and starve to death. But in a more narrative context,
we often need to make sure our simulation does not stretch our narrative
framework beyond what we’re prepared to handle.
IV
The Procedural Future
229
Chapter 22
Understanding
the Generated
Gillian Smith
Independent
231
232 ◾ Procedural Generation in Game Design
can see how well those qualities are distributed across the space. Maybe
you care about seeing a particular number of challenges in a level, or a
distribution of resources across a map, or a pleasing color scheme. There
isn’t one universal set of qualities to look for, although there are some
types of qualities you can think about for your own system. These types
of qualities are adapted from previous research.2
Example
For some concrete examples, Figure 22.1 shows three example levels from
Launchpad, zoomed all the way out so we can see the entire map at once.
Two qualities that we are interested in based on seeing these levels are
234 ◾ Procedural Generation in Game Design
Linearity and leniency are the two qualities that will be examples for
the remainder of the chapter, but there are some other example qualities
we could imagine caring about as well:
Example
Let’s look at the qualities we pulled out for Launchpad—linearity and leni-
ency—and see how they can be formalized into a metric.
∑
n
y − yexp
p =1
linearity =
n
Leniency Element
0.0 Gaps, enemies, long falls
0.25 Springs, stompers
0.75 Moving platforms
1.0 Jumps without a gap
Understanding the Generated ◾ 237
These points are chosen based on design intuition for how harm-
ful the element can be to a player. Gaps, enemies, and long falls have
low leniency because the failure state for interacting with these ele-
ments is death, and we’ve observed them to be the hardest elements
for players to interact with. Jumps with no gap underneath them,
even if technically difficult to overcome, will never be responsible for
player death—thus they are given a high leniency score.
Summing the score for each level component and dividing by the
total number of components gets us a leniency score between 0 and
1 that can be used to compare levels:
∑
n
leniency ( e )
leniency = e =1
n
Again, some information relevant to level leniency is lost in creat-
ing this metric. It does not consider the challenges that come from
ordering or frequency of level elements; for example, a player may be
more likely to come to harm if they face three difficult jumps over
gaps in quick succession, rather than three jumps over gaps that are
spread far apart from each other. The goal with this metric is to pro-
vide a rough estimate based in our design intuition and that will
later be interpreted with this caveat in mind.
takes regular actions, or slow-paced segments where the player has more
time to rest between each challenge. While the way these parameters are
set has an indirect impact on the expressive range of the overall system
and provides different generative spaces for each parameter combination,
the parameters themselves are not directly tied to the metrics of linearity
and leniency.
Histograms
A generative space has dense regions, inhabited by pieces of content that
have similar metrics scores, and sparse regions, where there are few or
even zero pieces of content that will ever be produced with those scores.
A useful way of viewing these regions of differing density is to use a heat-
map-based histogram, where the brightness of a region corresponds to its
density. Visualizing a generative space in this way lets us see at a glance
how varied content is, as well as if there are particular regions that a gener-
ator is biased toward or against. We can easily look at different histograms
side by side to visually scan for changes in the generative space based on
different input data or parameters.
However, visualizing a generative space with a 2D histogram comes
with the trade-off of only letting us view a 2D “slice” of the generative
240 ◾ Procedural Generation in Game Design
Example
Figure 22.2 shows a generative space heatmap for a particular parameter-
ization of Launchpad, produced by generating 10,000 levels and scoring
them with the leniency and linearity metrics described earlier. The linear-
ity metric has been normalized across all generated levels to be on a range
[0, 1], by first calculating all the linearity scores for all the levels, and res-
caling so that the maximum score is 1 and the minimum score is 0.
This particular parameterization generates levels that are chains of
5-second-long, medium-density level segments separated by a resting
platform. The player’s actions follow a regular, rhythmic beat. The his-
togram shows that for this configuration, the generator is biased toward
creating two types of levels, marked by bright green and red areas of the
heatmap. The two types of levels it most commonly creates are levels that
are highly nonlinear with medium leniency and levels that are highly lin-
ear with medium leniency. This heatmap also lets us see that with this
5 regular medium
0.75
Leniency
0.5
0.25
FIGURE 22.3 Set of expressive range histograms for Launchpad, each represent-
ing a different configuration of input parameters.
242 ◾ Procedural Generation in Game Design
kind of biasing wouldn’t be possible to see just from a quick visual inspec-
tion of single pieces of content produced by the system, because roughly
the same areas of the expressive range are still covered—just with a very
different frequency in certain regions than before. So hitting the “gener-
ate” button and playing a few levels would show that the same kinds of lev-
els are being created with these parameters, and we would actually need
to play and take note of thousands of levels before we could start to get the
sense that the system is biased.
Distance-Based Clustering
An alternative for visualizing high-dimensional spaces is to determine clus-
ters, or families, of content. While this method takes more implementation
effort up front, it can be a helpful way to visualize over time how different
clusters are changing in size and character. Clusters can show emergent
patterns or families of generated content. For example, Figure 22.4 shows
a cluster map for the Launchpad level generator. Each colored rectangle
CONCLUSION
In this chapter, we’ve seen a systematic method for understanding a gen-
erator’s capabilities in terms of its generative space. Instead of looking at
individual pieces of content by hand, we now have a method for looking
holistically at all pieces of content generated by the system to understand
the full range of what can be created, as well as for diagnosing any unin-
tentional biases in a generative space. While implementing and maintain-
ing metrics and expressive range visualization is additional development
overhead, this method for “understanding the generated” can help with
both the design and development of generative systems. For designers,
having a sense of the range of content a user might see—or not see—can
guide the creation of both the generative system and the larger game con-
text that uses it. For developers, visualizing a generative space and how it
changes during the course of development can help them track down bugs
(e.g., if a small code change suddenly radically alters the generative space)
and understand the emergent ramifications of seemingly small develop-
ment decisions.
REFERENCES
1. Smith, Gillian, Jim Whitehead, Michael Mateas, Mike Treanor, Jameka
March, and Mee Cha. 2011. Launchpad: A rhythm-based level generator for
2D platformers. IEEE Transactions on Computational Intelligence in AI and
Games 3 (1).
244 ◾ Procedural Generation in Game Design
245
246 ◾ Procedural Generation in Game Design
• Allow for shaping the room geometry by both addition and subtrac-
tion, based on chance or a conditional being fulfilled. Allow for add-
ing doors or passageways, taking out chunks in the wall. Based on
the previous nested chances, the same room could look very differ-
ent if you saw it multiple times in a single play.
• Allow for easy further scripting, for things like dialogue triggers,
doors being closed or opened by crossing an area, ambush encoun-
ters, cut scenes, and more.
• Be easy to learn for new people. Using layered image files and a
parser for them as a level editing tool means that it’ s easier to visu-
alize and make the modular content. This is again mostly for team
coordination. If we wanted to get a new designer to help make mod-
ular rooms, it would be preferable if they didn’ t have to spend large
chunks of time deciphering complex text files.
We ended up using the usual rooms in Wayward Souls , with the pro-
cedural bits mostly being short hallways. For the current game we’ re
working on, these modular rooms are being attached to and placed in
more purely code-generated areas. This approach is the best of both
worlds. You get freeform generated spaces to explore and maneuver in,
punctuated by a large amount of varied handcrafted modular geometry
(Figure 23.1).
In our previous games, we used a web-based tile level editor, but over
time, we found it was too cumbersome for more complex cases. We had
way too many things in Wayward Souls . Tile types, decorations, monsters,
and other entities would be too much to track. The main tool we ended up
using was Photoshop/GIMP.
SYSTEM OVERVIEW
Every pixel in a map image represented a tile. Every color represented a
different kind of tile. A separate palette file served to associate the colors
to specific tiles.
Data from a layered PSD file would be run through a web-based parser
(Figure 23.2). This processed all the graphic layers and converted them to
tile data, which was stored in an SQLite database on our server. This would
then be assessable in the test build of the game, instantly, for all developers
and testers.
The level image files were layered so that different layers could be flipped
on and off at will. The layer names served as scripting to determine the
conditionals as to when and how often that layer’ s pixels could be drawn
onto the map by the game. The layer name scripting had many different
uses, many of which were compatible to be applied to the same layer:
• Set pixels in that layer to be an entity rather than a tile. Set the pixel
as a specific monster, a breakable piece of furniture, a torch, a door,
or a large art asset.
• Set what percentage chance the layer has to spawn.
• Set a name for a group of layers from which only one layer is chosen.
Give the same name to two other layers; the game picks one out of
the three. Have different group names so one layer from each set gets
chosen.
• Set layers as associated with another layer, so it only has a chance to
spawn if the previous layer does, for example, 50% chance to spawn
a torch on a wall that only has a 50% chance to spawn.
• Set pixels drawn on the layer as invisible triggers for the player to
step on, calling a function also set by the layer scripting. Go past this
line, and it will close all doors in the room, and then spawn in waves
of enemies that need to be defeated to open the doors.
EXAMPLE ROOM
Geometry : This is the base room. Every other layer would be drawn
1.
over this layer, should it appear. The geometry is very simple: it’ s
a big square (Figure 23.3). The two light center pixels are possible
spawns of items the player can use. In the corners are spawn points
for possible larger, breakable decorative objects. The darker pixels are
possible spawn points for things that the player can walk over, and
can also be broken in the heat of combat.
Entry : This layer was designed to only appear if a hallway connected
2.
to the room from the east. Not only did it draw a door on the base of
the room, but it also drew spawn points for decorations (Figure 23.4).
FIGURE 23.4 A new door added to the room, which only appears if the room is
connected from the east.
Part of the wall was indented further out, and another part of the
wall came in to create a shallow alcove in the top right of the room.
3a. Random elements : Now the game chose from a pick-from-one group.
There were three groups to pick from, and the behavior of this one
was to potentially add pillars of various sizes to the room. It picked
that group, and then picked three possible large pillars to spawn
(Figure 23.5).
3b. Random elements : Here’ s the same room, but with a different pick-
from-one group selected (Figure 23.6). Also, new decorations were
randomly picked to be spawned in the room. Also, a new possible
door spawn point was added to the west, above the previous one.
FIGURE 23.7 The room with monsters added, in two different conditions.
This could also be applied to other ways to add details and points of inter-
est to code-generated areas in a game. Anything your game supports could
be put into this system. It also makes collaboration easier, improving your
game’ s quality overall. With designers being able to easily add things, you
could have a very large variety of interesting set pieces in an otherwise
code-generated level.
Chapter 24
251
252 ◾ Procedural Generation in Game Design
{ pipeGap=7.2,
Select game pipeWidth=3.3,
parameters . . . }
Explore
new game Generate level
parameters
Repeat N times
Optimize for
specific difficulty Simulate level
or
Sample for Record score
visualization in histogram
or After N times
Output d=.372
Repeat as needed difficulty “medium”
FIGURE 24.1 Diagram of how to explore game variants. We explore game space by
simulating game variants and estimating their difficulty using survival analysis.
Then, we look at the data we collected and decide if the game is too easy or
too hard. If it’s too easy, we can make some adjustments to make it harder
and try again. If we feel it’s too hard, we can make it easier. We don’t have
to guess which knobs we should adjust to make it easier or harder, as we
can just try different settings and let the computer quickly figure out the
effect of the changes.
If this overview leaves you with some questions, there are also
deeper details in our publicly available research papers hosted at game.
engineering.nyu.edu/exploring-game-space.
j: jump velocity
bw bh: bird size
pg: pipe gap
v: bird velocity
g: gravity
FIGURE 24.2 Gameplay of Flappy Bird. In Flappy Bird, the player must navi-
gate the bird through a series of pipes without crashing. We modify the labeled
parameters to generate unique game variants.
Automated Game Tuning ◾ 255
FIGURE 24.3 Two different generated levels given different parameter sets. More
simulations complete the second version, so we can see that it’s easier for the AI
to play. The horizontal lines indicate the target location for the AI to flap.
a bit above the top of the lower pipe, and each time the bird drops below
that target height (the horizontal lines in Figure 24.3) the AI immediately
executes a flap. Whatever AI is used, it should play with very good perfor-
mance on solvable levels, and should mainly only fail on impossible levels,
such as a level with a tiny pipe gap where the bird cannot fit through. You
might want to use an A* or Monte Carlo tree search–based AI for your
game, or write your own simple one, like we did.
We then modify the perfect AI to perform less well by modeling the
main components of human motor skill that impact difficulty in these
types of action games: precision and actions per second.* Adjusting these
values lets us model different player types, since novices react slower and
are less precise than experts. Our model relies on a predetermined value,
which we determined using a user study to figure out how precisely play-
ers can tap an onscreen button, and we can reuse those numbers for other
games too.
When a player plans to press a button at an exact time, they execute this
action with some imprecision. We model this error as a normal distribu-
tion (aka a bell curve), as shown in Figure 24.4. The width of the normal
distribution is proportional to a player’s imprecision. Imprecision is a trait
that all humans have, but it is also related to the time a subject has to react
to an event, called the speed–accuracy trade-off: the less time they have to
react, the less accurately they will respond.
For simplification, our player model assumes precision is an indepen-
dent variable and not dependent on bird speed. We measured precision
as an error, with standard deviation ranging between σp = 35.9 ms and
σp = 61.1 ms, and use this range for game space exploration. Unity, C#,
and JavaScript don’t have built-in functions for generating normally dis-
tributed random numbers (also called Gaussian distributed random num-
bers), but you can search the web for some libraries or functions that will
do this.
Humans can only perform a limited number of accurate button presses
per second. In our user study, we measured an average 7.7 actions per
second, or about once every 130 ms. We also limit our AI to this same
number of actions per second so that it can’t play unrealistically well. We
simplify our model by keeping this constant, although a more complex
* We also modeled reaction time to an unexpected event, but that didn’t matter as much, so I left it
out of this chapter. You can refer to our research papers if you want to implement it for your game.
Automated Game Tuning ◾ 257
Expert
Novice
FIGURE 24.4 Timing curve graph. Expert players are more precise than novice
players.
model would account for fatigue, since players can’t keep actions per sec-
ond constant for long periods.
This is how we actually coded this approach for use in our system. At
each frame of the simulation, we predict the next time t in the future
when the bird will drop below this ideal flapping location—the ideal
player would flap at exactly this time t. We predict this by just running
a copy of the game as fast as possible without drawing to the screen, and
figuring out how many game loop ticks until the bird will drop below
that line; this takes less than a millisecond to calculate. We then make
the player less precise by adjusting this time t by adding a random nor-
mal distribution with about a 30 ms standard deviation, as shown in
Figure 24.5. By reducing or increasing the width of the bell curve for our
precision model, the AI plays more or less well. To keep the AI from flap-
ping faster than a human could tap, t is limited by the number of actions
per second. If t happens too soon after making another flap, we force t to
be at least 130 ms.
Keep in mind that it’s important that the AIs we are using here don’t
learn or improve. If you make a change and the scores increase, you just
made the game easier for the AIs. You can’t necessarily do that with
human testers, because they are also learning and improving each time
they play the game. So if a human plays two variants and performs better
on the second, it might be that they are just getting more skillful at playing
the game. But AIs that don’t learn are reliable in the sense that they can be
258 ◾ Procedural Generation in Game Design
Early Dead
On time Alive
Late Dead
t-ϵ t t+ϵ
reused repeatedly with the same skill settings to determine how difficulty
changes as you modify game parameters.
For each simulation, we get a score s, equal to the number of pipes that
the AI passes before crashing, and we record each score s for analyzing in
the next step. If the AI reaches a goal score of 20, we store a score of 20
and terminate the run so we do not get stuck simulating easy games where
the AI will never hit a pipe. Although Flappy Bird can theoretically go on
forever, human players tire or get distracted and will eventually make a
terminal mistake, but the AI can truly play forever unless we enforce a
maximum score.
The generate and simulate steps are run repeatedly until we have
enough data samples to adequately analyze. The more times you run the
simulation, the more accurate an answer you’ll get, but it will take longer.
We found doing about 10,000 simulations was plenty, and this only took
about a second for the computer because Flappy Bird is a simple game and
we had our own version that had no graphics to draw. If your game is more
complicated, it will take longer, but you can speed things up by turning
off any graphics rendering and just run the game simulation without any-
thing being drawn. You can also adjust the goal score when you will stop
the simulation—lower goal scores will run faster. The important thing is
to try some different values and see what works best for your game.
of data structure that keeps track of how many times a value (or a range of
values) has appeared.
To make a histogram, first you keep track of all the final scores in an
array. When you want to figure out the probability of getting each score,
you just go through the array and count how many times each score
appears, and then divide by the total number of scores in the array. If
you’ve got many scores, then you can use bins to keep track of scores in a
range. For example, you might count scores of 49, 10, and 22 as being in
the same bin for scores between 0 and 50.
Figure 24.6 shows some examples of how you can use histograms to
compare different game variants. In Figure 24.6a, we see a pretty hard
game, such as a difficult variant of Flappy Bird. In this game, the most
likely score is 0, the second most likely is 1, and so forth. This means low
scores are very likely and high scores are very unlikely. In Figure 24.6b, we
see the same histogram as in Figure 24.6a, but now compared with a sec-
ond histogram in gray. The gray histogram represents an easier game. We
know this because the probability of getting a low score has gone down,
and the probability of getting a higher score has gone up.
In Figure 24.6c, we see another shape for the histogram, which is rep-
resentative of games that start out easy and then get harder as you score
Probability
0.3 0.3
0.2 0.2
0.1 0.1
0.0 0.0
0 2 4 6 8 10 0 2 4 6 8 10
(a) Score (b) Score
Probability
0.12 0.20
0.10 0.15
0.08
0.06 0.10
0.04 0.05
0.02
0.00 0.00
0 2 4 6 8 10 0 2 4 6 8 10
(c) Score (d) Score
higher. That gives a low probability of achieving a low score, since the
game starts out easy; a high probability of achieving a medium-valued
score; and a low probability of achieving a high-valued score. In Figure
24.6d, we can see that the game data shown in gray is a harder game than
the game data shown in black. We know this because it is more likely to
get a low score for the gray data than the black data.
Using this histogram, we can use some relatively simple statistics to
determine how difficult the game is. In our research, we used a technique
called survival analysis, which figures out how the score frequencies
change as a player continues in the game. In practice, a simpler method
of just taking the median or mean of the histogram would also be reason-
able and is easier to code. If the median score decreases, then the game is
harder; if the median score increases, then the game is easier.
A couple of situations might come up:
0.75
Difficulty
0.50
0.25
0.00
20 25 30
Pipe gap
FIGURE 24.7 Line graph of difficulty. Increasing pipe gap decreases difficulty.
Each line shows a different setting for player precision. Lighter lines plot lower
precision, modeling poorer performance, and so are more difficult for the player
model.
262 ◾ Procedural Generation in Game Design
Impossible games
g : gravitational constant 1000
(crash into floor)
es
gam
750 Harder
Medium
ya ble
Easier
Pla
500
Impossible games
Original
(crash into ceiling)
250 Flappy Bird
FIGURE 24.8 Graph of parameters that make playable games. Jump velocity and
gravity are related and should be adjusted together.
gets more difficult—faster reaction times are required as the bird is mov-
ing rapidly up and down. Lower values of gravity and jump velocity give
the player more time to react and are easier to play.
By exploring different parameters, the system can find different versions
of the game for you. If you want an easier or harder version, the system can
try a bunch of different parameters to find one easier or harder. Using an
optimizer, you can even have the computer find an exact target difficulty.
We’ve also used this system for exploratory computational creativity,
to find game variants that are as different as possible from existing ver-
sions that have already been explored (Figure 24.9). Unplayable variants
are invalidated, and the system only returns the games that can actually
be played by humans. The designer then can examine the unique games to
find inspiration and new ideas.
Using our system, we have generated interesting and surprising vari-
ants, such as “Frisbee Bird,” which has a very different game feel. This
variant, shown in Figure 24.10, was created by allowing the optimizer to
vary every design parameter, including speed, player width, player height,
jump velocity, gravity, pipe distance, pipe width, and pipe randomness.
The optimizer returned a game with a wide flat bird that moves horizon-
tally very fast but slow vertically and requires short bursts of rapid presses,
followed by a long pause while the bird floats in the air. This unexpected
variant, discovered by our system while using the optimization algorithm,
still relies on the mechanics and rules of the original, but is a significantly
different play experience.
Automated Game Tuning ◾ 263
3000
Harder
Target difficulty
2000
Gravity
1000
Easier
0
0 100 200 300 400
Jump velocity
FIGURE 24.9 Scatterplot graph of game variants. We can search different game
variants for a target difficulty. Each point indicates a variant tested to find the
target; ´ indicates impossible games; dot size indicates closeness to the target.
FIGURE 24.10 New Flappy Bird variant. “Frisbee Bird” was unexpectedly cre-
ated by our system, an example of computational creativity. We show six simu-
lated paths with jump points indicated by triangles. The player is very wide and
thin, with weak jump velocity and gravity that gives the feeling of floating.
CONCLUSION
I hope this chapter has convinced you that using some simple player mod-
eling and human-like AI players can help you understand the difficulty of
your own game. These techniques can be implemented without any com-
plex libraries or significant experience with statistics. You can analyze the
data using a separate program, perhaps Excel, or doing some simple data
processing in Python (which is how I do it).
The ultimate goal here is not to replace human testers, but to enhance
your game testing with AIs that can reliably play at different skill levels.
264 ◾ Procedural Generation in Game Design
They won’t find the same kinds of issues that human players can find, and
there is no guarantee that AIs will agree with humans about how difficult
the game is. The important part is that you can get a sense of whether your
changes are making the game easier or harder, and that can really speed
up development time when you are tweaking your game parameters.
ACKNOWLEDGMENTS
Special thanks to Andy Nealen, Tanya X. Short, Tarn Adams, Julian
Togelius, Frank Lantz, Dan Gopstein, Steve Swink, Ron Carmel, Mark
Nelson, the NYU Game Center, NYU Game Innovation Lab, and various
fellow researchers, game designers, and reviewers that have influenced this
work and for their helpful suggestions and comments. Finally, I would like
to especially thank Dong Nguyen for making Flappy Bird and for inspir-
ing this research. Images appear here with his permission.
Chapter 25
Generating Rules
Dr. Michael Cook
Independent
265
266 ◾ Procedural Generation in Game Design
too much might completely change that. It’ s also very hard to know how
to even represent things like a game’ s rules— rules don’ t fit into neat tem-
plates like dungeons or quests. They often are unique bits of executable
code that we wrote once to express a certain idea. They’ re also very hard
to test. If a dungeon has a dead end or is a bit boring, it’ s not the end of the
world, and we can try and detect these issues and work around them. If
a ruleset is broken, though, it might make your game unplayable. As any
game designer knows, it can be really hard to see that a game is broken,
even if you’ re a human being.
In this section, we walk through a few basic things you can try out if
you want to play with rule generation in your games. The exciting thing
about this area is that because it’ s relatively unexplored, it’ s a wide-open
playground for new ideas and discoveries— so don’ t be afraid to go off on
your own and try out your own designs, too.
fixed! For the effects of colliding, we can think about the general events
we want to happen in our game. Can the player gain score? Can the player
die? Can the player get power-ups? All these bits of code become separate
effects.
All our generator has to do then is pick two object types and one effect,
and it’ s got a little collision rule generated. It’ s our job to convert it into
real game code, though, but usually it’ s just a case of having lots of code to
check each building block and point it toward some code you’ ve already
written.
This format of rule generation is really easy to expand by adding in
more options for the generator. We could add extra elements to our rules,
for example. Maybe instead of collisions only having one effect, they have
two effects, one for each of the objects involved in the collision. Now you
can do things like have one object kill another object and survive (like
PAC-MAN ghosts), or have effects only target one object. We can also add
more types of rules, like rules for when things leave the screen or rules for
when a button is pressed on the keyboard. To get more variety out of this
technique, it’ s important to add things that you might think are useless or
not interesting. Don’ t just add obvious game objects to the collision object
list. Add in the floor. Add in background objects. Add the user interface
in— anything you can think of. If you only put predictable things into a
system like this, you’ re likely to only get predictable things out the other
end.
or delete files from the player’ s computer (at least, you probably didn’ t).
You decided that some things would be better for games than others, and
that’ s an example of you helping the system design games.
But we can do better— we can write heuristics , little rules of thumb or
guidelines for the system to follow that will help it create better rulesets.
These are things that we believe to be true about our rules regardless of
anything else going on in the game. Some of these guidelines we know to
be universally true, no matter what rules come up. For example, if we’ re
making a Candy Crush – style game, there has to be at least one rule that
destroys blocks. Our game is about destroying blocks, so if there aren’ t
any rules that destroy blocks, we can safely say that the ruleset isn’ t very
good, and our generator can scrap it and go back to the drawing board.
These heuristics might seem very simple, but they can be very power-
ful. Even a basic one like “ Can the player do anything?” can cut out a huge
percentage of bad ruleset designs. Sometimes we can’ t know enough up
front, though. Much like designing a game for yourself, you can’ t tell what
a game will be like just by looking at all the rules written down— that’ s
why people playtest their games or give them to others to play. If we could
get our generator to playtest the rulesets it makes, we could maybe take the
data from those playtests and write even better heuristics.
Right now, there’ s a lot of research funding being put into a field called
general game playing (GGP). The aim is to develop artificial intelligence
(AI) capable of playing any game, even one it’ s never seen before, by rap-
idly learning rules and strategies. One of the uses for AI like this is to
automatically evaluate games and investigate any problems the designs
might have. It’ s a long road toward that goal, though, and you might not
feel like developing cutting-edge AI systems just to play with rule genera-
tion. Instead of using the cleverest AI possible to play our games and test
them, what we can do instead is use the stupidest approach possible, and
get our games played entirely randomly by a system that has no idea what
it’ s doing.
This might sound like a waste of time, but even a random agent tells
you something about how the game works. Suppose we run a random AI
player on our generated ruleset 10 times. Our agent can record things as it
plays— we can get it to record if it completes the game, perhaps, or when-
ever it gains score or touches an object. At the end, we have 10 samples of
how the game looks. Suppose we’ re making a game like PAC-MAN . If all
10 of our random players never died, or if they all completed the level in
under 3 seconds, there might be something wrong with our ruleset. We
Generating Rules ◾ 269
can write more heuristics, more guidelines, that use this new data to think
about what it says about our game. Our random player isn’ t clever, but it
represents a kind of worst-case scenario for gameplay, which is a step up
from just looking at the rules without any kind of gameplay.
Algorithms and
Approaches
Brian Bucklew
Freehold Games
RANDOM NUMBERS
271
272 ◾ Procedural Generation in Game Design
generators. The “pseudo” in this case refers to the fact that these typically
do not return a truly random set of numbers, but only a series of numbers
that appear to be random.
Pseudorandom number generators start from an initial seed value and
then perform a mathematical operation on that seed value that produces
the next value in the random series and increments the seed in some way
so the following call will produce a different (but statistically random)
value. Whenever you give a pseudorandom number generator a particular
starting seed, it will always produce the same sequence of random values.
For example, a particular pseudorandom number generator that is
given the initial seed 5 and gives you 3, 23, 195, and 1 when asked for the
first four random numbers in its series will always return 3, 23, 195, and 1
as the first four numbers when its initial seed is 5. The same is true of all
remaining numbers in the series it generates for the seed value 5.
If that particular pseudorandom number generator is given a seed value
different than 5, the series of numbers it would return when asked would
likewise be different. For example, if you gave that exact same pseudoran-
dom number generator an initial seed of 6 (instead of 5), it might give you
55,129, 4, 51, and 0 (instead of 3, 23, 195, and 1) when asked for the first
four numbers of its sequence.
Another helpful use of the fact that the hash values are statistically
random is that you can use as much, or as little, of the hash function’s
return value as you want since a smaller chunk of bits pulled from a per-
fectly random number are themselves perfectly random. This means if a
hash function generates 128 bits of data, and you want a 32-bit integer as
a pseudorandom number generator seed, you can simply grab the first 32
bits of the value the hash function returns to use as your random number
generator seed.
There are many common hash functions, including MD5, the SHA
family, xxHash, and Murmer. Some, like SHA, produce more statistically
random output, which is useful for cryptography, and some, like xxHash,
produce less statistically random output but with much higher perfor-
mance. Games typically do not need the statistical strength that the slower
hash families provide, so a typical choice for game projects is a fast hash
function like MD5 or xxHash.
Examples of hash functions in use are
Rolling Dice
It is common to talk about random numbers in terms of rolling a number
of dice. These dice are not restricted to the familiar six-sided cube dice.
“1d6” means the result of one six-sided die, which you might find in any
common board game, resulting in a value between 1 and 6. “1d8” means
Algorithms and Approaches ◾ 275
the result of one eight-sided die. “3d6” means the result of three six-sided
dice added together, resulting in a value from 3 to 18.
Some pseudorandom number generators will only generate an integer
between 0 and the largest representable integer. Since you often want to
generate smaller ranges of values to simulate things like die rolls, it’s very
often useful to generate a range of integers between two given numbers
(say, 1–6 for a d6).
Although many random number generator libraries give you the abil-
ity to specify a minimum and a maximum value for the next number you
generate, if they don’t, you can write your own:
RangeInclusive(max,min)
{
return ((rng.next() % (max-min+1)) + min);
}
FloatingPointRange(max,min)
{
Return ((rng.next() / MAX_INTEGER) * (max-min)) +
min;
}
Normal Distributions
It’s often useful to generate a normal (“bell curve” or Gaussian) distribution
of numbers instead of a linear one. Adding several dice of the same type
276 ◾ Procedural Generation in Game Design
A normal distribution is described with two terms, the mean and the
standard deviation. The mean is the value at the “peak” of the bell curve.
The standard deviation describes how “wide” the curve is. In a truly nor-
mal distribution, about 68.27% of the values fall within one multiple of
the standard deviation and about 99.73% of the values fall within three
multiples of the standard deviation.
Here’s a basic implementation that will generate a normal distribution
of random numbers with a given mean and standard deviation (std).
GaussianRandomNumber(mean,std)
{
A = rng.nextfloat(); // from 0 to 1
B = rng.nextfloat(); // from 0 to 1
C = SquareRoot(-2 * Log(A)) * Sin(2 * PI * B);
return mean + (std * C);
}
Other, faster methods are known, like the Ziggurat algorithm, if higher
performance is required.
Examples of normal distribution use are
Weighted Distributions
Another very useful tool is the weighted distribution. For example, you
might want a common result 9 out of 10 times, and a rare result on the
10th. You can think of this weighted distribution like a bag with nine balls
marked “common” and one ball marked “rare” in a bag. The weight for
each item in a weighted distribution describes the number of balls in the
bag with that item’s result.
278 ◾ Procedural Generation in Game Design
Result Weight
Common 9
Rare 1
WeightedResult(mean,std)
{
Roll = rng.RangeInclusive(1,sumOfAllWeights);
WeightAccumulator = 0;
foreach( currentItem in Items )
{
WeightAccumulator →
WeightAccumulator+currentItem.Weight;
if( WeightAccumulator >= Roll ) return
currentItem.Result;
}
}
A useful variant of this algorithm simulates not returning the ball back
to bag after drawing it, preventing it from being drawn again in future
picks. In order to accomplish this, you simply reduce the weight of the
selected item by one after it is selected.
WeightedResultRemovePickedItem(mean,std)
{
Roll = rng.RangeInclusive(1,sumOfAllWeights);
WeightAccumulator = 0;
foreach( currentItem in Items )
{
WeightAccumulator →
WeightAccumulator+currentItem.Weight;
if( WeightAccumulator >= Roll )
{
result = currentItem;
currentItem.Weight--;
return result;
}
}
}
Algorithms and Approaches ◾ 279
HEIGHTMAPS
The shape of a lake, the layout of continents, clumps of weeds, and a topo-
graphical map are just a few of the many kinds of map features that are
common in procedurally generated environments. All of them require the
generation of a two-dimensional (2D) grid of values that vary with some
degree of smoothness from cell to cell. These types of 2D grids of smoothly
varying values are called heightmaps (Figure 26.3).
FIGURE 26.3 Example heightmap created with Perlin noise layering. Whiter
pixels have higher values.
1 3 1
3 5 3
1 3 1
Midpoint Displacement
Square-diamond midpoint displacement generates a heightmap by start-
ing with random values for the corners of a grid. The center grid square
of that square (M in the grid below) is then given a value of the aver-
age of those corner values plus or minus a small random variance. Then
the middle grid of each edge (E in the grid below) is given a value of the
average of the two corners and midpoint plus or minus a small random
variance. This creates four subsquares, and the process continues on these
subsquares iteratively until the whole grid is populated. Typically, during
Algorithms and Approaches ◾ 281
each iterative step the amount of variance applied to each new point is
reduced exponentially.
The corners are given a random value:
2 E 8
E M E
10 E 5
The center cell is given a value equal to the average of the corners plus
or minus a small random amount:
2 8
10 5
The midpoint of each edge is given a value equal to the average of the
corners and midpoint plus or minus a small random amount:
2 8 8
5 9 6
10 4 5
FIGURE 26.4 Example of a single 2D layer of Perlin noise; whiter pixels have
higher values.
Algorithms and Approaches ◾ 283
called OpenSimplex was developed in 2014 that shares many of the posi-
tive qualities of simplex noise without patent encumbrance.
SEQUENCE GENERATION
Input string: A
Rule 1. (A→AB)
Rule 2. (B→A)
Initial value: A
(Iteration 1: A becomes AB via rule 1.)
AB
(Iteration 2: A becomes AB via rule 1; B becomes A via rule 2.)
ABA
(Iteration 3: A becomes AB via rule 1; B becomes A via rule 2; A becomes
AB via rule 1.)
ABAAB
(Etc.)
ABAABABA
ABAABABAABAAB
Markov Chains
Markov chains produce a sequence by utilizing a directed graph of nodes.
Each edge has a percentage weight assigned to it. The result of a Markov
chain is generated by starting a particular node. That node’s value becomes
the first value of the sequence.
The next node is chosen randomly from among all the edges directed
away from the current node. That next node’s value is used as the second
value of the sequence. Then the third node is chosen from the edges lead-
ing away from that node, and the chain continues in that way until the
sequence reaches some termination condition. That condition might be,
for example, a particular length of sequence or a node that’s flagged as an
end node.
In order to generate a sequence of weather for a week, we can use the
simple Markov chain shown in Figure 26.6.
Let’s say we randomly choose to begin on the rainy node. So the first
day in our week is rainy.
The two edges leading away from rainy are a 25% chance of the rainy
node and a 75% chance of the sunny node. Let’s say we choose randomly
between those two options and choose to move to the sunny node, so the
second day of our week is sunny.
Algorithms and Approaches ◾ 285
25%
Rainy
75%
25%
Sunny
75%
FIGURE 26.6 Simple Markov chain sequence generating a sequence of rainy and
sunny days.
The two edges leading away from sunny are rainy with a 25% chance
and sunny with a 75% chance. We choose one of those two edges at random
to generate the weather for our third day. We continue moving between
these two nodes until we’ve generated seven days of weather, and then our
sequence is complete!
If you have an existing sequence of data, you can construct a Markov chain
from it in order to create more data that shares similar stochastic properties.
Let’s say we have a sequence of the letters ABCD. Each of these letters
becomes one of the nodes in our chain.
ABCAABACBACDB
We then look at each letter and determine the number of times each
node is followed by each of the others.
20% 40%
A 75% B
25%
40% 33.3% 100%
33.3%
C D
33.3%
The example chains in Figure 26.7 are “order 1,” which means each sin-
gle element is used as a node in the chain. The order number is the number
of elements per node. An order 2 Markov chain would operate on pairs
of elements instead of single elements. So in Figure 26.7, our nodes in a
second-order chain would be AB, BC, CA, and so forth.
Examples of Markov chains in use are
FILLING SPACE
Random Walks
Random walks are produced by starting at a given point and then tak-
ing steps in random directions. Many natural processes, like molecular
motion, can be described by random walks, and they can be useful for
generating all sorts of naturalistic paths and features.
FIGURE 26.9 Two steps in a 2D random walk, first east then north.
Cellular Automata
Cellular automata are a broad category of systems that operate on a graph
of discrete cells. They define a set of states for each cell and a set of rules
that describe how the state of each cell changes based on the state of adja-
cent cells. These rules are typically (but not always) applied to every cell
in a stepwise fashion, with each cell computing the next state based on its
Algorithms and Approaches ◾ 289
current neighborhood, and then all the cells changing in one step to the
next state defined by the rules.
A common and familiar cellular automaton is Conway’s Game of Life,
which is played out on a regular 2D grid with two states for each cell, alive
and dead. The rules for each time step are described in terms of the cur-
rent state of the cell and how many of the four cardinal direction neigh-
bors are in the alive state.
Rules for Conway’s Game of Life
These rules, when applied repeatedly, tend to smooth out the stand-
alone walls and concentrate the denser clusters, resulting in a cave-like
appearance.
Figure 26.11 shows a cave map being iteratively generated by cellular
automata in Caves of Qud. The field is generated with a two-wide border,
and then each interior cell has a 55% chance to contain a wall. The cave
rules described above are then executed twice on that random field, result-
ing in a cave-like set of chambers.
Examples of cellular automata in use are
Settling
A settling algorithm takes a set of assorted shapes that are generated
with some overlap. Those shapes are given simple physics rigid body
representations, and a physics simulation that causes the overlapping
shapes to “push” away from each other is run until they no longer over-
lap. This provides a straightforward means to arrange a large set of pieces
with widely varying sizes and shapes into a set that is connected but not
overlapping.
Examples of settling in use are
Wang Tiles
Wang tiles are a mechanism for defining a set of tiles and the way they
each connect to each other side by side as they are laid down across a
plane. They can be imagined as squares with a color for each side. The tiles
are placed so that the color of each side of each newly placed tile matches
the color of the sides of each other tile that it touches.
In games, these colors often signify a particular kind of connection
between tiles. For example, “blue” tile sides might be those with a door
along that side, and “green” tile sides those with a hallway, so that when
tiles are aligned based on the color, they produce a properly connected set
of areas.
One particularly interesting subset of Wang tiles for procedural games
is those carefully select sets of tiles that can tile a plane without creating
repeating patterns (aperiodic tilings) (Figure 26.12). Not all possible com-
binations of tile number and side color will produce aperiodic tiling, but
many such sets have been discovered. These aperiodic sets can be as small
as 11 tiles (Figure 26.13) (http://arxiv.org/abs/1506.06492).
292 ◾ Procedural Generation in Game Design
FIGURE 26.12 A 13-tile Wang tile set that will not repeat its pattern across a
plane.
FIGURE 26.13 Example of nine tiles from the set tiled properly in a 3 × 3 block.
PARTITIONING SPACE
It’s often the case in generating procedural content that you have an open,
undifferentiated space that you need to partition into a set of regions.
This might be, for example, dividing a landmass or star map into political
areas, dividing that country into states, or taking a space and generating a
set of units for pathfinding or decision making.
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
FIGURE 26.15 Step 2: A portal is placed at random somewhere along the wall.
The newly created subregions are marked 1 and 2.
3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4
4 4 4 4 4 4
1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4
1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4
1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4
1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
FIGURE 26.16 Step 3: Each subregion is now split at random and a portal
placed along the wall, typically restricted to a place where it won’t create a T or
X junction.
7 7 7 7 7 3 3 3 3 3 4 4 4 8 8
7 7 7 7 7 3 3 3 3 3 4 4 4 8 8
7 7 7 7 7 3 3 3 3 3 4 4 4 8 8
7 7 7 7 7 3 3 3 3 3 4 4 4 8 8
4 4 4 8 8
5 5 5 1 1 1 1 1 1 1 4 4 4 8 8
5 5 5 1 1 1 1 1 1 1 4 4 4 8 8
5 5 5 1 1 1 1 1 1 1 4 4 4 8 8
5 5 5 1 1 1 1 1 1 1 4 4 4 8 8
5 5 5 1 1 1 1 1 1 1
5 5 5 1 1 1 1 1 1 1 2 2 6 6 6
5 5 5 1 1 1 1 1 1 1 2 2 6 6 6
5 5 5 1 1 1 1 1 1 1 2 2 6 6 6
5 5 5 1 1 1 1 1 1 1 2 2 6 6 6
5 5 5 1 1 1 1 1 1 1 2 2 6 6 6
FIGURE 26.17 Step 4: After a third round of partition, the area starts to resemble
a set of connected rooms.
Algorithms and Approaches ◾ 295
FIGURE 26.18 Set of ruins in Caves of Qud, generated primarily via binary space
partition.
Voronoi Diagrams
A Voronoi diagram is constructed by taking a set of seed points on a
plane and partitioning that plane so that the region containing each seed
contains only the points on the plane closest to the seed (Figure 26.19).
A variety of distance metrics can be used.
Since Voronoi diagrams work to partition a continuous plane of space,
they are most useful for partitioning continuous, uninterrupted spaces,
like continents; however, there are variations of Voronoi diagrams that
take obstacles into account.
Examples of Voronoi diagrams in use are
Dijkstra Maps
Dijkstra maps partition space in a manner similar to that of Voronoi dia-
grams; however, they work on a discrete graph instead of a continuous
plane. In our examples, we use a square grid, which is a graph where each
node is connected to its four or eight neighbors, but the algorithm sup-
ports any graph.
A Dijkstra map is generated by taking a set of seed points and calculat-
ing the distance from each node in the graph to the closest seed point. This
is typically done via a breadth-first search from each seed point. During
the search, each node is typically marked with the seed point it is closest
to and the distance to that seed, forming a region surrounding each seed.
Dijkstra maps have wide applicability to terrain analysis and pathfind-
ing. Caves of Qud utilizes Dijkstra maps with randomly placed seeds in
order to generate a uniform population of uneven spaces (Figure 26.20).
Random seeds are placed on the map until the largest region reaches a
target size. The resulting Dijkstra map regions are each populated with a
similar number of objects, providing an even distribution of map contents
irrespective of the map’s layout or amount of open space.
Algorithms and Approaches ◾ 297
Tree Mapping
Tree mapping is a technique used to take a list of values and then parti-
tion a rectangular 2D field into a set of rectangular division (Figure 26.21).
Each of the rectangular divisions has an area proportional to one of the
target values in the list. There are several algorithms for producing tree
maps that trade off a consistent visual aspect ratio of the divisions with
the stability of the map layout when changes are introduced to the list of
values.
Examples of tree maps in use are
• Creating a basic city street grid for a set of buildings and city blocks
of known size
• Creating the rooms of a side-view building given a list of room sizes
298 ◾ Procedural Generation in Game Design
So now we know the size of each star and we can pick the display color
based on the temperature.
When the player clicks on a star, we can seed the random number
generator with a value like (starseed+hash(“starname”)) and then use a
Markov chain of syllables we’ve created from a catalog of star names to
generate a random name for the star. This is fast enough that we can just
do it in real time whenever we mouse over a star.
When the player zooms into the system, we can continue to add detail.
A weighted table to tell us if it has one or more companion stars, perhaps a
weighted table for the number of inner rocky planets, and then one for the
outer gas planets. Then we can select a seed for each planet, perhaps a hash
of the system name and orbital (“Algotauri 4”) and generate the overall
visual aspects of the planet for display.
When the player zooms in to a planet, we can generate more detail, for
example, using Perlin noise layers to generate the topography, L-systems
to generate the layouts of the cities of the creatures that occupy it, binary
partition to create the rooms in an individual building, a weighted table
to tell you what the contents of a particular room are, and a Markov chain
to tell you what is on the notepad that is in a desk in that particular room.
Procedural generation opens endless doors in endless hallways to end-
less untracked worlds.
Happy hiking!
Chapter 27
Meaning
Dr. Mark R. Johnson
Independent
301
302 ◾ Procedural Generation in Game Design
MEANING IN GAMES
What is meaning? On the most highly abstracted level, meaning in games
(and any work of art, fiction, or media) is created through forging connec-
tions between elements of that experience. A phrase has meaning when
the reader remembers another character uttering the same phrase before;
a company name has meaning when the viewer recalls seeing their logo
on a van earlier in the film; the visual design of a boss or enemy has mean-
ing when it is similar or comparable to others seen previously. When this
is not the case, in-media information serves only a role as background
or scene setting. Background is an important role, without doubt, but
does not produce elements that are truly meaningful to the experience
of the work, because they could be exchanged for other comparable ele-
ments (switching the logo on one van seen for a moment with a different
logo) and the salient elements of the media artifact would go unchanged,
because that element has nothing to do with the message being conveyed.
Meaning is fundamentally created through the connection of otherwise
disparate elements.
A common source of meaning in games is through the distribution of
information about what now tends to be called “lore.” This is often textual
in-game content that is optional to the player’s success over the mechan-
ical challenges of the game, but serves instead to flesh out the fictional
world in which the action takes place.
In procedural games, this takes many forms. A game like Tales of
Maj’Eyal adheres to a model of scattered lore that adds up to a large body
of data about a story, and a story can appear at first to be one thing and
then morph into something else as more information is acquired. Dungeon
Crawl Stone Soup instead draws on classical mythology for its lore, posi-
tioning its monsters within various mythologies, ranging from ancient
Greek to Egyptian and Jewish to Hindu, in many cases giving hints about
how these monsters behave based on these classical origins. The Binding
Meaning ◾ 303
make the quite repetitive core gameplay of the games themselves feel sur-
prisingly paltry in contrast to the rich world hinted at, but never directly
experienced. Lore in this case does bring meaning and background to the
game world, but it also undermines that same meaning by highlighting
the artificiality of the game world and the limited numbers of interac-
tions that can take place in the game’s possibility space, and reminding the
player that what they read is pure fiction, one step disconnected from the
possible interactions in the world they’re currently exploring.
Meaning is therefore about striking a balance between bringing together
all the elements within a particular fictional world to come to resemble
more than the sum of their parts and avoiding bringing to the player’s
attention what isn’t there—a meaningful game world must be somehow
hermetically sealed, giving out just the right amount of information. This
is a difficult balance that few games get exactly right, showing that mean-
ing is a complex question that extends into all elements of game design,
from the mechanical to the thematic and the narratological to the experi-
ential, as embodied by each individual player.
MEANINGLESSNESS IN GAMES
Meaningless occurrences in games take many forms, but here I’d like
to focus on particular kinds in specifically procedural generation—the
unnecessary item and the mostly uninteresting map. In games with very
explicit and linear differences in the quality of items, where there are rarely
interesting decisions to be made about using Weapon A over Weapon B
in Context C, for example, then acquiring Weapon A after Weapon B,
if Weapon B is undeniably stronger and there are no contexts in which
Weapon A will actually be better, makes the acquisition of Weapon A an
effectively meaningless moment, and turns Weapon A into a meaningless
item (from a gameplay mechanics perspective).
This meaninglessness is not inherent to the item, but rather an emer-
gent property from the elements of the context in which it was acquired—
Weapon A might have been deeply meaningful if found at the start of the
game and in the process giving the player’s character a significant boost,
and it was an item the player had become used to using for hours and hours
of subsequent gameplay, but at the end of the game, it becomes merely an
unnecessary addition. This is perhaps most marked in the Angband family
of roguelikes—in many of these games, late-game item decisions become
almost impossible without actively ignoring or removing from consider-
ation a large volume of the acquired loot.
Meaning ◾ 305
A related but distinct system to the one outlined above is the creation
of handmade optional content segments worked into otherwise proce-
dural areas. In addition to Chapter 7, you may also take, for example, the
“vaults” in Dungeon Crawl Stone Soup parlance. In Dungeon Crawl Stone
Soup, the vaults range from unique and distinctive gameplay challenges
to areas designed to give the player a little bit of information about the
game’s fictional universe. One might encounter a shrine to a particularly
bloodthirsty god with the remains of sacrifices strewn around it, or a vault
designed to tell a particular story, such as the tragic and rather amusing
tale of the deceased bakers, which I encourage all readers to go and seek
out. Handmade segments of gameplay such as vaults are typically nones-
sential, will appear on some playthroughs of a procedural content gen-
eration game but not others, are generally used to develop thematic or
“background” elements rather than the immediate narrative of a game,
and are placed on top of the game’s procedural generation systems as an
optional and unpredictable extra.
There are also situations in which players will assign their own meaning
to particular events. In Chapter 13, we explored briefly how players could
come to regard actions of particular artificial intelligence (AI) actors in
some roguelikes as being far more “intelligent” than they actually were.
Similarly, in a playthrough of a roguelike where the player character has
always been weak and been unlucky with procedurally generated items,
for example, the sudden discovery of a tremendously powerful weapon
or highly effective piece of armor will immediately transform the player’s
experience of that playthrough and come to be seen as a moment of great
meaning in that playthrough.
This is very visible when we look at the player-created practice of writ-
ing “Yet Another Stupid Death” or “Yet Another Victory Post” forum
posts that offer handwritten narratives of a character’s eventual success
or death within a permadeath roguelike. These player stories assign their
own meaning to particular stages of the game that had no designer inten-
tion and were entirely or predominantly procedural, but which came to
strongly affect the outcome of the game, such as gaining a powerful item,
defeating a particular enemy, or making a critical error.
Meaning is also often assigned in procedural games through encour-
aging players to take greater risks to achieve greater rewards, and these
playthroughs—when successful—are moments for great celebration and
pride. In Dungeon Crawl Stone Soup, for example, the player must acquire
three “runes” to win, but there are 15 available runes in total, and a victory
308 ◾ Procedural Generation in Game Design
with more runes is seen as more prestigious than one with fewer. NetHack,
similarly, has a range of “conducts”—such as the vegetarian conduct that
forbids the player character from consuming meat. Practices of this sort
are another way to give even greater weight and meaning to a player’s deci-
sions and to the eventual outcome of victory, if achieved, and to mark out
one playthrough of a roguelike from all the other playthroughs that sur-
round it.
Such practices are rare in player cultures surrounding non procedurally
generated games (such as speed running and high score tables), whereas it
is hard to find a roguelike without a wealth of player-created (or designer-
created) extra challenges that give players the feeling that a particular
playthrough in a particular style was especially meaningful, and represen-
tative of their skill, knowledge, and abilities in the game in question. These
many forms of meaning combine to offer players a range of “anchors” for
their experiences in these randomized worlds, providing ample sources of
meaning and consequence for their activities, and undermining the popu-
lar idea that randomness is necessarily devoid of any deeper importance.
the world, and also to produce extra variety as the players move around
the planet. Games that generate huge procedural worlds often struggle
with making different areas of the world feel different, and although ter-
rain (temperate, desert, tundra, etc.) goes a long way, URR deploys this
procedural flora and fauna as an additional detail that varies widely as the
player moves around the world.
The crucial point, however, is that animals and plants (just one example
of a vast number of elements I could have selected for this discussion) do
not only serve this purpose—they also create and influence meaning in a
range of other in-game elements. The covers of books might depict local
animals. Healers in the area will speak of local plants and their regen-
erative properties. Those encountered in distant lands might speak of the
national animals or plants of their homeland.
Perhaps one of the most striking and effective examples of this system
thus far implemented is the generation and reproduction of shared aesthet-
ics distinct to each (secular) culture and each religion (with some bleeding
of visual styles and practices between the two). Everything within a par-
ticular culture is designed to share commonalities of shape and color—
everything from chairs to shop signs and city layouts to ornate floor tilings
in one civilization will share a particular geometric form (squares, octa-
gons, circles, etc.), while everything in a religion, from religious vestments
to altars and prayer mats to holy books, shares particular sets of colors
reproduced in different but clearly connected ways across each item.
The point of these systems is to show the player the meaning in the
generated world, instead of telling them about it. When viewing a sigil
embossed on a shield, for example, the game never says, “This is the coat
of arms of House B.” Instead, the world is simply presented to the player,
along with the understanding that nothing in the game world is discon-
nected, and that meaning is there to be found if the player is able to iden-
tify it, and the player is left to do the rest.
If these elements were generated merely as background informa-
tion, however, their meaning would be limited, no matter how detailed.
However, as well as the technical and artistic interest and challenge of
developing a system of this sort, it is also arguably the most fundamental
gameplay system in the game. The player’s central objective is the uncov-
ering of a global conspiracy, clues to which are distributed through the
world’s cultures: a hint might be found in the corner of a painting, or a
particular line in a particular novel, or hidden in a chest in the quarters of
310 ◾ Procedural Generation in Game Design
All games of course have some kind of learning process, but the per-
madeath of roguelike games is what encourages many players away from
learning “the hard way” that Medusa will immediately petrify you if she is
given line of sight, or that certain enemies in Dungeon Crawl Stone Soup
can banish you to the abyss far before you are ready, and thereby away
from the intended gradual discovery metagame and toward immediate
knowledge.
There are two different kinds of knowledge at play here—NetHack
knowledge applies to every playthrough, since Medusa will always be a
threat, and URR knowledge, which only applies to a single playthrough,
aside from the meta-knowledge of how knowledge in URR is acquired. In
URR, players can only take to the next playthrough the understanding
that they are meant to acquire knowledge, not what that knowledge is,
and thus a wiki or guide becomes almost irrelevant and the centrality of
“discovering meaning as a game mechanic” is maintained even with the
presence of spoilers.
CONCLUSION
An opposition between meaning and randomness need not always be pres-
ent. Unchanging meaning can be easily added into procedural games
through the use of static markers around which the rest of the world is
generated, while “changing” meaning that is unique to every playthrough
can be implemented through utilizing deeply interconnected procedural
generation systems that do nothing in isolation, and always draw upon
each other when producing their outcomes.
In turn, this final point allows for the development of intriguing and
highly unusual game mechanics, focused on discovery, understanding,
and problem solving. They are similar to those used in many puzzle and
adventure games, but replayable across however many playthroughs are
desired. Even the creation of riddles or puzzles whose widely distributed
yet closely related elements, ideally, should be indistinguishable from
something that was handmade. Meaning can therefore be a central part
of procedural generation, but it requires designers to move beyond the
mental model of the “random” procedural generation that distributes
affordances with little thought to their connections, and instead embrace
the ability to distribute moments of meaning within the randomness, and
from these build a story, a background, or entire gameplay mechanics.
Index
313
314 ◾ Index
U Z
Ultima Ratio Regum (URR), 103, 138, 140, Zelda, 92, 93
141, 302, 308–311 Zubmariner, 27