Python: List to Dictionary Function for Fantasy Game Inventory

本文介绍如何使用Python进行游戏内物品库存的管理和展示。通过定义两个函数:displayInventory()用于显示玩家当前拥有的物品及数量;addToInventory()则用于将新获取的物品加入到玩家的库存中,并更新库存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习《Python编程快速上手》P93

问题链接:https://automatetheboringstuff.com/chapter5/

Fantasy Game Inventory

You are creating a fantasy video game. The data structure to model the player’s inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on.

Write a function named displayInventory() that would take any possible “inventory” and display it like the following:

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

List to Dictionary Function for Fantasy Game Inventory

Imagine that a vanquished dragon’s loot is represented as a list of strings like this:

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

Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item.

The previous program (with your displayInventory() function from the previous project) would output the following:

Inventory:
45 gold coin
1 rope
1 ruby
1 dagger

Total number of items: 48

代码实现: (书本中已给出代码的大致框架)

#  Problem: List to Dictionary Function for Fantasy Game Inventory
#  The url of the problem: https://automatetheboringstuff.com/chapter5/

def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print('\nTotal number of items: ' + str(item_total))
    
def addToInventory(inventory, addedItems):
    for Item in addedItems:
        inventory.setdefault(Item,0)
        inventory[Item] += 1
    return inventory

# inventory and addedItems
inv = {'gold coin': 42, 'rope': 1}
dragonloot = ['gold coin', 'dragger', 'gold coin', 'gold coin', 'ruby'] 

# Update the inventory
inv = addToInventory(inv, dragonloot)
displayInventory(inv)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值