Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First and Ugly solution in Clear category for Multicolored Lamp by 87buick
#!/usr/bin/env checkio --domain=py run multicolored-lamp
#as the mission author suggested, I have attemped to use the state pattern here.
#In researching, I found a few variations of the pattern and I used the one
#I almost understand.
class LampState(object):
"""A class for the various state classes to subclass and subsequently
accept the Lamp class as a parameter in their constructors."""
pass
class NoColor(LampState):
"""The Lamp has no color in this state and the nextColor method will
cause the Lamp to be green"""
def __init__(self, Lamp):
self.Lamp = Lamp
def nextColor(self):
self.Lamp.state = self.Lamp.greenColor
return 'Green'
class GreenColor(LampState):
"""The Lamp is green in this state and the nextColor method will
cause the Lamp to be red"""
def __init__(self, Lamp):
self.Lamp = Lamp
def nextColor(self):
self.Lamp.state = self.Lamp.redColor
return 'Red'
class RedColor(LampState):
"""The Lamp is red in this state and the nextColor method will
cause the Lamp to be blue"""
def __init__(self, Lamp):
self.Lamp = Lamp
def nextColor(self):
self.Lamp.state = self.Lamp.blueColor
return 'Blue'
class BlueColor(LampState):
"""The Lamp is blue in this state and the nextColor method will
cause the Lamp to be yellow"""
def __init__(self, Lamp):
self.Lamp = Lamp
def nextColor(self):
self.Lamp.state = self.Lamp.yellowColor
return 'Yellow'
class YellowColor(LampState):
"""The Lamp is yellow in this state and the nextColor method will
cause the Lamp to be green"""
def __init__(self, Lamp):
self.Lamp = Lamp
def nextColor(self):
self.Lamp.state = self.Lamp.greenColor
return 'Green'
class Lamp(object):
"""The Lamp object has the method light which causes the Lamp to change
color"""
def __init__(self):
"""Each state gets a variable which gets and instance of that states'
object"""
self.noColor = NoColor(self)
self.greenColor = GreenColor(self)
self.redColor = RedColor(self)
self.blueColor = BlueColor(self)
self.yellowColor = YellowColor(self)
self.state = self.noColor #sets the initial state of having no color
def light(self):
"""Calls the nextColor method of the current state object"""
return self.state.nextColor()
pass
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. 31, 2018
Comments: