Part 7: Show inventory
Contents
Part 7: Show inventory#
In this section we’ll add the inventory command.
Part 7.1: Add command#
In this section we’ll define a do_inventory() function that gets called when the
player types i, or inventory.
Demo
A: Define do_inventory()#
[ ]Define ado_inventory()function.[ ]In it, use thedebug()function to print something like"Trying to show inventory.".
Code
299def do_inventory():
300 """Show the players inventory"""
301
302 debug("Trying to show inventory.")
B: Modify main(), in the while loop#
[ ]Add anelifthat checks ifcommandis"i", or"inventory".[ ]if so, calldo_inventory()
Code
319 if command in ["q", "quit", "exit"]:
320 do_quit()
321
322 elif command in ("shop"):
323 do_shop()
324
325 elif command in ("g", "go"):
326 do_go(args)
327
328 elif command in ("x", "exam", "examine"):
329 do_examine(args)
330
331 elif command in ("l", "look"):
332 do_look()
333
334 elif command in ("t", "take", "grab"):
335 do_take(args)
336
337 elif command in ("i", "inventory"):
338 do_inventory()
339
340 else:
341 error("No such command.")
342 continue
Part 7.2: Print inventory#
In this section we’ll print the players inventory.
Demo
A: Modify do_inventory()#
[ ]Use theheader()function to print"Inventory"[ ]IfPLAYER["inventory"]is falsy:[ ]use thewrite()function to print"Empty."
[ ]Iterate over the results of.items()onPLAYER["inventory"]using the variablesnameandqty.[ ]Get the value associated with thenamekey fromITEMSand assign it toitem.[ ]Use thewrite()function to print theqtyanditem["name"]
[ ]Print a blank line
Code
299def do_inventory():
300 """Show the players inventory"""
301
302 debug("Trying to show inventory.")
303
304 header("Inventory")
305
306 if not PLAYER["inventory"]:
307 write("Empty.")
308
309 for name, qty in PLAYER["inventory"].items():
310 item = ITEMS.get(name)
311 write(f"(x{qty:>2}) {item['name']}")
312
313 print()