Command programming pattern implementation in the game StoneDrop
Goal: be able to record all events in the game (save replays) and allow player to cancel his turns.
Approach: Command - a programming pattern.
To be able to save game replays we need to incapsulate all actions in the game into some class. The ordered list of the objects of such a class will represent the game record. You can read about this approach in details here: en.wikipedia.org/w... and in the article I'll describe how it's implemented in the StoneDrop.
Take a look at the figure attached:
- there is an object called GameState which holds all the information about the current game state (game field, score, time, statistics,...),
- no one (I mean no other class except for classes derived from GameChange) allowed to modify the GameState,
- if some class needs to change the GameState it has to create an object of a class derived from the GameChange class and pass this object to the GameState via Apply method,
- all classes derived from GameChange are designed in such a way that they stores all the information that required both to perform the change and to undo it,
- when the GameState gets a GameChange object the state initializes it (via Init method by passing the state to allow the change to save all the information that is about to be changed), applies it (by calling Apply method where the change modifies the state) and remembers it in the ordered list of changes,
- when we need to undo last change the state recalls it from the Changes list and calls Discard method which restores the modified before values,
- if it's required to save a game replay then we just serialize the Changes list (here is a post about Serialization in C# Serialization (Uni...) into a file. To replay the whole game we just need to deserialize it and call Apply method in all changes consequently from start to end.