You cannot undo the last action if you did not save it.
If you saved the last action, you can invert it. Since you know the reverse action after the action is completed, you can simply save the reverse action directly.
Let your instance Minibothave an attribute .reverse_actionthat is a tuple of the method to call and arguments to pass.
So,
def left(self):
self.reverse_action = (self.right, ())
...
def forward(self, distance):
self.reverse_action = (self.forward, (-distance,))
def revert_last(self):
if self.reverse_action:
(method, args) = self.reverse_action
method(*args)
self.reverse_action = None
. , , .pop() , .
, . ( google up: "Undo buffer", "Circular buffer", "Event sourcing".)
, , .. :
def save_state(self):
self.previous_state = (self.x, self.y, self.angle)
def restore_previous_state(self):
(self.x, self.y, self.angle) = self.previous_state
def left(self):
self.save_state()
...
.. , , , .