Advertisement

# Let Your Players Undo Their In-Game Mistakes With the Command Pattern

Read Time: 16 min

Many turn-based games include an undo button to let players reverse mistakes they make during play. This feature becomes especially relevant for mobile game development where the touch may have clumsy touch recognition. Rather than rely on a system where you ask the user "are you sure you want to do this task?" for every action they take, it is much more efficient to let them make mistakes and have the option of easily reversing their action. In this tutorial, we'll look at how to implement this using the Command Pattern, using the example of a tic-tac-toe game.

Note: Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment. (It's not restricted to tic-tac-toe games, either!)

## Final Result Preview

The final result of this tutorial is a tic-tac-toe game that offers unlimited undo and redo operations.

This demo requires Java to run.

Can't load the applet? Watch the gameplay video on YouTube:

You can also run the demo on the command line using TicTacToeMain as the main class to execute from. After extracting the source run the following commands:

 1 2 javac *.java  3 java TicTacToeMain 

## Step 1: Create a Basic Implementation of Tic-Tac-Toe

For this tutorial, you are going to consider an implementation of tic-tac-toe. Although the game is extremely trivial, the concepts provided in this tutorial can apply to much more complex games.

The following download (which is different from the final source download) contains the basic code for a tic-tac-toe game model that does not contain an undo or redo feature. It will be your job to follow this tutorial and add these features. Download the base TicTacToeModel.java.

You should take note, in particular, of the following methods:

 1 public void placeX(int row, int col) {  2  assert(playerXTurn);  3  assert(spaces[row][col] == 0);  4  spaces[row][col] = 1;  5  playerXTurn = false;  6 } 
 1 public void placeO(int row, int col) {  2  assert(!playerXTurn);  3  assert(spaces[row][col] == 0);  4  spaces[row][col] = 2;  5  playerXTurn = true;  6 } 

These methods are the only methods for this game that change the state of the game grid. They will be what you will change.

If you're not a Java developer, you'll probably still be able to understand the code. It's copied here if you just want to refer to it:

 1 2 /** The game logic for a Tic-Tac-Toe game. This model does not have  3  * an associated User Interface: it is just the game logic.  4  *  5  * The game is represented by a simple 3x3 integer array. A value of  6  * 0 means the space is empty, 1 means it is an X, 2 means it is an O.  7  *  8  * @author aarnott  9  *  10  */  11 public class TicTacToeModel {  12  //True if it is the X player’s turn, false if it is the O player’s turn  13  private boolean playerXTurn;  14  //The set of spaces on the game grid  15  private int[][] spaces;  16   17  /** Initialize a new game model. In the traditional Tic-Tac-Toe  18  * game, X goes first.  19  *  20  */  21  public TicTacToeModel() {  22  spaces = new int[3][3];  23  playerXTurn = true;  24  }  25   26  /** Returns true if it is the X player's turn.  27  *  28  * @return  29  */  30  public boolean isPlayerXTurn() {  31  return playerXTurn;  32  }  33   34  /** Returns true if it is the O player's turn.  35  *  36  * @return  37  */  38  public boolean isPlayerOTurn() {  39  return !playerXTurn;  40  }  41   42  /** Places an X on a space specified by the row and column  43  * parameters.  44  *  45  * Preconditions:  46  * -> It must be the X player's turn  47  * -> The space must be empty  48  *  49  * @param row The row to place the X on  50  * @param col The column to place the X on  51  */  52  public void placeX(int row, int col) {  53  assert(playerXTurn);  54  assert(spaces[row][col] == 0);  55  spaces[row][col] = 1;  56  playerXTurn = false;  57  }  58   59  /** Places an O on a space specified by the row and column  60  * parameters.  61  *  62  * Preconditions:  63  * -> It must be the O player's turn  64  * -> The space must be empty  65  *  66  * @param row The row to place the O on  67  * @param col The column to place the O on  68  */  69  public void placeO(int row, int col) {  70  assert(!playerXTurn);  71  assert(spaces[row][col] == 0);  72  spaces[row][col] = 2;  73  playerXTurn = true;  74  }  75   76  /** Returns true if a space on the grid is empty (no Xs or Os)  77  *  78  * @param row  79  * @param col  80  * @return  81  */  82  public boolean isSpaceEmpty(int row, int col) {  83  return (spaces[row][col] == 0);  84  }  85   86  /** Returns true if a space on the grid is an X.  87  *  88  * @param row  89  * @param col  90  * @return  91  */  92  public boolean isSpaceX(int row, int col) {  93  return (spaces[row][col] == 1);  94  }  95   96  /** Returns true if a space on the grid is an O.  97  *  98  * @param row  99  * @param col  100  * @return  101  */  102  public boolean isSpaceO(int row, int col) {  103  return (spaces[row][col] == 2);  104  }  105   106  /** Returns true if the X player won the game. That is, if the  107  * X player has completed a line of three Xs.  108  *  109  * @return  110  */  111  public boolean hasPlayerXWon() {  112  //Check rows  113  if(spaces[0][0] == 1 && spaces[0][1] == 1 && spaces[0][2] == 1) return true;  114  if(spaces[1][0] == 1 && spaces[1][1] == 1 && spaces[1][2] == 1) return true;  115  if(spaces[2][0] == 1 && spaces[2][1] == 1 && spaces[2][2] == 1) return true;  116  //Check columns  117  if(spaces[0][0] == 1 && spaces[1][0] == 1 && spaces[2][0] == 1) return true;  118  if(spaces[0][1] == 1 && spaces[1][1] == 1 && spaces[2][1] == 1) return true;  119  if(spaces[0][2] == 1 && spaces[1][2] == 1 && spaces[2][2] == 1) return true;  120  //Check diagonals  121  if(spaces[0][0] == 1 && spaces[1][1] == 1 && spaces[2][2] == 1) return true;  122  if(spaces[0][2] == 1 && spaces[1][1] == 1 && spaces[2][0] == 1) return true;  123  //Otherwise, there is no line  124  return false;  125  }  126   127  /** Returns true if the O player won the game. That is, if the  128  * O player has completed a line of three Os.  129  *  130  * @return  131  */  132  public boolean hasPlayerOWon() {  133  //Check rows  134  if(spaces[0][0] == 2 && spaces[0][1] == 2 && spaces[0][2] == 2) return true;  135  if(spaces[1][0] == 2 && spaces[1][1] == 2 && spaces[1][2] == 2) return true;  136  if(spaces[2][0] == 2 && spaces[2][1] == 2 && spaces[2][2] == 2) return true;  137  //Check columns  138  if(spaces[0][0] == 2 && spaces[1][0] == 2 && spaces[2][0] == 2) return true;  139  if(spaces[0][1] == 2 && spaces[1][1] == 2 && spaces[2][1] == 2) return true;  140  if(spaces[0][2] == 2 && spaces[1][2] == 2 && spaces[2][2] == 2) return true;  141  //Check diagonals  142  if(spaces[0][0] == 2 && spaces[1][1] == 2 && spaces[2][2] == 2) return true;  143  if(spaces[0][2] == 2 && spaces[1][1] == 2 && spaces[2][0] == 2) return true;  144  //Otherwise, there is no line  145  return false;  146  }  147   148  /** Returns true if all the spaces are filled or one of the players has  149  * won the game.  150  *  151  * @return  152  */  153  public boolean isGameOver() {  154  if(hasPlayerXWon() || hasPlayerOWon()) return true;  155  //Check if all the spaces are filled. If one isn’t the game isn’t over  156  for(int row = 0; row < 3; row++) {  157  for(int col = 0; col < 3; col++) {  158  if(spaces[row][col] == 0) return false;  159  }  160  }  161  //Otherwise, it is a “cat’s game”  162  return true;  163  }  164 165 } 

## Step 2: Understand the Command Pattern

The Command pattern is a design pattern that is commonly used with user interfaces to separate the actions performed by buttons, menus, or other widgets from the user interface code definitions for these objects. This concept of separating action code can be used to track every change that happens to the state of a game, and you can use this information to reverse the changes.

The most basic version of the Command pattern is the following interface:

 1 public interface Command {  2  public void execute();  3 } 

Any action that is taken by the program that changes the state of the game - such as placing an X in a specific space - will implement the Command interface. When the action is taken, the execute() method is called.

Now, you likely noticed that this interface does not offer the ability to undo actions; all it does is take the game from one state to another. The following improvement will allow implementing actions to offer undo capability.

 1 public interface Command {  2  public void execute();  3  public void undo();  4 } 

The goal when implementing a Command will be to have the undo() method reverse every action taken by the execute method. As a consequence, the execute() method will also be able to provide the capability to redo an action.

That's the basic idea. It'll become clearer as we implement specific Commands for this game.

## Step 3: Create a Command Manager

To add an undo feature, you will create an CommandManager class. The CommandManager is responsible for tracking, executing, and undoing Command implementations.

(Recall that the Command interface provides the methods to make changes from one state of a program to another and also reverse it.)

 1 public class CommandManager {  2  private Command lastCommand;  3 4  public CommandManager() {}  5 6  public void executeCommand(Command c) {  7  c.execute();  8  lastCommand = c;  9  }  10 11  ...  12 13 } 

To execute a Command, the CommandManager is passed a Command instance, and it will execute the Command and then store the most recently executed Command for later reference.

Adding the undo feature to the CommandManager simply requires telling it to undo the most recent Command that executed.

 1 public boolean isUndoAvailable() {  2  return lastCommand != null;  3 }  4 5 public void undo() {  6  assert(lastCommand != null);  7  lastCommand.undo();  8  lastCommand = null;  9 } 

This code is all that is required to have a functional CommandManager. In order for it to function properly, you will need to create some implementations of the Command interface.

## Step 4: Create Implementations of the Command Interface

The goal of the Command pattern for this tutorial is to move any code that changes the state of the tic-tac-toe game into a Command instance. Namely, the code in the methods placeX() and placeO() are what you will be changing.

Inside the TicTacToeModel class, add two new inner classes called PlaceXCommand and PlaceOCommand, respectively, which each implement the Command interface.

 1 public class TicTacToeModel {  2 3  ...  4 5  private class PlaceXCommand implements Command {  6 7  public void execute() {  8  ...  9  }  10 11  public void undo() {  12  ...  13  }  14 15  }  16 17  private class PlaceOCommand implements Command {  18 19  public void execute() {  20  ...  21  }  22 23  public void undo() {  24  ...  25  }  26 27  }  28 29 } 

The job of a Command implementation is to store a state and have logic to either transition to a new state resulting from the execution of the Command or to transition back to the initial state before the Command was executed. There are two straightforward ways of achieving this task.

1. Store the entire previous state and next state. Set the game's current state to the next state when execute() is called and set the game's current state to the stored previous state when undo() is called.
2. Store only the information that changes between states. Change only this stored information when execute() or undo() is called.
 1 //Option 1: Storing the previous and next states  2 private class PlaceXCommand implements Command {  3  private TicTacToeModel model;  4  //  5  private int[][] previousGridState;  6  private boolean previousTurnState;  7  private int[][] nextGridState;  8  private boolean nextTurnState;  9  //  10  private PlaceXCommand (TicTacToeModel model, int row, int col) {  11  this.model = model;  12  //  13  previousTurnState = model.playerXTurn;  14  //Copy the entire grid for both states  15  previousGridState = new int[3][3];  16  nextGridState = new int[3][3];  17  for(int i = 0; i < 3; i++) {  18  for(int j = 0; j < 3; j++) {  19  //This is allowed because this class is an inner  20  //class. Otherwise, the model would need to  21  //provide array access somehow.  22  previousGridState[i][j] = m.spaces[i][j];  23  nextGridState[i][j] = m.spaces[i][j];  24  }  25  }  26  //Figure out the next state by applying the placeX logic  27  nextGridState[row][col] = 1;  28  nextTurnState = false;  29  }  30  //  31  public void execute() {  32  model.spaces = nextGridState;  33  model.playerXTurn = nextTurnState;  34  }  35  //  36  public void undo() {  37  model.spaces = previousGridState;  38  model.playerXTurn = previousTurnState;  39  }  40 } 

The first option is a bit wasteful, but that does not mean it is bad design. The code is straightforward and unless the state information is extremely large the amount of waste won't be something to worry about.

You will see that, in the case of this tutorial, the second option is better, but this approach won’t always be the best for every program. More often than not, however, the second option will be the way to go.

 1 //Option 2: Storing only the changes between states  2 private class PlaceXCommand implements Command {  3  private TicTacToeModel model;  4  private int previousValue;  5  private boolean previousTurn;  6  private int row;  7  private int col;  8  //  9  private PlaceXCommand(TicTacToeModel model, int row, int col) {  10  this.model = model;  11  this.row = row;  12  this.col = col;  13  //Copy the previous value from the grid  14  this.previousValue = model.spaces[row][col];  15  this.previousTurn = model.playerXTurn;  16  }  17  //  18  public void execute() {  19  model.spaces[row][col] = 1;  20  model.playerXTurn = false;  21  }  22  //  23  public void undo() {  24  model.spaces[row][col] = previousValue;  25  model.playerXTurn = previousTurn;  26  }  27 } 

The second option only stores the changes that happen, rather than the entire state. In the case of tic-tac-toe, it is more efficient and not notably more complex to use this option.

The PlaceOCommand inner class is written in a similar way - have a go at writing it yourself!

## Step 5: Put Everything Together

In order to make use of your Command implementations, PlaceXCommand and PlaceOCommand, you will need to modify the TicTacToeModel class. The class must make use of a CommandManager and it must use Command instances instead of applying actions directly.

 1 public class TicTacToeModel {  2  private CommandManager commandManager;  3  //  4  ...  5  //  6  public TicTacToeModel() {  7  ...  8  //  9  commandManager = new CommandManager();  10  }  11  //  12  ...  13  //  14  public void placeX(int row, int col) {  15  assert(playerXTurn);  16  assert(spaces[row][col] == 0);  17  commandManager.executeCommand(new PlaceXCommand(this, row, col));  18  }  19  //  20  public void placeO(int row, int col) {  21  assert(!playerXTurn);  22  assert(spaces[row][col] == 0);  23  commandManager.executeCommand(new PlaceOCommand(this, row, col));  24  }  25  //  26  ...  27 } 

The TicTacToeModel class will work exactly as it did before your changes now, but you can also expose the undo feature. Add an undo() method to the model and also add a check method canUndo for the user interface to use at some point.

 1 public class TicTacToeModel {  2  //  3  ...  4  //  5  public boolean canUndo() {  6  return commandManager.isUndoAvailable();  7  }  8  //  9  public void undo() {  10  commandManager.undo();  11  }  12 13 } 

You now have a completely functional tic-tac-toe game model that supports undo!

## Step 6: Take it Further

With a few small modifications to the CommandManager, you can add support for redo operations as well as an unlimited number of undos and redos.

The concept behind a redo feature is pretty much the same as an undo feature. In addition to storing the last Command executed, you also store the last Command that was undone. You store that Command when an undo is called and clear it when a Command is executed.

 1 public class CommandManager {  2 3  private Command lastCommandUndone;  4 5  ...  6 7  public void executeCommand(Command c) {  8  c.execute();  9  lastCommand = c;  10  lastCommandUndone = null;  11  }  12 13  public void undo() {  14  assert(lastCommand != null);  15  lastCommand.undo();  16  lastCommandUndone = lastCommand;  17  lastCommand = null;  18  }  19 20  public boolean isRedoAvailable() {  21  return lastCommandUndone != null;  22  }  23 24  public void redo() {  25  assert(lastCommandUndone != null);  26  lastCommandUndone.execute();  27  lastCommand = lastCommandUndone;  28  lastCommandUndone = null;  29  }  30 } 

Adding in multiple undos and redos is a matter of storing a stack of undoable and redoable actions. When a new action is executed it is added to the undo stack and the redo stack is cleared. When an action is undone, it is added to the redo stack and removed from the undo stack. When an action is redone, it is removed from the redo stack and added to the undo stack.

The above image shows an example of the stacks in action. The redo stack has two items from commands that have already been undone. When new commands, PlaceX(0,0) and PlaceO(0,1), are executed, the redo stack is cleared and they are added to the undo stack. When a PlaceO(0,1) is undone, it is removed from the top of the undo stack and placed on the redo stack.

Here's how that looks in code:

 1 public class CommandManager {  2 3  private Stack undos = new Stack();  4  private Stack redos = new Stack();  5 6  public void executeCommand(Command c) {  7  c.execute();  8  undos.push(c);  9  redos.clear();  10  }  11 12  public boolean isUndoAvailable() {  13  return !undos.empty();  14  }  15 16  public void undo() {  17  assert(!undos.empty());  18  Command command = undos.pop();  19  command.undo();  20  redos.push(command);  21  }  22 23  public boolean isRedoAvailable() {  24  return !redos.empty();  25  }  26 27  public void redo() {  28  assert(!redos.empty());  29  Command command = redos.pop();  30  command.execute();  31  undos.push(command);  32  }  33 } 

Now you have a tic-tac-toe game model that can undo actions all the way back to the beginning of the game and redo them again.

If you'd like to see how this all fits together, grab the final source download, which contains the completed code from this tutorial.

## Conclusion

You may have noticed that the final CommandManager you wrote will work for any Command implementations. This means that you can code up a CommandManager in your favorite language, create some instances of the Command interface, and have a full system prepared for undo/redo. The undo feature can be a great way to allow users to explore your game and make mistakes without feeling committed to bad decisions.

Thanks for taking interest in this tutorial!

As some further food for thought, consider the following: the Command pattern along with the CommandManager allow you to track every state change during the execution of your game. If you save this information, you can create replays of the execution of the program.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Game Development tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.