Flyweights, Prototypes, and Evil Space Monsters:
What Conventional Software Design Can Learn From Game Design, and Vice Versa.
Blair Schneider McKayBlair Schneider McKayClareos, Inc.Clareos, Inc.http://home.comcast.net/~blairschneidermckay/http://home.comcast.net/~blairschneidermckay/
email: [email protected]
Presented to Upsilon Pi Epsilon Presented to Upsilon Pi Epsilon
at The University of Michigan – Dearbornat The University of Michigan – Dearborn
Monday, April 4Monday, April 4thth, 2005, 2005
Scott DemingScott DemingClareos, Inc.Clareos, Inc.http://www.makefile.com/http://www.makefile.com/
email: [email protected]
You are in a maze of twisty passages, all alike.
_>
Blair Schneider McKay / Scott DemingGame Design – Slide 3
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
q & aq & a
Blair Schneider McKay / Scott DemingGame Design – Slide 4
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
q & aq & a
Blair Schneider McKay / Scott DemingGame Design – Slide 5
Apr. 4, 2005
Games come in all sorts of flavors.They can be…
relaxingrelaxing frustratingfrustratingeducationaleducational mind-rottingmind-rottingviolentviolent non-violentnon-violentgraphicalgraphical text-basedtext-basednoisynoisy peacefulpeacefulsophisticatedsophisticated simplesimpleupliftinguplifting offensiveoffensivenaughtynaughty niceniceinstructiveinstructive escapistescapistfreefree cheapcheap expensiveexpensive
. . . and, one hopes, “fun”!. . . and, one hopes, “fun”!
Blair Schneider McKay / Scott DemingGame Design – Slide 6
Apr. 4, 2005
For example…
Blair Schneider McKay / Scott DemingGame Design – Slide 7
Apr. 4, 2005
Developing games can be…
relaxingrelaxing frustratingfrustratingeducationaleducational mind-rottingmind-rottingviolentviolent non-violentnon-violentgraphicalgraphical text-basedtext-basednoisynoisy peacefulpeacefulsophisticatedsophisticated simplesimpleupliftinguplifting offensiveoffensivenaughtynaughty niceniceinstructiveinstructive escapistescapistlucrative?
. . . and, one hopes, “fun”!. . . and, one hopes, “fun”!
Blair Schneider McKay / Scott DemingGame Design – Slide 8
Apr. 4, 2005
Getting a job programming games?
““Finally, you’ll need a game demo. . . . It doesn’t Finally, you’ll need a game demo. . . . It doesn’t matter if the game is a pixelated mess; just show matter if the game is a pixelated mess; just show that you made the effort and you have the that you made the effort and you have the passion.”passion.”
Melanie Cambron, Game Recruiting Goddesshttp://www.melaniecambron.com/In “Introduction to Computer Game Programming
with DirectX 8.0” by Ian Parberry, Ph.D.
Read Melanie’s interviews at: http://www.gignews.com/goddess/
Blair Schneider McKay / Scott DemingGame Design – Slide 9
Apr. 4, 2005
What’s so great about game programming?
Developing games can give you a chance to Developing games can give you a chance to enjoyenjoy the practice of your craft. the practice of your craft.
““Conventional” programming often doesn’t.Conventional” programming often doesn’t.
Blair Schneider McKay / Scott DemingGame Design – Slide 10
Apr. 4, 2005
What’s so great about game programming?
When developing a game you are in complete control When developing a game you are in complete control of the design and implementation.* of the design and implementation.*
The The choiceschoices are yours. are yours.
In “conventional” programming, you are generally In “conventional” programming, you are generally constrained by the (often hideous) choices of others.constrained by the (often hideous) choices of others.
(* Presuming you don’t work for an evil game company.)(* Presuming you don’t work for an evil game company.)
Blair Schneider McKay / Scott DemingGame Design – Slide 11
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
q & aq & a
Blair Schneider McKay / Scott DemingGame Design – Slide 12
Apr. 4, 2005
What’s in a game? user-interfaceuser-interface
data validation, parsing, and processingdata validation, parsing, and processing
flow-controlflow-control state machinesstate machines error handlingerror handling
interface to third-party APIsinterface to third-party APIs graphics, sounds, file-system, networkgraphics, sounds, file-system, network mouse, keyboard, joystick, light-sabermouse, keyboard, joystick, light-saber
artificial intelligenceartificial intelligence simulations of consciousnesssimulations of consciousness simulations of environmental conditionssimulations of environmental conditions
Blair Schneider McKay / Scott DemingGame Design – Slide 13
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
q & aq & a
Blair Schneider McKay / Scott DemingGame Design – Slide 14
Apr. 4, 2005
Design Parallels: using low-level APIs
Interfacing with low-level APIs generally means using Interfacing with low-level APIs generally means using
C-style function calls, e.g. C-style function calls, e.g. int retcode=fn(param1, param2..);int retcode=fn(param1, param2..);
GameGame ConventionalConventionalDirectXDirectX ODBC, E/SQLODBC, E/SQLDirect3DDirect3D TCP/IP - SocketsTCP/IP - SocketsOpenGLOpenGL PLC / SensorPLC / SensorMIDIMIDI BothBoth
File SystemFile SystemNetwork I/ONetwork I/OMath LibrariesMath Libraries
Blair Schneider McKay / Scott DemingGame Design – Slide 15
Apr. 4, 2005
Design Parallels: modular architectures 1
OSI 7-Layer Networking Model:OSI 7-Layer Networking Model:
Layer 1: PHYSICAL
Layer 2: DATA-LINK
Layer 3: NETWORK
Layer 4: TRANSPORT
Layer 5: SESSION
Layer 6: PRESENTATION
Layer 7: APPLICATION telnet, ftp, pop3, smtp
conversions, encrypt/decrypt, parts of odbc / html
cookies, “shopping basket” techniques, etc.
TCP, data reliability (re-transmission, etc.)
IP
ppp, slip, hdlc, token-ring, MAC addressing
NIC cards, RS-232, electrical characteristics
Blair Schneider McKay / Scott DemingGame Design – Slide 16
Apr. 4, 2005
Design Parallels: modular architectures 2
A decoupled model for a biological simulation:A decoupled model for a biological simulation:
Mod: RENDERING
Mod: POPULATION MECHANICS
Mod: MOVEMENT
Mod: EVENTS
Mod: ARTIFICIAL INTELLIGENCE
Mod: USER INTERFACE instrumentation to let the user manipulate environment params
maybe we have “smart” fish, that detect and try to avoid sharks
the environment itself might occasionally throw your sprites a curve (perhaps, a fishing net).
wriggle, swim, or fly…
automatic management of birth/death, production/consumption
interface to low-level graphics APIs
Mod: SERIALIZATION saving the simulation’s current state to disk, for later recall
Blair Schneider McKay / Scott DemingGame Design – Slide 17
Apr. 4, 2005
Design Parallels: Code clarity
An unfortunate truth in conventional programming: An unfortunate truth in conventional programming: many developers feel no responsibility to write many developers feel no responsibility to write clear, understandable, clear, understandable, maintainablemaintainable code. code.
There are many reasons for this—There are many reasons for this—all of them badall of them bad..
In game programming, where (often) you’re the In game programming, where (often) you’re the only coder, you may be tempted to do the same…only coder, you may be tempted to do the same…
But remember: But remember: youyou are also the poor soul who has are also the poor soul who has to maintain the program!to maintain the program!
Blair Schneider McKay / Scott DemingGame Design – Slide 18
Apr. 4, 2005
Design Parallels: Robustness
My chief complaint with the computer games I’ve played My chief complaint with the computer games I’ve played over the years has been unexplained crashes and program over the years has been unexplained crashes and program errors.errors.
My chief complaint with the My chief complaint with the conventionalconventional computer computer software I’ve used over the years has been unexplained software I’ve used over the years has been unexplained crashes and program errors.crashes and program errors.
E.g., no one will thank you if your RainForest Quest game E.g., no one will thank you if your RainForest Quest game diesdies just as Amazon Sally finds the Magic Ruby and is a just as Amazon Sally finds the Magic Ruby and is a the verge of rescuing her Prince Charming. the verge of rescuing her Prince Charming.
Blair Schneider McKay / Scott DemingGame Design – Slide 19
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
Blair Schneider McKay / Scott DemingGame Design – Slide 20
Apr. 4, 2005
Design Choices: how much to optimize?
Commonly Held BeliefCommonly Held Belief::
The best way to achieve speed is by using low-level languages, like C, or The best way to achieve speed is by using low-level languages, like C, or even Assembly-Language.even Assembly-Language.
Real-world findingsReal-world findings::
Modern compilers can sometimes beat hand-crafted assembler code.Modern compilers can sometimes beat hand-crafted assembler code.
Developers are Developers are terribleterrible at guessing where code needs optimization. at guessing where code needs optimization.
Optimize late in the game, ideally only after Optimize late in the game, ideally only after profilingprofiling..
But, don’t pessimize prematurely!But, don’t pessimize prematurely!
Blair Schneider McKay / Scott DemingGame Design – Slide 21
Apr. 4, 2005
Design Choices: using low-level APIs
class class ScreenManager {ScreenManager {public:public:
ScreenManager( ScreenManager( /*construction params*//*construction params*/ ) { ) {m_hwnd = m_hwnd = CreateDefaultWindowCreateDefaultWindow( ( /* … */ /* … */ ););if (!m_hwnd) {if (!m_hwnd) {/*throw exception*//*throw exception*/ } }
}}~ScreenManager( ) {~ScreenManager( ) {
DestroyWindowDestroyWindow(m_hwnd); (m_hwnd); }}// . . . // . . .
};};
If you are in C++, you can use the “Resource Acquisition Is If you are in C++, you can use the “Resource Acquisition Is Initialization” (RAII) idiom:Initialization” (RAII) idiom:
void void goToHelpScreen( ){goToHelpScreen( ){// Obtain a DirectX screen handle// Obtain a DirectX screen handleScreenManager screen( FULL_SCRN, PRIMARY);ScreenManager screen( FULL_SCRN, PRIMARY);// Use the “screen” object.// Use the “screen” object.drawHelpGraphicsOn( screen.getHandle( ) );drawHelpGraphicsOn( screen.getHandle( ) );// etc…// etc…
} } // On exit, the “screen” object is automatically // On exit, the “screen” object is automatically destroyed, and the underlying resource handle is freed.destroyed, and the underlying resource handle is freed.
Blair Schneider McKay / Scott DemingGame Design – Slide 22
Apr. 4, 2005
Design Choices: PolymorphismPolymorphism is about handling different objects as if they were all the same. (Access through a common interface.)
Consider example of an “Ocean” simulation or screen-saver:
A Movement sub-system iterates over a collection of “Sprites”, telling each sprite when to move. (Each sprite knows how to move itself: wriggle, swim, fly, etc.) Even though the collection holds different types of objects, they can all be handled as if they were the same type.
Sprite
SharkGuppy Kelp Crab
Blair Schneider McKay / Scott DemingGame Design – Slide 23
Apr. 4, 2005
Design Choices: the Prototype pattern
class Guppy : public Sprite {public: virtual Sprite* clone() const; // return copy of myself virtual bool handles( SpriteType request ); // ...}
It’s related to the Factory Method, but even the factory doesn’t need to know exactly how to build each product sub-class.
The sub-class itself takes on that responsibility.
SpriteFactory::SpriteList my_prototypes_;
Sprite* SpriteFactory::getSprite( SpriteType request ) { for (/* ... each prototype in my list . . .*/) { if (prototype->handles(request)) return prototype->clone(); } // return default type or throw exception.}
Blair Schneider McKay / Scott DemingGame Design – Slide 24
Apr. 4, 2005
Design Choices: the Observer patternHere is a simplified Observer pattern:
Observer Subject
attach() detach() notify()
update()
ConcreteObserver
update()
(Diagram based on p. 294 in “Design Patterns”, by Gamma et al. Addison Wesley, 1995.)
The goal of this pattern is for each (concrete) observer object to receive updates on state changes that occur within the subject object – without the subject object knowing any details about each observer. This is the ultimate in “need-to-know” programming.
Blair Schneider McKay / Scott DemingGame Design – Slide 25
Apr. 4, 2005
Observer Subject
attach() detach() notify()
update()
ConcreteObserver
update()
Setup:
1. Observer calls attach() on Subject, passing “this” pointer.
2. Client of Subject (or Subject itself) calls notify() at appropriate time.
3. In notify(), Subject iterates through list of observers and calls update() on each one, possibly passing state-data.
Use:
Tear-down:
4. Observer calls detach().
Observer Pattern – Event Sequence
Blair Schneider McKay / Scott DemingGame Design – Slide 26
Apr. 4, 2005
Ocean.cpp
#include “Observer.h”;
LevelReader::attach(Observer* obs) { observers_.push_back(obs);}
LevelReader::detach(Observer* obs) { observers_.erase(obs);}
LevelReader::notify( ) { for ( /* each fish in my list */ ) fish->update(this);}
Fish.cpp
#include “Ocean.h”;
// . . .Fish::update(Ocean* ocean) { if (ocean->getWaterTemp() > s_max) { die(); }}
Observer Pattern – Sample Implementation
Ocean.h
#include <list>class Fish; // forward decl.class Ocean{public: Ocean(); virtual ~Ocean(); void attach( Fish* fish ); void detach( Fish* fish ); void notify( ); double getWaterTemp() const; // . . .public: std::list<Fish*> fishes_;}
Fish.h
class Ocean; // forward decl.class Fish{public: Fish(); virtual ~Fish(); void update(Ocean* ocean); // . . .}
Blair Schneider McKay / Scott DemingGame Design – Slide 27
Apr. 4, 2005
Game Uses of Observer Pattern
Collecting statistics and tracking history.Collecting statistics and tracking history. Feed data to the brain engine for AI.Feed data to the brain engine for AI. Feed data to the rendering engine to add residual Feed data to the rendering engine to add residual
effects (disrupting smoke, fog.)effects (disrupting smoke, fog.) Collect/transmit data in multi-player game. Collect/transmit data in multi-player game.
Observer feeds separate thread to avoid Observer feeds separate thread to avoid sputtering/lag.sputtering/lag.
Input observer: capture user input before sending Input observer: capture user input before sending to game engine. Pause or mute the audio without to game engine. Pause or mute the audio without the game itself having to worry about it.the game itself having to worry about it.
Blair Schneider McKay / Scott DemingGame Design – Slide 28
Apr. 4, 2005
The Decorator Pattern
Attach additional responsibilities to an object dynamically.Attach additional responsibilities to an object dynamically. Alternative to sub-classing. Alternative to sub-classing. How it works:How it works:
The Decorator has the same interface as the type being The Decorator has the same interface as the type being decorated and contains an object of that type.decorated and contains an object of that type.
It accepts requests on behalf of the decorated object. It It accepts requests on behalf of the decorated object. It forwards them, as needed, to the object, and adds its forwards them, as needed, to the object, and adds its own flourish.own flourish.
Key pointKey point: adding additional responsibilities to a specific : adding additional responsibilities to a specific objectobject, not to a whole , not to a whole classclass..
http://www.dofactory.com/Patterns/PatternDecorator.aspxhttp://www.dofactory.com/Patterns/PatternDecorator.aspx
Blair Schneider McKay / Scott DemingGame Design – Slide 29
Apr. 4, 2005
Game Uses of the Decorator Pattern Alter the visual environment.Alter the visual environment.
Weather conditions (fog, rain, etc.)Weather conditions (fog, rain, etc.) Night-vision gogglesNight-vision goggles Line of sightLine of sight
Alter the musical environment.Alter the musical environment. Increase tempo during exciting moments without changing the Increase tempo during exciting moments without changing the
musical scoremusical score Add special effects based on power-ups.Add special effects based on power-ups.
Make player sprite transparent to indicate invisibilityMake player sprite transparent to indicate invisibility Lighten an entire area to indicate an illumination spellLighten an entire area to indicate an illumination spell
Alter physical featuresAlter physical features Change the magnetic properties of certain objects and watch Change the magnetic properties of certain objects and watch
the effect on their forces of attractionthe effect on their forces of attraction Add density to an object in water and watch it sink like a rockAdd density to an object in water and watch it sink like a rock
Blair Schneider McKay / Scott DemingGame Design – Slide 30
Apr. 4, 2005
Demos of Observer and Decorator
DemoObs.exe – dynamic registrationDemoObs.exe – dynamic registration
Ex2.exe – transparency and searchlightEx2.exe – transparency and searchlight
Ex5.exe – line-of-sight decorationEx5.exe – line-of-sight decoration
Blair Schneider McKay / Scott DemingGame Design – Slide 31
Apr. 4, 2005
Other Patterns FlyweightFlyweight
Support a large number of find-grained objects through sharing.Support a large number of find-grained objects through sharing. Use in games to efficiently model vast numbers of sprites that Use in games to efficiently model vast numbers of sprites that
have only minor differences in state. (Make the state extrinsic have only minor differences in state. (Make the state extrinsic to the object.)to the object.)
FaçadeFaçade Encapsulate all calls to a third-party API or low-level library Encapsulate all calls to a third-party API or low-level library
within one class or set of classes. within one class or set of classes. For example, put a façade between your game logic and For example, put a façade between your game logic and
DirectX, OpenGL, etc.DirectX, OpenGL, etc.
MementoMemento Serialize an object’s state for later recall. Serialize an object’s state for later recall. Use for “save game” and for multi-player network traffic.Use for “save game” and for multi-player network traffic.
Blair Schneider McKay / Scott DemingGame Design – Slide 32
Apr. 4, 2005
Agenda
playing at work—working at playplaying at work—working at play
what’s in a game?what’s in a game?
design parallelsdesign parallels
design choicesdesign choices
resources for the game developerresources for the game developer
q & aq & a
Blair Schneider McKay / Scott DemingGame Design – Slide 33
Apr. 4, 2005
Resources: Clanlib
http://www.clanlib.org/http://www.clanlib.org/
Cross-platform C++ framework / Game SDKCross-platform C++ framework / Game SDK
Released under LGPL 2.1. Released under LGPL 2.1. Next release under Mozilla Public License 1.1.Next release under Mozilla Public License 1.1.
DEMO: cl_test.exeDEMO: cl_test.exe
Blair Schneider McKay / Scott DemingGame Design – Slide 34
Apr. 4, 2005
Resources: DirectX
http://www.microsoft.com/windows/directx/
SDK “enables high-performance graphics and SDK “enables high-performance graphics and sound, without requiring hardware-specific code”.sound, without requiring hardware-specific code”.
Faster, richer than Windows GDI.Faster, richer than Windows GDI.
Drawback: Windows-specific.Drawback: Windows-specific.
Blair Schneider McKay / Scott DemingGame Design – Slide 35
Apr. 4, 2005
Resources: OpenGL http://www.opengl.org/
High-performance. (Quake III, Doom III, etc.)High-performance. (Quake III, Doom III, etc.)
Portable.Portable.
Blair Schneider McKay / Scott DemingGame Design – Slide 36
Apr. 4, 2005
Final Thoughts: What matters to us.
ScottScott::
Focus on Focus on GAME PLAYGAME PLAY, please! , please! (Too many bloody shooters out there.)(Too many bloody shooters out there.)
BlairBlair::
There is There is alwaysalways a need for new and better educational games. a need for new and better educational games. The standards: logic puzzles, math, spelling, …The standards: logic puzzles, math, spelling, …
Simulation technology can now teach all sorts of things:Simulation technology can now teach all sorts of things: cooperation / conflict resolutioncooperation / conflict resolution problem solvingproblem solving the scientific methodthe scientific method
Apr. 4, 2005
Blair Schneider McKayBlair Schneider McKay
http://home.comcast.net/~blairschneidermckay/http://home.comcast.net/~blairschneidermckay/
email: [email protected]
Scott DemingScott Deming
http://www.makefile.com/http://www.makefile.com/
email: [email protected]
Also, please feel free to email questions:Also, please feel free to email questions:
Questions, Answers, and Cowardly Evasions.