|
| 1 | +# game_inventory.py |
| 2 | + |
| 3 | +# We demonstrate some ways to display, add and remove |
| 4 | +# items from a player's inventory in a fantasy game. |
| 5 | + |
| 6 | + |
| 7 | +def display_inventory(inventory={}): |
| 8 | + print('\n- - - - - - - - - -') |
| 9 | + print('INVENTORY: \n') # Print title |
| 10 | + count = 0 # Initialize counter variable |
| 11 | + |
| 12 | + if (inventory != {}): # CASE: Nonempty Inventory |
| 13 | + for key, val in inventory.items(): |
| 14 | + count += val |
| 15 | + if (val > 1): key += 's' # Handle plurals |
| 16 | + |
| 17 | + as_string = '{num} {name}'.format(num=val, name=key) |
| 18 | + print(as_string) |
| 19 | + else: # CASE: Empty Inventory |
| 20 | + print(' (empty) ') |
| 21 | + |
| 22 | + weight_msg = ' (Things are getting pretty heavy.)' if (count > 400) else '' # Conditional weight comment. |
| 23 | + print("\nTotal number of items: " + str(count) + weight_msg) # Always print the total. |
| 24 | + print('\n- - - - - - - - - -\n\n') |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +def add_items(inventory={}, add_list=[]): |
| 29 | + if (add_list != []): # CASE: Nonempty list |
| 30 | + for item in add_list: # Iterate through each item in the list |
| 31 | + if item not in inventory.keys(): ## CASE: New type of item |
| 32 | + inventory[item] = 1 |
| 33 | + else: ## CASE: Item of this type already exist. |
| 34 | + inventory[item] += 1 |
| 35 | + |
| 36 | + else: pass # CASE: Empty list |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +def remove_items(inventory={}, remove_list=[]): |
| 41 | + if (remove_list != []): # CASE: Nonempty list |
| 42 | + for item in remove_list: # Iterate through each item in the list |
| 43 | + if item not in inventory.keys(): ## CASE: No such item in the inventory. |
| 44 | + continue |
| 45 | + else: ## CASE: Item of this type exists, and one was removed. |
| 46 | + inventory[item] -= 1 |
| 47 | + if (inventory[item] == 0): # Delete items with zero inventory. |
| 48 | + del inventory[item] |
| 49 | + |
| 50 | + else: pass # CASE: Empty list |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +# SOME TESTS COMMENTED BELOW: |
| 55 | +''' |
| 56 | +empty = {} |
| 57 | +basic = { 'rope': 1, 'arrow': 12, 'gold coin': 25, 'fire stick': 5, 'dagger': 1 } |
| 58 | +advanced = { 'rope': 8, 'arrow': 42, 'gold coin': 312, 'fire stick': 18, 'dagger': 11, 'helmet': 5, |
| 59 | + 'glove': 7, 'shield potion': 11, 'health potion': 7, 'elixir': 2, 'orb of confusion': 1, |
| 60 | + 'label maker': 1, 'label': 4, 'cookie': 5 } |
| 61 | +
|
| 62 | +display_inventory(empty) |
| 63 | +add_items(empty, ['rope', 'gold coin', 'twig', 'dirt', 'pebble', 'gold coin', 'gold coin']) |
| 64 | +display_inventory(empty) |
| 65 | +
|
| 66 | +display_inventory(advanced) |
| 67 | +remove_items(advanced, ['rope', 'arrow', 'arrow', 'label', 'health potion', 'arrow', 'fire stick', 'cookie']) |
| 68 | +display_inventory(advanced) |
| 69 | +''' |
0 commit comments