Home ยป What are some programming design patterns that are useful in game development? [closed]

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


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.

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

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.

Related Solutions

Default value for UUID column in Postgres

tl;dr Call DEFAULT when defining a column to invoke one of the OSSP uuid functions. The Postgres server will automatically invoke the function every time a row is inserted. CREATE TABLE tbl ( pkey UUID NOT NULL DEFAULT uuid_generate_v1() , CONSTRAINT pkey_tbl...

comparing five integers with if , else if statement

try this : int main () { int n1, n2, n3, n4, n5, biggest,smallest; cout << "Enter the five numbers: "; cin >> n1 >> n2 >> n3 >> n4 >> n5 ; smallest=biggest=n1; if(n2>biggest){ biggest=n2; } if(n2<smallest){ smallest=n2;...

How to play YouTube audio in background/minimised?

Here's a solution using entirely free and open source software. The basic idea is that although YouTube can't play clips in the background, VLC for Android can play clips in the background, so all we need to do is pipe the clip to VLC where we can listen to it...

Why not use “which”? What to use then?

Here is all you never thought you would ever not want to know about it: Summary To get the pathname of an executable in a Bourne-like shell script (there are a few caveats; see below): ls=$(command -v ls) To find out if a given command exists: if command -v...

Split string into Array of Arrays [closed]

If I got correct what you want to receive as a result, then this code would make what you want: extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: self.count, by: size).map { Array(self[$0 ..< Swift.min($0 + size,...

Retrieving n rows per group

Let's start with the basic scenario. If I want to get some number of rows out of a table, I have two main options: ranking functions; or TOP. First, let's consider the whole set from Production.TransactionHistory for a particular ProductID: SELECT...

Don’t understand how my mum’s Gmail account was hacked

IMPORTANT: this is based on data I got from your link, but the server might implement some protection. For example, once it has sent its "silver bullet" against a victim, it might answer with a faked "silver bullet" to the same request, so that anyone...

What is /storage/emulated/0/?

/storage/emulated/0/Download is the actual path to the files. /sdcard/Download is a symlink to the actual path of /storage/emulated/0/Download However, the actual files are located in the filesystem in /data/media, which is then mounted to /storage/emulated/0...

How can I pass a command line argument into a shell script?

The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The...

What is pointer to string in C?

argv is an array of pointers pointing to zero terminated c-strings. I painted the following pretty picture to help you visualize something about the pointers. And here is a code example that shows you how an operating system would pass arguments to your...

How do mobile carriers know video resolution over HTTPS connections?

This is an active area of research. I happen to have done some work in this area, so I'll share what I can about the basic idea (this work was with industry partners and I can't share the secret details ๐Ÿ™‚ ). The tl;dr is that it's often possible to identify an...

How do I change the name of my Android device?

To change the hostname (device name) you have to use the terminal (as root): For Eclair (2.1): echo MYNAME > /proc/sys/kernel/hostname For Froyo (2.2): (works also on most 2.3) setprop net.hostname MYNAME Then restart your wi-fi. To see the change, type...

How does reverse SSH tunneling work?

I love explaining this kind of thing through visualization. ๐Ÿ™‚ Think of your SSH connections as tubes. Big tubes. Normally, you'll reach through these tubes to run a shell on a remote computer. The shell runs in a virtual terminal (tty). But you know this part...

Difference between database vs user vs schema

In Oracle, users and schemas are essentially the same thing. You can consider that a user is the account you use to connect to a database, and a schema is the set of objects (tables, views, etc.) that belong to that account. See this post on Stack Overflow:...

What’s the output of this code written in java?

//if you're using Eclipse, press ctrl-shift-f to "beautify" your code and make it easier to read int arr[] = new int[3]; //create a new array containing 3 elements for (int i = 0; i < 3; i++) { arr[i] = i;//assign each successive value of i to an entry in...

How safe are password managers like LastPass?

We should distinguish between offline password managers (like Password Safe) and online password managers (like LastPass). Offline password managers carry relatively little risk. It is true that the saved passwords are a single point of failure. But then, your...