What are some programming design patterns that are useful in game development?

jcurrie33
  • What are some programming design patterns that are useful in game development? jcurrie33

    I have a few books on Design Patterns, and have read some articles, but cannot intuitively figure out which programming design patterns would be useful in game development.

    For example, I have a book called ActionScript 3 with Design Patterns that details several design patterns such as Model View Controller, Singleton, Factory, Command, etc.

    As someone new to this, I cannot figure out which of these would be useful, or in fact if any of these are the design patterns I should be learning and trying to use. Perhaps there are other, more game-programming-specific design patterns that I am not even aware of?

    If you have experience using a certain design pattern in game development, I'd love to hear it. Reasoning as to why it was used, code samples, or online resources would all be very helpful as well if you have them. I am at the moment most interested in ActionScript 3 and C++ implementations, but could definitely benefit from experience and examples from any language.

    Thanks!

  • All of them. Except Singleton. [/flippancy]

  • Now for a less flippant response, with some suggestions. Don't take these as implementation recommendations, more as examples of possible use.

    • Builder: set up component-based entity one component at a time, based on data
    • Factory Method: create NPCs or GUI widgets based on a string read from a file
    • Prototype: store one generic 'Elf' character with initial properties and create Elf instances by cloning it.
    • Singleton: this space deliberately left blank.
    • Adapter: incorporate an optional 3rd party library by wrapping it in a layer that looks like your existing code. Very useful with DLLs.
    • Composite: make a scene graph of renderable objects, or make a GUI out of a tree of Widgets
    • Facade: simplify complex 3rd party libraries by providing a simpler interface to make your life easier later.
    • Flyweight: store the shared aspects of an NPC (eg. models, textures, animations) separately from the individual aspects (eg. position, health) in a mostly transparent way
    • Proxy: Create small classes on a client that represent larger, more complex classes on a server, and forward requests via the network.
    • Chain of responsibility: handle input as a chain of handlers, eg. global keys (eg. for screen shots), then the GUI (eg. in case a text box is focused or a menu is up), then the game (eg. for moving a character)
    • Command: encapsulate game functionality as commands which can be typed into a console, stored and replayed, or even scripted to help test the game
    • Mediator: implement game entities as a small mediator class that operates on different components (eg. reading from the health component in order to pass the data to the AI component)
    • Observer: have the renderable representation of a character listen to events from the logical representation, in order to change the visual presentation when necessary without the game logic needing to know anything about rendering code
    • State: store NPC AI as one of several states, eg. Attacking, Wandering, Fleeing. Each can have its own update() method and whatever other data it needs (eg. storing which character it is attacking or fleeing from, the area in which it is wandering, etc.)
    • Strategy: switch between different heuristics for your A* search, depending on what sort of terrain you're in, or perhaps even to use the same A* framework to do both pathfinding and more generic planning
    • Template method: set up a generic 'combat' routine, with various hook functions to handle each step, eg. decrement ammo, calculate hit chance, resolve hit or miss, calculate damage, and each type of attack skill will implement the methods in their own specific way

    Some patterns left out due to lack of inspiration.

  • One thing Brandon Eich had the good sense to bring up in Coders at Work is that patterns are hacks and workarounds: [Patterns] show some kind of defect in the language. These patterns are not free. There's no free lunch. So we should be looking for evolution in the language that adds the right bits.

    As game programmers rather than compiler designers we rarely get the option to evolve the languages we use, but we can learn to evolve our own style to better fit our language and requirements. Patterns are some of this, but not using patterns is another part, especially since as Brandon says, patterns rarely go without a notable performance or memory or code agility cost. MVC just is not a great pattern for many things in games. Singleton is a workaround for lame C++ static initialization rules, and you probably shouldn't be doing those anyway. Factory simplifies complicated object creation - maybe your objects should just be simpler to start with. The popular patterns are tools to resort to when we need them to manage something complex, not tools we should be longing to use to build something complex at the start.

    Good (game) code might use patterns, or it might not. If it does use patterns, fine - they're a great communication tool to explain code structure to other programmers at a high, language-independent level. If you think the code is better without using a pattern, don't beat yourself up over it - it probably is.

  • Of course, as others have said, all patterns are useful in the right circumstances, and part of learning how to use them is learning when to use them. However, the excellent book Core Techniques and Algorithms in Game Programming by Daniel Sanchez-Crespo Dalmau, lists six programming patterns and six usability patterns as especially useful in game programming.

    Programming:

    • Singleton: I don't hate this one like many people do; it can be used for things like the single-player player or the keyboard reader.
    • Factory: Lets you create and destroy objects efficiently.
    • Strategy: Lets you change out AI strategies elegantly.
    • Spatial Index: Helps perform queries on spatial data sets.
    • Composite: Sets up a useful object heirarchy.
    • Flyweight: Frees memory by genericizing things like identical enemies.

    Usability:

    • Shield: Protects from accidental activation of dramatic actions.
    • State: Visual cues of the world/UI status.
    • Automatic Mode Cancellation: Makes the game work more intutitively.
    • Magnetism: Autoaiming and easy unit selection.
    • Focus: Eliminating distracting UI elements.
    • Progress: Universally useful.

    The book, of course, goes into more detail on each of these.

  • Not really about patterns, but about basic principles behind them. In "Design Patterns: Elements of Reusable Object-Oriented Software" (1995), the gang of four (Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides) recommends only two principles for object oriented design: (1) program to an interface and not to an implementation and (2) favor object composition over class inheritance.

    These 2 principles are very helpful in many tasks of game development. For example, many game programmers have used a deep class hierarchy to represent game entities. There is another approach based on composition - component-based game objects. Article about this approach. Even more links. It is a Decorator pattern example.

  • Entity systems are a nice kind of pattern. It's not exactly a design pattern since it's not strickly OOP. However you can mix it with OOP.

    Some good links (start from top for intro):

  • The curiously recurring template pattern can be really useful for avoiding virtual methods and the performance penalty that can come from the virtual function calls.

    This can be the appropriate pattern when you don't actually need to have a container of the base class type which has the interface you're after, but you'd like to have similarly named behaviors and interfaces.

    For example you can use this when compiling classes for multiple platforms or engines (dx vs. opengl) where the variance of type is known at compile time.

  • I wrote a book on exactly that topic: Game Programming Patterns. The chapters that are there might be helpful for you.

  • A design pattern that I evolved over the course of many years, and which has been spectacularly useful to me, is something I refer to as "brokered definition sets"; how to summarize it in GOF terms appears to be controversial, but this question I wrote about it on StackOverflow goes into some detail about it.

    The core concept is that some property of a model, like the species of a creature, is set up so that each possible value for the property has a corresponding definition object -- a single, shared object per value -- that specifies its behavior, and these are accessed through a central broker (which, GOF-wise, may be a Registry, a Factory, or both). In my usage, they're also generally accessed via scalar keys, to facilitate weak binding for runtime morphism purposes.

Tags
c++ software-engineering actionscript-3 design-patterns
Related questions and answers
  • but forced myself to wait on, as there are only so many hours in the day to devote to projects. I am an experienced web developer (12 years) with most of my experience programming in C# and .Net (8 years). I am also a capable graphic designer. I have a surface knowledge of C++, though it's been 10 years since I wrote any C++ code. I also played with the DirectX 5 API back then as well. I am... to devote to pure maths self-education, or can I pretty much figure it out as I go? In a nutshell, I'd love to get some idea of what the best approach for me would be, including DO's and DON'T's that might

  • As most of game programming is done - I read on this very site - in C/C++ I was wondering if there is any learning/studying material for C/C++ that would target specifically game programming. I am not looking for material about "developing games" or "software architecture for games", but rather for material that uses "game programming" as the CONTEXT for introducing and illustrating C/C... experience in OO scripting languages and only some experience in C and Assembler (on AVR microcontrollers), so I am thinking to mid-to-advanced level material, rather than tutorials for beginners

  • I'm fairly new to game development, played around with xna before and just learning OpenGL & c now and I'm interested to know which c/c++ based model animation libraries are out there and which you would recommend? I don't have any particular model format in mind yet but probably a format that is supported by a free modelling tool like Blender.

  • ++ or java I just dont have much experience using the jni. Ive built some sample projects where I pass primitives like floats and perform operations on them on the native side and then passed them back but I cant figure out how to create a scene in opengl in c++ and then pass it to java. Ive been looking at writing everything using java but Im not sure if the java bindings make for some performance...Ive been reteaching myself opengl so I can make a game on android. However Ive been struggling with how to build objects and scenes in opengl using c/c++ and passing them through the jni

  • What tools, patterns, or best practices would you recommend to implement the quest mechanics given below listed requirements? I am talking about software architecture (how generic should you... do you recommend? Requirements: simple 2D mmo(rpg) all the game data, including quests, is stored in a relational database any event in the game could trigger a new quest for players or advancement... be manageable using a world editor without scripting or programming knowledge (Edit: not advocating against scripting in general though) I assume C++ as the language of implementation I was thinking

  • know if my speculations are ok, as I don't have much experience with 3d animations yet. I want to make a well decision as any option I choose would require a lot of work to get it to render and I... them to be attached to the node in most cases, even if I allow setting global lights to the scene. @Nicol: Yes that's what I'm trying to figure out. You can see the code doesn't rely on any hardware... shader in every node. Other option I was thinking was making some helper functions to deal with the simpler cases, which would set some default parameters and would ask only the most basic ones

  • I am a 2D Game Programmer.Some programming languages which I am good at are C,Java ,C#. I also know Actionscript 2.0,3.0 and some javascript. I'm interested in learning 3D Game programming. So far from the research I have accumulated by googling and reading different game development forums and articles. I've noticed that most programmers tend to prefer C++.Also in an online game programming teaching course I noticed they prefer to teach C++ and Visual C++ as the starting course. The reason I am asking this question since I would like to know the "strength" difference of C++, C# and Java

  • I would like to create some level of abstraction above math in my code. I mean I don't want to be dependant on the implementation of math operations or even on class names, which are provided by some math library. I will show you a simple example. Let's assume that we have 2 math libraries. Let's consider 3D-vector classes: Library A has 3D-vector class as "Vector3D" and its method "Subtract... would like to have it like this: My 3D-vector class name will be "vec3" and its method "sub". But behind "vec3" and "sub" it can be implementation from library A or library B, depending on what I

  • wouldn't call myself a C# wizard however. The main questions I have are: Where do I start with my goal to create overlays for games? Does anyone here have any experience with it? How steep would...Greetings I've recently created some interest in Overlays for games. Examples can be Steam/Xfire which use these overlays ingame so the user can access their programs while being in a game. I love this idea and I'm wondering how steep the learning curve would be to eventually create such an overlay (not exactly as advanced as the ones mentioned above). I'm currently programming mainly in C#, I