Created
September 5, 2018 18:31
-
-
Save clamytoe/81b4e8f17b053f8e0aac7fdbe34b56db to your computer and use it in GitHub Desktop.
100DaysOfCode Traffic Light challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 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