In a game I'm writing there is a player that moves on a board. On this board there are other objects too. So I have a bunch of objects each one holding its state. The player can be asked to move onto a specific adjacent cell. Its moving is made of three discrete parts: exiting its current cell; traversing from the current cell to the destination cell; entering the new cell. Each of these phases may trigger some change of the objects on the board. The player either perform a full movement or doesn't move at all. There may be obstacles that prevent the player from reaching the goal cell on each of the three phases. The problem is to tell if the player can perform the move, and move it if and only if it can.
I first thought that I can inspect if there is no obstacle that prevents the player from exiting its current cell, if there is no obstacle preventing it to traverse towards the goal cell, and if there is no obstacle that prevents it to enter the goal cell. If all these conditions are matched, then I move the player; if not, then I don't move the player and the state of the board hasn't changed.
But it's not that simple. In fact, even if the three tests succeed, the player may be unable to move. For instance, when it exits its cell a change of the board may be triggered that makes impossible for it to later transition to the goal cell. In this situation everything must stay the same: the player shouldn't move (because it can't perform a full move) and the board should stay the same, meaning that no event should be triggered.
Since I can't know if the player can move or not beforehand, but only attempting to move it, I thought about another approach. I can try to move the player without checking anything beforehand, and rollback to the previous state in case of failure on any of the three moving steps. The rolling back is necessary because, while trying to move, an event may have been triggered so the board may have changed accordingly.
The question is the following. How can I try to execute some code that may change the state of some objects and then rollback to the previous state in case something happens? More concretely, suppose I have a method move
that returns a boolean, and that changes the state of some objects. I'd like to keep the changes if the method returns true, otherwise rollback all the changes. How can such a behaviour be implemented?
Or do you have a better idea to solve the described problem?
Aucun commentaire:
Enregistrer un commentaire