Undo & Redo [ October 07, 2003 ] by Roberto Valdunciel, alias Rober
Adding "Undo" and "Redo" buttons to increase playability in puzzle games.
In puzzle-like games where you perform movements in some order to resolve a level, you can add undo and redo buttons to increase playability.
You need 2 arrays: UndoArray and RedoArray. So everytime you perform an action, you store some information that TOTALLY describe this action in UndoArray. Add it to last position.
The content of an action to store in the arrays it's usually a set of variables: an array. For example the position x,y of a block and the direction dx,dy of the movement: [x,y,dx,dy]. But what is an action? You must decide what you want to be able to undo or redo. In a game where a character moves blocks, perphaps you want only to undo block movements, not character free movements...
When you press undo button you extract last position of UndoArray and use it to undo the action, while moving this action to RedoArray. For redo an action just reverse this process. Then, first action to be undone is last in UndoArray and first action to be redone is last in RedoArray. Note that when you perform a new action, if there's any content in RedoArray you must delete it.
To undo an action, we use same instructions that performing it but reversing things. Then, if clicking somewhere gives a point, we just store where we click [x,y], and when undoing the action we check if this position gives a point or not (we don't need to store that it gives a point). So if it gives a point, when undoing removes one. To redo an action we do things as performing it.
UndoButton.onRelease = Undo;
RedoButton.onRelease = Redo;
//EXTRACT LAST UNDO ACTION wHILE MOVING IT TO REDO
redoArray.push(action = undoArray.pop());
//UNDO THE ACTION
x = action;
y = action;
//more instructions in reverse way that move()...
//EXTRACT LAST REDO ACTION wHILE MOVING IT TO UNDO
undoArray.push(action = redoArray.pop());
//REDO THE ACTION
x = action;
y = action;
//more instructions like in move()...
//PRESSING IT'S AN ACTION, HERE
board.onPress = move;
//ADD THE ACTION TO UNDOARRAY
//EMPTY OUT REDOARRAY
//performs the action
We can also use one array storing all performed actions, along a cursor that stores current position. To undo we use cursor position in the array, to redo cursor next position. On performing a new action, we delete all values after the cursor and add the action at the end of the array.
When we resolve a level, UndoArray content it's the level solution. We can send this solution to a server script to save it in a db. Then, to play the level solution, we go through each value like when redoing. Knowing we can't send and array to the script, the first try would be: