Skip to content

Instantly share code, notes, and snippets.

@wotori
Last active May 20, 2021 16:03
Show Gist options
  • Save wotori/2e4aae7850eb41052be9c8d79cfaa803 to your computer and use it in GitHub Desktop.
Save wotori/2e4aae7850eb41052be9c8d79cfaa803 to your computer and use it in GitHub Desktop.
FSM

Finite State Machine based on youtube video
The same solution splited to modules is here

from random import randint
from time import sleep

# _____________________________________________________
State = type("State", (object,), {})


class LightOn(State):

    @staticmethod
    def execute():
        print("Light is on")


class LightOff(State):

    @staticmethod
    def execute():
        print("Light is off")


# _____________________________________________________
class Transition(object):
    def __init__(self, to_state):
        self.to_state = to_state

    @staticmethod
    def execute():
        print("Transitioning")


# _____________________________________________________
class FSM(object):
    def __init__(self, asset_obj):
        self.asset_obj = asset_obj
        self.states = {}
        self.transitions = {}
        self.cur_state = None
        self.transition = None

    def set_state(self, state_name):
        self.cur_state = self.states[state_name]

    def switch_transition(self, transition_name):
        self.transition = self.transitions[transition_name]

    def execute(self):
        if self.transition:
            self.transition.execute()
            self.set_state(self.transition.to_state)
            self.transition = None
        self.cur_state.execute()


# _____________________________________________________

class Lamp(object):
    def __init__(self):
        self.FSM = FSM(self)
        self.light_on = True


if __name__ == '__main__':
    light = Lamp()

    light.FSM.states["on"] = LightOn()
    light.FSM.states["off"] = LightOff()

    light.FSM.transitions["to_on"] = Transition("on")
    light.FSM.transitions["to_off"] = Transition("off")

    light.FSM.set_state("on")

    for i in range(20):
        if randint(0, 2):
            if light.light_on:
                light.FSM.switch_transition("to_off")
                light.light_on = False
            else:
                light.FSM.switch_transition("to_on")
                light.light_on = True
        light.FSM.execute()
        sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment