Skip to content

Instantly share code, notes, and snippets.

@agosmou
Created December 10, 2023 00:19
Show Gist options
  • Save agosmou/ed51caa68964e0354755ffbb2bdfe1bb to your computer and use it in GitHub Desktop.
Save agosmou/ed51caa68964e0354755ffbb2bdfe1bb to your computer and use it in GitHub Desktop.
Hand Rolling State Machine (Traffic Light Example)

Hand Rolling State Machine (Traffic Light Example)

Handroll

This is to get a general idea of what handrolling could look like:

  • Statechart Pattern
    • states
    • triggers
    • transitions
# database.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class TrafficLight(Base):
    __tablename__ = 'traffic_lights'

    id = Column(Integer, primary_key=True)
    state = Column(String)

# Setup the database connection and session
engine = create_engine('sqlite:///traffic_lights.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
# state_machine.py
from database import TrafficLight, Session
from enum import Enum

class TrafficLightStates(Enum):
    GREEN = 'Green'
    YELLOW = 'Yellow'
    RED = 'Red'

class TrafficLightMachine:
    def __init__(self, traffic_light_id):
        self.session = Session()
        self.traffic_light = self.session.query(TrafficLight).get(traffic_light_id)
        if not self.traffic_light:
            raise ValueError("Traffic Light not found")

    def change_state(self, new_state):
        print(f"Changing from {self.traffic_light.state} to {new_state}")
        self.traffic_light.state = new_state
        self.session.commit()

    def to_yellow(self):
        self.change_state(TrafficLightStates.YELLOW.value)

    def to_red(self):
        self.change_state(TrafficLightStates.RED.value)

    def to_green(self):
        self.change_state(TrafficLightStates.GREEN.value)

# Example usage
# traffic_light_machine = TrafficLightMachine(traffic_light_id=1)
# traffic_light_machine.to_yellow()
# traffic_light_machine.to_red()
# traffic_light_machine.to_green()

Alternatives to Consider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment