• 12
• 10
• 10
• 13
• 10

# "Command" design pattern for games

This topic is 2173 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm trying to figure out a good design for having "commands" in a video game (an RTS specifically). The language I use is C#, although I can take inspiration from solutions in any language really. I'll illustrate:

Player hits "left" arrow on keyboard
A "move camera, x = -10, y = 0" command is generated
The command is enqueued to the general queue of commands
At some point in the future, the "command processor" dequeues the command
It figures out that this is a move camera command, extract the parameters, and sends to, say, the camera class
The camera class moves the camera -10 to the left

Other requirements:
- commands can be serialized to disk and to the network for replay/multiplayer
- processing of commands should be fast - no reflection involved if at all possible

I read about the Command Pattern but every example I see is trivial and would pose problems in a real game, for instance each command has to know about every object necessary to execute it; not only is this not very clean, it'll also pose problems for serialization. My UnitManager is not the same reference as your UnitManager. I don't want a MoveUnitCommand to call the UnitManager, I want the UnitManager to receive MoveUnitCommands and know how to process them himself.

For now, here's what my first attempt looks like:

 public interface ICommand {} public class CommandMoveCamera : ICommand { public int DeltaX; public int DeltaY; } // other commands public class Game { Queue<ICommand> m_commands; void Update() { // Say we need to add a CommandMoveCamera m_commands.Enqueue(new CommandMoveCamera { DeltaX = x, DeltaY = y }); // At some point in the future, the commands are processed: while (m_commands.Count > 0) { ICommand command = m_commands.Dequeue(); // how do we branch based on the concrete type? } } }
And the question is in the code, how to branch out based on the concrete type of each command? Efficiently I mean, I can figure out very slow means myself just fine.

I'm sure some of you have implemented similar systems in the past and I'd like to know how you solved this problem.

As long as you always construct that array in the same way, then the "camera system" index will be the same every time you run the code, so commands are easily serialized to disk/network.class Command { public UInt16 system; public UInt16 type; }; class CommandQueue { List<System> systems; public void ExecuteCommand( Command c ) { systems[c.system].ExecuteCommand(c); } }Using integer indices/IDs instead of pointers/references is very common in games because of the flexibility that such simplicity gives you.