用python写一个自动贩卖机有限状态机
时间: 2024-05-11 11:18:46 浏览: 249
好的,下面是一个简单的自动贩卖机有限状态机的 Python 代码:
```python
class VendingMachine:
def __init__(self):
self.balance = 0
self.items = {
"cola": {"price": 1.5, "quantity": 10},
"chips": {"price": 1, "quantity": 5},
"candy": {"price": 0.5, "quantity": 2}
}
self.current_state = self.idle_state
def idle_state(self):
print("Welcome to the vending machine!")
print("Please insert coins or select an item.")
print(f"Current balance: {self.balance} dollars.\n")
action = input("Enter coin amount or item name: ")
if action in self.items:
self.current_state = self.item_selected_state
self.selected_item = action
else:
self.balance += float(action)
def item_selected_state(self):
item = self.items[self.selected_item]
if item["quantity"] == 0:
print(f"Sorry, {self.selected_item} is sold out.")
self.current_state = self.idle_state
elif self.balance < item["price"]:
print("Insufficient funds. Please insert more coins.")
self.current_state = self.idle_state
else:
self.balance -= item["price"]
item["quantity"] -= 1
print(f"Thank you for purchasing {self.selected_item}!")
print(f"Your change is {self.balance} dollars.")
self.current_state = self.idle_state
def run(self):
while True:
self.current_state()
```
这个自动贩卖机有三种商品(cola, chips, candy),并且可以接受硬币。在初始状态下,它会提示用户插入硬币或选择商品。如果用户选择了商品,它会进入“item_selected_state”,检查商品是否有库存,用户是否有足够的余额,并且发出购买成功的消息。购买成功后,它会返回“idle_state”并等待下一个操作。如果商品没有库存或余额不足,它会返回“idle_state”并提示用户。你可以调用 `VendingMachine().run()` 来运行这个自动贩卖机。
阅读全文