Skip to content

Instantly share code, notes, and snippets.

@Pinacolada64
Created May 3, 2024 02:28
Show Gist options
  • Save Pinacolada64/9e64503926fd92046f6148d50c29709a to your computer and use it in GitHub Desktop.
Save Pinacolada64/9e64503926fd92046f6148d50c29709a to your computer and use it in GitHub Desktop.
Shop routine, maintain shop and player inventory (with item quantities)
import logging
from dataclasses import dataclass, field
@dataclass
class ShopItem:
name: str
quantity: int
price: int
def remove_inventory(self):
if self.quantity == 0:
print("There are none left.")
return
else:
self.quantity -= 1
logging.info(f"{self.quantity=}")
def __str__(self):
return f"({self.quantity:2}x) {self.name:<20} ${self.price:,<}"
@dataclass
class InventoryItem:
name: str
quantity: int
def find_by_name(self, item_to_find: str):
return self.name == item_to_find
def __str__(self):
return f"({self.quantity:2}x) {self.name:<20}"
@dataclass
class Player:
money: int
inventory: list[InventoryItem] = field(default_factory=InventoryItem)
def add_to_inventory(self, item_name: str, item_quantity: int):
logging.info(f"{item_name in self.inventory=}")
# thanks, google gemini for this bit:
item_found = False
for item in self.inventory:
if item.name == item_name:
item.quantity += item_quantity
item_found = True
break
# Only add a new entry if the item wasn't found
if not item_found:
self.inventory.append(InventoryItem(item_name, item_quantity))
if __name__ == '__main__':
# initialize logging:
logging.basicConfig(level="DEBUG")
shop_items = [ShopItem('Banana', 10, 2),
ShopItem('Strawberry', 5, 4),
ShopItem('Apple', 7, 6),
ShopItem("Magic Wand", 1, 1000)]
rulan = Player(money=1000, inventory=[InventoryItem('Banana', 2)])
print('\nYou are in the shop.')
while True:
print('\nWhat would you like to buy?\n')
for num, item in enumerate(shop_items, start=1):
# Item.__str__ method handles printing fancy item listing:
print(f"{num:3}. {item}")
print(" B. Account balance")
print(" I. Inventory")
print(" Q. Quit")
choice = input(f"\nWhich item [1-{len(shop_items)}]? ")
print()
if choice.lower() == "q":
print("Bye!")
break
elif choice.lower() == 'b':
print(f'You have ${rulan.money:,}.')
continue
elif choice.lower() == 'i':
if rulan.inventory:
print('Inventory:')
for i, item in enumerate(rulan.inventory, start=1):
print(f"{i:3}. {item}")
else:
print("You are carrying nothing.")
continue
else:
# purchase a numbered item:
option = int(choice) - 1
if option in range(len(shop_items)):
"""
>>> shop_items[option].name
'Magic Wand'
"""
purchase = shop_items[option]
if purchase.price > rulan.money:
print("You cannot afford that!")
continue
elif purchase.price <= rulan.money:
# TODO: implement buying more than one at once
purchase.remove_inventory()
rulan.add_to_inventory(purchase.name, 1)
rulan.money -= purchase.price
else:
print("That is not available!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment