I'm working on a game, in which a player can move around a board/grid. It has moveLeft(), moveRight(), moveUp(), and moveDown() methods which move the player 1 space at a time around the board.
I'm trying to plan out my approach to required Undo/Redo functionality on the player movement (e.g. if player had gone one space to left, and Undo was called, player would move one space to right). I'm a student, and looking into Stacks.
However, when planning the logic out on paper before programming (I find this helps me when undertaking homework), I don't know if Stacks would be appropriate based on the following problem....
When each move method is called, a string 'Up', 'Down', 'Left', 'Right' is added to Stack 1, dependent on the method called. This tracks the players movement around the board.
If undo() is called, the string on top of Stack 1 is removed, and added to a new stack, 'Stack 2'. This is used to track 'undone' moves, so that redo() has a path to follow.
If redo() is called, the string on Stack 2 is removed, and back added to Stack 1.
This works perfectly, but only if you call Redo() for exactly the same amount of times as Undo() and directly after it.
E.g.:
- Player makes 4 moves: (Stack 1 now has 4 strings)
- Undo() is called once: (Stack 1 now has 3 strings, Stack 2 has 1 string)
- Player makes 4 more moves: (Stack 1 now has 7 strings, Stack 2 still has 1 string)
- Undo() is called once: (Stack 1 now has 6 strings, Stack 2 has 2 strings)
- Redo() is called : (here is the problem) This can be called twice, because Stack 2 has 2 strings, but in reality the Player on the board should only be able to call Redo() once.
I've been trying to work on the logic behind this in isolation for the last 4 hrs! Any advice appreciated. Namely - based on the above, is it still possible to do what I need to do with Stacks, and I need to find a work around to the problem? Or should I abandon, because it is not possible.
Stackor can you use something else (i.e.List)? - Dan W