[]class GarageDoor(object): def init(self): # Initial status; and variables that will be used. self.state = "CLOSED" self.stopped_state = "" self.blocked = False print("Door: " + self.state) self.states_dict = {"CLOSED": "OPENING", "OPEN": "CLOSING", "CLOSING": "CLOSED", "OPENING": "OPEN", "STOPPED_WHILE_OPENING": "CLOSING", "STOPPED_WHILE_CLOSING": "OPENING", "EMERGENCY_OPENING": "OPEN_BLOCKED", "OPEN_BLOCKED": "OPEN"} self.stop_states = {"OPENING": "STOPPED_WHILE_OPENING", "CLOSING": "STOPPED_WHILE_CLOSING"} self.blocked_states = {"CLOSING": "EMERGENCY_OPENING"}
def perform(self, action):
# Own code which prints the status and makes entering the strings valid
if action == "button_clicked" and not self.blocked and self.state not in ("OPEN_BLOCKED", "EMERGENCY_OPENING"):
# When the door is blocked it shouldn't accept input!
self.button_clicked()
elif action == "cycle_complete":
self.cycle_complete()
elif action == "block_detected" and self.state != "EMERGENCY_OPENING":
# Without the second condition it would cause an error
self.block()
elif action == "block_cleared" and self.blocked and self.state != "EMERGENCY_OPENING":
self.clear()
self.door_print(action)
def button_clicked(self):
if self.state in self.stop_states.keys():
# If the status is opening/closing
self.state = self.stop_states[self.state]
else:
self.state = self.states_dict[self.state]
def cycle_complete(self):
# Avoid re-running of the Cycle Complete command
if self.state in self.stop_states.keys() or self.state == "EMERGENCY_OPENING":
self.state = self.states_dict[self.state]
def block(self):
# For the bonus, I save the prior status when the door blocks
self.stopped_state = self.state
# And if the door is opening/closing, behaviour changes
if self.state == "CLOSING":
self.state = self.blocked_states[self.state]
# To prevent inputs when blocked
self.blocked = True
def clear(self):
# Un-block the door
self.blocked = False
self.state = self.stopped_state
# Return to "OPEN"
if self.stopped_state == "CLOSING":
self.state = "OPEN"
def door_print(self, action):
print("> " + action.replace("_", " ").capitalize()
+ "\nDoor: " + self.state + " | Blocked = " + str(self.blocked))
a = "button_clicked" b = "cycle_complete" c = "block_detected" d = "block_cleared"
garage_door1 = GarageDoor()
input1 = '''button_clicked cycle_complete button_clicked button_clicked button_clicked button_clicked button_clicked cycle_complete'''
for x in input1.split(): garage_door1.perform(x)
print("-----------------------------------------------------")
garage_door2 = GarageDoor()
input2 = '''button_clicked cycle_complete button_clicked block_detected button_clicked cycle_complete button_clicked block_cleared button_clicked cycle_complete'''
for x in input2.split(): garage_door2.perform(x)