Crave For Games

You are in the Article list. If you want a full list of the StoneDrop develompent log notes you can go to the DevLog page.
Game record, Undo operation (generic gamedev approach)


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:[1] 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.


UPD June 2016: You can try the undo operation in action right in your desktop browser (Firefox prefered) in the WebGL build on the StoneDrop website[2]


Link 1:

Link 2:

This article in social networks: