ÿØÿà JFIF ` ` ÿþxØ
| Server IP : 109.234.164.53 / Your IP : 216.73.216.110 Web Server : Apache System : Linux cervelle.o2switch.net 4.18.0-553.32.1.lve.el8.x86_64 #1 SMP Thu Dec 19 13:14:03 UTC 2024 x86_64 User : computer3 ( 1098) PHP Version : 7.1.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : OFF | Pkexec : OFF Directory : /opt/alt/python37/share/doc/alt-python37-pyparsing-doc/examples/statemachine/ |
Upload File : |
#
# vending_machine.py
#
# Example of using the statemachine parser without importing a .pystate module.
#
# A vending machine that dispenses candy and chips in a 4x4 grid, A1 thru D4.
# To dispense a product, you must press an alpha button, then a digit button.
#
import statemachine
# Vending machine buttons:
# A, B, C, D
# 1, 2, 3, 4
#
vending_machine_state_description = """\
statemachine VendingMachineState:
Idle-(press_alpha_button)->WaitingOnDigit
WaitingOnDigit-(press_alpha_button)->WaitingOnDigit
WaitingOnDigit-(press_digit_button)->DispenseProduct
DispenseProduct-(dispense)->Idle
"""
# convert state machine text to state classes
generated = statemachine.namedStateMachine.transformString(
vending_machine_state_description
)
# print(generated)
# exec generated code to define state classes and state mixin
exec(generated)
class VendingMachine(VendingMachineStateMixin):
def __init__(self):
self.initialize_state(Idle)
self._pressed = None
self._alpha_pressed = None
self._digit_pressed = None
def press_button(self, button):
if button in "ABCD":
self._pressed = button
self.press_alpha_button()
elif button in "1234":
self._pressed = button
self.press_digit_button()
else:
print("Did not recognize button {!r}".format(str(button)))
def press_alpha_button(self):
try:
super().press_alpha_button()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
self._alpha_pressed = self._pressed
def press_digit_button(self):
try:
super().press_digit_button()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
self._digit_pressed = self._pressed
self.dispense()
def dispense(self):
try:
super().dispense()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
print("Dispensing at {}{}".format(self._alpha_pressed, self._digit_pressed))
self._alpha_pressed = self._digit_pressed = None
vm = VendingMachine()
for button in "1 A B 1".split():
print(">> pressing {!r}".format(button))
vm.press_button(button)
print("Vending machine is now in {} state".format(vm.state))