I am writing my own 'Rubik's cube' application. The main class Cube
has 18 rotation methods:
- RotateAxisXClockWise, RotateAxisXAntiClockWise
- RotateAxisYClockWise, RotateAxisYAntiClockWise
RotateAxisZClockWise, RotateAxisZAntiClockWise
RotateUpperFaceClockWise, RotateUpperFaceAntiClockWise
- RotateFrontFaceClockWise, RotateFrontFaceAntiClockWise
- RotateRightFaceClockWise, RotateRightFaceAntiClockWise
- RotateBackFaceClockWise, RotateBackFAceAntiClockWise
- RotateLeftFaceClockWise, RotateLeftFaceAntiClockWise
- RotateDownFaceClockWise, RotateDownFaceAntiClockWise
Yes, they could be joined in pairs with a parameter Direction (for example RotateFrontFace(Direction direction)
) but for now this seems appropriately.
I would like to implement undo/redo functionality and because all methods have the same signature (no input parameters, void return type) they could be saved in a LinkedList data structure. So every time one of the rotation methods is called, it is added to the linked list.
This would work pretty well if we start on the beginning of the LinkedList (haven't tried it out yet though) and advance toward the end, so each rotation would be performed exactly as it was in the first place.
But what about undo? If I traverse the list from the end to the beginnig, then the opposite method should be called (for example instead of RotateFrontFaceClockWise
, RotateFrontFaceAntiClockWise
should be called). Any ideas how to implement this? Elegantly? :)
I would not use delegate references as the way to model the rotations, if one of the main purposes is to be able to perform redo/undo. I would consider creating a data-model for each rotation, and store a list of these rotation steps. Each step could then have it's own associated Redo/Undo delegate, which allows someone traversing the list (from either end) to understand what operations took place, and either repeat or reverse them.
One additional benefit of a data-oriented approach to model such transformations, is that it could potentially reduce the number of similar (but slightly different) versions of your
RotateXXX( )
methods.EDIT: Addressing the your question about what shape such a solution might take.
The simplest thing to do may be to store a
Tuple<Action,Action>
representing each pair of rotate/unrotate operations as paired delegates. However, I would consider using an explicit data structure that describes the rotation operation, perhaps eventually including things like a descriptive name, direction/face attributes, and so on. I would also change yourRotateXXX
methods so that they are static methods ofCube
, and accept an instance of cube as a parameter. This would allow modeling the rotation operations externally to the instance ofCube
.