Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Implementation by state pattern solution in Clear category for Multicolored Lamp by Negamax
from abc import ABCMeta, abstractmethod
class State(metaclass=ABCMeta):
@abstractmethod
def light(self):
pass
class Green(State):
def __init__(self, lamp):
self.lamp = lamp
def light(self):
self.lamp.state = self.lamp.red
return "Green"
class Red(State):
def __init__(self, lamp):
self.lamp = lamp
def light(self):
self.lamp.state = self.lamp.blue
return "Red"
class Blue(State):
def __init__(self, lamp):
self.lamp = lamp
def light(self):
self.lamp.state = self.lamp.yellow
return "Blue"
class Yellow(State):
def __init__(self, lamp):
self.lamp = lamp
def light(self):
self.lamp.state = self.lamp.green
return "Yellow"
# Color order: "Green", "Red", "Blue", "Yellow".
class Lamp:
def __init__(self):
self.green = Green(self)
self.red = Red(self)
self.blue = Blue(self)
self.yellow = Yellow(self)
self.state = self.green
def light(self):
return self.state.light()
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
lamp_1 = Lamp()
lamp_2 = Lamp()
lamp_1.light() #Green
lamp_1.light() #Red
lamp_2.light() #Green
assert lamp_1.light() == "Blue"
assert lamp_1.light() == "Yellow"
assert lamp_1.light() == "Green"
assert lamp_2.light() == "Red"
assert lamp_2.light() == "Blue"
print("Coding complete? Let's try tests!")
Dec. 26, 2019