Python编程快速上手 实践项目

Python编程快速上手 实践第五章

5.6.1 好玩游戏的物品清单

你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物品。

例如,字典值 {‘rope’: 1, ‘torch’: 6, ‘gold coin’: 42, ‘dragger’: 1, ‘arrow’: 12}意味着玩家有1条绳索、6个火把、42枚金币等。

写一个名为displayInventory()的函数,它接受任何可能的物品清单,并显示如下:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items:62

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dragger': 1, 'arrow': 12}
def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    # print(inventory.items())  # dict_items以列表([***])的形式列出(里面是元组(***))
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print('Total number of items: ' + str(item_total))
displayInventory(stuff)

5.6.2 战利品获取

假设征服一条龙的战利品表示为这样的字符串列表:

dragonLoot=['gold coin', 'dagger', 'goldcoin', 'gold coin', 'ruby']

写一个名为addToInventory(inventory,addedItems)的函数,其中inventory参数是一个字典,表示玩家的物品清单(像前面项目一样),addedItems参数是一个列表,就像dragonLoot。

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dragger': 1, 'arrow': 12}


def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    # print(inventory.items())  # dict_items以列表([***])的形式列出(里面是元组(***))
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print('Total number of items: ' + str(item_total))


# displayInventory(stuff)


def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i] += 1
    return inventory


inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

猜你喜欢

转载自blog.csdn.net/yht493508433/article/details/83544130
今日推荐