当前位置:嗨网首页>书籍在线阅读

16-好玩游戏的物品清单

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

5.6.2 好玩游戏的物品清单

创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,用于描述清单中的物品;值是一个整型值,用于说明玩家有多少该物品。例如,字典值 {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} 意味着玩家有1条绳索、6个火把、42枚金币等。

编写一个名为 displayInventory() 的函数,它接收任何可能的物品清单,显示如下:

Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62

提示: 你可以使用 for 循环遍历字典中所有的键。

# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        # FILL THIS PART IN
    print("Total number of items: " + str(item_total))
displayInventory (stuff)