Skip to content

Instantly share code, notes, and snippets.

@clamytoe
Created September 5, 2018 18:31
Show Gist options
  • Save clamytoe/81b4e8f17b053f8e0aac7fdbe34b56db to your computer and use it in GitHub Desktop.
Save clamytoe/81b4e8f17b053f8e0aac7fdbe34b56db to your computer and use it in GitHub Desktop.
100DaysOfCode Traffic Light challenge
"""
traffic_lights.py
100DaysOfCode Traffic Light challenge
"""
from collections import namedtuple
from itertools import cycle
from os import platform, system
from time import sleep
Color = namedtuple("Color", "name pause msg")
GREEN = Color("green", 10, "Go! The light is green")
YELLOW = Color("yellow", 3, "Caution! The light is amber")
RED = Color("red", 5, "Stop! The light is red")
class Light:
"""Traffic Light
Handles the state of the lights
"""
colors = cycle((GREEN, YELLOW, RED))
def __init__(self):
"""Initializes the class with itertools cycle"""
self.color = cycle(self.colors)
def __repr__(self):
"""Object representation of the light"""
return f"{self.__class__.__name__}(color={self.color})"
def __str__(self):
"""String representation of the light"""
state = next(self.color)
return eval(f"state.{self.mode}")
@staticmethod
def clear():
"""Clears the screen"""
if platform.lower() in ["darwin", "linux"]:
_ = system("clear")
else:
_ = system("cls")
def start(self):
"""Starts the loop cycle"""
while True:
try:
state = next(self.color)
self.clear()
print(eval(f"{state}.msg"))
sleep(eval(f"{state}.pause"))
except KeyboardInterrupt:
print("\nAborted by user!")
exit(0)
def main():
"""Starts the program if called from command line"""
traffic = Light()
traffic.start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment