Skip to content

Commit

Permalink
Changed inventory to be nested dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
vidoardes committed Nov 4, 2016
1 parent b8b968f commit ca47eeb
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 59 deletions.
2 changes: 1 addition & 1 deletion save_the_girl/src/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_available_actions(self, room, player, list_available_actions):
self.action_adder(actions, 't', self.player.trade)
list_available_actions['t'] = '(T)rade'

if player.curr_hp < 100:
if player.curr_hp < player.max_hp:
self.action_adder(actions, 'h', self.player.heal)
list_available_actions['h'] = '(H)eal up'

Expand Down
25 changes: 16 additions & 9 deletions save_the_girl/src/npc.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,34 @@ def __init__(self):
self.name = "Trader"
self.gold = random.randint(70, 150)

self.inventory = []
self.inventory = {"Items": {}}

crusty_bread_qty = random.randint(1, 4)
potion_qty = random.randint(1, 3)
hi_potion_qty = random.randint(1, 2)

for i in range(crusty_bread_qty):
self.inventory.append(items.CrustyBread())
self.inventory["Items"]["Crusty Bread"] = {}
self.inventory["Items"]["Crusty Bread"]["obj"] = items.CrustyBread()
self.inventory["Items"]["Crusty Bread"]["qty"] = crusty_bread_qty

item_picker = random.randint(1, 10)

if item_picker > 3:
for i in range(potion_qty):
self.inventory.append(items.Potion())
self.inventory["Items"]["Potion"] = {}
self.inventory["Items"]["Potion"]["obj"] = items.Potion()
self.inventory["Items"]["Potion"]["qty"] = potion_qty

if item_picker > 5:
for i in range(hi_potion_qty):
self.inventory.append(items.HiPotion())
self.inventory["Items"]["Hi-Potion"] = {}
self.inventory["Items"]["Hi-Potion"]["obj"] = items.HiPotion()
self.inventory["Items"]["Hi-Potion"]["qty"] = hi_potion_qty

if item_picker > 8:
self.inventory.append(items.XPotion())
self.inventory["Items"]["X-Potion"] = {}
self.inventory["Items"]["X-Potion"]["obj"] = items.XPotion()
self.inventory["Items"]["X-Potion"]["qty"] = 1

if item_picker == 10:
self.inventory.append(weapons.RustySword())
self.inventory["Weapons"]["Rusty sword"] = {}
self.inventory["Weapons"]["Rusty sword"]["obj"] = weapons.RustySword()
self.inventory["Weapons"]["Rusty sword"]["qty"] = 1
88 changes: 60 additions & 28 deletions save_the_girl/src/player.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
"""Create player entity and define player actions"""

import os
import json
import random
import decimal

import src.weapons as weapons
import src.items as items
import src.world as world
import src.weapons as weapons


class Player:
def __init__(self):
self.room = None
self.base_class = 'Knight'
self.inventory = [weapons.Rock(),
items.CrustyBread()]
self.name = "Unnamed Soldier"
self.base_class = "Knight"
self.inventory = {
"Weapons": {
"Rock": {"obj": weapons.Rock(), "qty": 1}
},
"Items": {
"Crusty Bread": {"obj": items.CrustyBread(), "qty": 1}
}
}
self.x = world.start_tile_location[0]
self.y = world.start_tile_location[1]
self.curr_hp = 100
Expand Down Expand Up @@ -54,12 +62,13 @@ def print_inventory(self):
os.system('cls')
print("{}'s Inventory:".format(self.base_class))
print("{} / {} HP".format(self.curr_hp, self.max_hp))
print("----------")
print("----------\n")

for item in self.inventory:
print(' * ' + str(item))
for item_cat, item_attr in self.inventory['Items'].items():
if item_attr["qty"] > 0:
print(' * {} x{}'.format(item_cat, item_attr["qty"]))

print('\nGold: {}'.format(self.gold))
print('\n{} Gold'.format(self.gold))

best_weapon = self.most_powerful_weapon()
print('Best Weapon: {} ({} damage)'.format(best_weapon, best_weapon.damage))
Expand All @@ -68,11 +77,11 @@ def most_powerful_weapon(self):
max_damage = 0
best_weapon = None

for item in self. inventory:
for weapon_cat, weapon_attr in self.inventory['Weapons'].items():
try:
if item.damage > max_damage:
best_weapon = item
max_damage = item.damage
if weapon_attr["obj"].damage > max_damage:
best_weapon = weapon_attr["obj"]
max_damage = weapon_attr["obj"].damage
except AttributeError:
pass

Expand Down Expand Up @@ -116,45 +125,68 @@ def attack(self):

if enemy.name == "Goblin" and random.randrange(1, 3) == 2:
print("They also dropped their dagger. Sweet!")
self.inventory.append(weapons.Dagger())

if weapons.Dagger.name in self.inventory['Weapons'].items():
for weapon_cat, weapon_attr in self.inventory['Weapons'].items():
if item_cat == weapons.Dagger.name:
item_attr["qty"] += 1
else:
self.inventory['Weapons'][weapons.Dagger.name] = {}
self.inventory['Weapons'][weapons.Dagger.name]['obj'] = weapons.Dagger
self.inventory['Weapons'][weapons.Dagger.name]['qty'] = 1

if enemy.name == "Rock Monster" and random.randrange(1, 3) == 2:
print("They also dropped their heavy axe. Sweet!")
self.inventory.append(weapons.Dagger())

if weapons.HeavyAxe.name in self.inventory['Weapons'].items():
for weapon_cat, weapon_attr in self.inventory['Weapons'].items():
if item_cat == weapons.HeavyAxe.name:
item_attr["qty"] += 1
else:
self.inventory['Weapons'][weapons.Dagger.name] = {}
self.inventory['Weapons'][weapons.Dagger.name]['obj'] = weapons.HeavyAxe
self.inventory['Weapons'][weapons.Dagger.name]['qty'] = 1
else:
print("{} HP is {}.".format(enemy.name, enemy.hp))

def heal(self):
consumables = [item for item in self.inventory if isinstance(item, items.Consumable)]
heal_choice = None
consumables = []

if not consumables:
print("\nYou don't have any items to heal you!\n")
return
for item_cat, item_attr in self.inventory['Items'].items():
if isinstance(item_attr["obj"], items.Consumable) and item_attr['qty'] > 0:
consumables.append(item_attr["obj"])

print("\nHealing Items")
print("----------------\n")

for i, item in enumerate(consumables, 1):
print(" {}: {}".format(i, item))
if not consumables:
print("You don't have any items to heal you!")
else:
for i, item in enumerate(consumables, 1):
print(" {}: {}".format(i, item.name))

print(" q: Back to battle")
valid = False
print("\nq: Back to battle")

while heal_choice not in consumables:
heal_choice = input("\nWhich item do you want to use?: ")

if heal_choice == 'q':
if heal_choice in ['Q', 'q']:
self.room.visited = 0
return
else:
try:
to_eat = consumables[int(choice) - 1]
to_eat = consumables[int(heal_choice) - 1]
self.curr_hp = min(self.max_hp, self.curr_hp + to_eat.healing_value)
self.inventory.remove(to_eat)
print("Current HP: {}".format(self.curr_hp))
valid = True
for item_cat, item_attr in self.inventory['Items'].items():
if item_cat == item.name:
item_attr["qty"] -= 1
self.room.visited = 0
return

print("HP: {} / {}".format(self.curr_hp, self.max_hp))
except (ValueError, IndexError):
print("Invalid choice, try again.")
print("Invalid choice!")

def trade(self):
room = self.room
Expand Down
80 changes: 59 additions & 21 deletions save_the_girl/src/world.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import random
import decimal

import src.enemies as enemies
import src.npc as npc
import src.enemies as enemies


class MapTile:
Expand Down Expand Up @@ -157,38 +157,73 @@ def __init__(self, x, y):
super().__init__(x, y)

def trade(self, buyer, seller):
if len(seller.inventory) == 0:
return
if buyer.name == "Trader":
action = "sell"
buyer_char = "Trader"
else:
action = "buy"
buyer_char = "Player"

for i, item in enumerate(seller.inventory, 1):
print("{}. {} - {} Gold".format(i, item.name, item.value))
seller_inventory = []
item_choice = None

while True:
if len(seller.inventory) == 0:
return
for item_cat, item_attr in seller.inventory['Items'].items():
if item_attr["qty"] > 0:
seller_inventory.append(item_attr["obj"])

user_input = input("\nChoose an item or press Q to exit: ")
print("\nTrading Items")
print("----------------\n")

if not seller_inventory:
print("There are no items to sell!")
else:
for i, item in enumerate(seller_inventory, 1):
print(" {}: {}".format(i, item.name))

print("\nq: Cancel trade")

while item_choice not in seller_inventory:
item_choice = input("\nWhich item do you want to {}? ".format(action))

if item_choice in ['Q', 'q']:
if buyer_char == "Player":
buyer.room.visited = 0
else:
seller.room.visited = 0

if user_input in ['Q', 'q']:
return
else:
try:
choice = int(user_input)
if choice > len(seller.inventory) or choice < 1:
print("Invalid choice!")
else:
to_swap = seller.inventory[choice - 1]
self.swap(seller, buyer, to_swap)
except ValueError:
to_swap = seller_inventory[int(item_choice) - 1]
self.swap(seller, buyer, to_swap)
except (ValueError, IndexError):
print("Invalid choice!")

def swap(self, seller, buyer, item):
if buyer.name == "Trader":
action = "sell"
buyer_char = "Trader"
else:
action = "buy"
buyer_char = "Player"

if item.value > buyer.gold:
print("That's too expensive")
return
print("That's too expensive!")
self.trade(buyer, seller)

for item_cat, item_attr in seller.inventory['Items'].items():
if item_cat == item.name:
item_attr["qty"] -= 1

if item.name in buyer.inventory['Items'].items():
for item_cat, item_attr in buyer.inventory['Items'].items():
if item_cat == item.name:
item_attr["qty"] += 1
else:
buyer.inventory['Items'][item.name] = {}
buyer.inventory['Items'][item.name]['obj'] = item
buyer.inventory['Items'][item.name]['qty'] = 1

seller.inventory.remove(item)
buyer.inventory.append(item)
seller.gold = seller.gold + item.value
buyer.gold = buyer.gold - item.value
print("Trade complete!")
Expand All @@ -197,12 +232,15 @@ def check_if_trade(self, player):
while True:
if len(self.trader.inventory) == 0:
print("No items to trade!")
player.room.visited = 0
return

user_input = input("Would you like to (B)uy, (S)ell, or (Q)uit?: ")

if user_input in ['Q', 'q']:
player.room.visited = 0
return

elif user_input in ['B', 'b']:
print("Here's whats available to buy:\n")
self.trade(buyer=player, seller=self.trader)
Expand Down

0 comments on commit ca47eeb

Please sign in to comment.