Python 好玩遊戲的物品清單

Python編程快速上手實踐項目題目,歡迎指證與優化!
你在創建一個好玩的視頻遊戲。用於對玩家物品清單建模的數據結構是一個字
典。其中鍵是字符串,描述清單中的物品,值是一個整型值,說明玩家有多少該物
品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味着玩
家有 1 條繩索、 6 個火把、 42 枚金幣等。
寫一個名爲 displayInventory()的函數,它接受任何可能的物品清單, 並顯示如下:

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():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
displayInventory(stuff)

運行結果:

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

列表到字典的函數,針對好玩遊戲物品清單
假設征服一條龍的戰利品表示爲這樣的字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
寫一個名爲 addToInventory(inventory, addedItems)的函數, 其中 inventory 參數
是一個字典, 表示玩家的物品清單(像前面項目一樣), addedItems 參數是一個列表,
就像 dragonLoot。
addToInventory()函數應該返回一個字典, 表示更新過的物品清單。請注意, 列
表可以包含多個同樣的項。你的代碼看起來可能像這樣:

def addToInventory(inventory, addedItems):
# your code goes here

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

新代碼:

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():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
#displayInventory(stuff)

def addToInventory(inventory, addedItems):
# your code goes here
    for i in addedItems:
        if i in inventory.keys():
            inventory[i] += 1
        else:
            inventory.setdefault(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)

運行結果:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章