Skip to content

Instantly share code, notes, and snippets.

@OhadRubin
Created January 8, 2023 16:40
Show Gist options
  • Save OhadRubin/ce1c1c137b3f68bb30c6e52594a0d0a8 to your computer and use it in GitHub Desktop.
Save OhadRubin/ce1c1c137b3f68bb30c6e52594a0d0a8 to your computer and use it in GitHub Desktop.
Robot state machine
from transitions import Machine
import random
import numpy as np
class RobotModel(object):
# Define some states. Most of the time, narcoleptic superheroes are just like
# everyone else. Except for...
states = ['LeftY', 'LeftN', 'MidY', 'MidN', 'RightY','RightN']
def __init__(self):
# Initialize the state machine
self.machine = Machine(model=self, states=RobotModel.states, initial='RightN')
#RightN
self.machine.add_transition(trigger='picked_up_page', source='RightN', dest='RightY')
#RightY
self.machine.add_transition('moved_to_middle_w_page', 'RightY', 'MidY')
#MidN
self.machine.add_transition('moved_to_start', 'MidN', 'RightN')
#MidY
self.machine.add_transition('dropped_page', 'MidY', 'MidN')
self.machine.add_transition('moved_to_left_w_page', 'MidY', 'LeftY')
#LeftY
self.machine.add_transition('released_page', 'LeftY', 'LeftN')
#LeftN
self.machine.add_transition('moved_to_middle_wo_page', 'LeftN', 'MidN')
def step(self):
print(self.state)
if self.state=="RightN":
if random.random() < 0.5:
print("picked_up_page")
self.picked_up_page()
if self.state=="RightY":
if random.random() < 0.5:
print("moved_to_middle_w_page")
self.moved_to_middle_w_page()
if self.state=="MidY":
action = np.random.choice(["Stay","Drop","Move"],p=[0.4,0.4,0.2])
if action=="Drop":
print("dropped_page")
self.dropped_page()
if action=="Move":
print("moved_to_left_w_page")
self.moved_to_left_w_page()
if self.state=="MidN":
if random.random() < 0.5:
print("moved_to_start")
self.moved_to_start()
if self.state=="LeftY":
if random.random() < 0.5:
print("released_page")
self.released_page()
if self.state=="LeftN":
if random.random() < 0.5:
print("moved_to_middle_wo_page")
self.moved_to_middle_wo_page()
import time
robot = RobotModel()
while True:
time.sleep(0.1)
robot.step()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment