It is helpful to build a general Python module, containing a number classes to make it easy to utilize strategies and decorators with Monty Karel programs. These classes won't be robots, but can be used by robots and are often features (fields) of robot classes. Strategies and Decorators are discussed in Chapter 4, including how to build up a list of decorators to "remember" a chain of actions for execution later.
Initially, you are asked to add some infrastructure to a module to make it possible to use strategies appropriate for all of the UrRobot basic actions. This will require building a number of simple Decorator classes. Below is some infrastructure to get you started.
Initially you should add decorators (classes) that represent common and useful actions of UrRobots. This module can be extended later for more advanced things.
from karel.robota import UrRobot, East, window, world
class Strategy:
"An interface to define strategies. Subclass this to define concrete strategies."
def doIt(self, robot):
raise NotImplementedError ("Unimplemented Strategy")
def decorated(self):
return self
class NullStrategy(Strategy):
"An implementation in which doIt does nothing at all"
def doIt(self, robot):
pass
class Decorator(NullStrategy):
def __init__(self, decorated):
self._decorated = decorated
def decorated(self):
return self._decorated
class TurnLeftDecorator(Decorator):
def doIt(self, robot):
robot.turnLeft()
self._decorated.doIt(robot)
The following classes have been found useful, similar to the TurnLeftDecorator above: TurnRightDecorator, TurnAroundDecorator, PickBeeperDecorator, PutBeeperDecorator, MoveDecorator and possibly one or two others. The author hasn't found any use for a TurnOffDecorator, however, but it is easy to build.
Note that all of these classes can be in a single module and imported into other programs as needed.
Note that the LeftTurnDecorator sends the leftTurn message to its argument, a robot, prior to invoking the doIt method of the decorated strategy. This implies that if you build up a chain of decorators the last one added will be the first one that acts.