上一节我们用列表做了基础背包系统,已经可以存道具、看道具、用药水了。今天我们继续升级:学习字典(dict),把“道具名字”和“道具功能”绑定起来,完成项目 v2.0!
课程目录
一、回顾:列表背包系统的核心点
上节课我们主要使用了列表:
# Lesson 5 的核心思路(简化版)backpack = ["potion", "axe"]print("背包:")for item in backpack: print("-", item)if "potion" in backpack: backpack.remove("potion") print("你使用了 potion")
问题来了:如果我们想让不同道具有不同效果,光靠列表就不够方便了。因为列表只适合“存东西”,不擅长“描述东西的属性和功能”。
二、为什么需要字典?
字典就像一本“道具说明书”:你给它一个名字(键 key),它就能告诉你对应的信息(值 value)。
字典核心:键值对(key-value)
例如:"potion" -> "恢复生命","axe" -> "造成攻击"
# 一个最简单的字典item_effects = { "potion": "恢复30点生命", "axe": "造成10点伤害", "hammer": "造成15点伤害", "shield": "减少下次伤害"}print(item_effects["potion"]) # 输出:恢复30点生命
三、字典基础:创建、访问、修改
3.1 创建字典
item_db = { "potion": {"desc": "小型恢复药水", "type": "heal", "value": 30}, "axe": {"desc": "木斧", "type": "attack", "value": 10}, "hammer": {"desc": "铁锤", "type": "attack", "value": 15}, "shield": {"desc": "木盾", "type": "defense", "value": 1}}
3.2 访问字典
print(item_db["axe"]) # 取出 axe 的整条信息print(item_db["axe"]["desc"]) # 取出 axe 的描述print(item_db["potion"]["value"]) # 取出 potion 的数值
3.3 修改和新增
# 修改已有数据item_db["potion"]["value"] = 35# 新增一个道具item_db["apple"] = {"desc": "苹果", "type": "heal", "value": 10}
3.4 删除
# 删除一个键值对del item_db["apple"]
四、字典遍历与 get() 方法
4.1 遍历字典
# 方式1:遍历键for item_name in item_db: print(item_name)# 方式2:遍历键和值for item_name, info in item_db.items(): print(item_name, "=>", info["desc"])
4.2 get() 方法(重点)
如果直接访问一个不存在的键,会报错;get() 可以更安全。
# 直接访问(可能报错)# print(item_db["sword"])# 安全访问(不存在返回 None)print(item_db.get("sword"))
新手建议:只要你不确定一个键是否存在,就优先用 get()。
五、项目 v2.0:道具功能映射系统(完整代码)
下面是本节课完整可运行代码。考虑到我们还没学函数,这里使用纯主循环 + if/elif 的写法,一样可以实现完整功能。
import random# 玩家基础状态player_hp = 100player_attack = 5# 背包(列表,沿用上节课)backpack = ["potion", "axe", "shield"]# 道具数据库(字典,本节课新增)item_db = { "potion": {"desc": "小型恢复药水", "type": "heal", "value": 30}, "axe": {"desc": "木斧", "type": "attack", "value": 10}, "hammer": {"desc": "铁锤", "type": "attack", "value": 15}, "shield": {"desc": "木盾", "type": "defense", "value": 1}}while True: print("====== 冒险菜单 v2.0 ======") print("1. 外出探索") print("2. 查看背包") print("3. 使用道具") print("4. 查看状态") print("5. 退出游戏") print("===========================") choice = input("请输入选择:").strip() if choice == "1": drops = ["potion", "axe", "hammer", "shield"] got_item = random.choice(drops) backpack.append(got_item) print(f"你探索后获得道具:{got_item}") elif choice == "2": if not backpack: print("背包是空的") else: print("【当前背包】") for idx, item_name in enumerate(backpack, start=1): info = item_db.get(item_name, {"desc": "未知道具"}) print(f"{idx}. {item_name} - {info['desc']}") elif choice == "3": if not backpack: print("背包是空的") print() continue print("【当前背包】") for idx, item_name in enumerate(backpack, start=1): info = item_db.get(item_name, {"desc": "未知道具"}) print(f"{idx}. {item_name} - {info['desc']}") target = input("请输入要使用的道具名:").strip().lower() if target not in backpack: print("你背包里没有这个道具") else: info = item_db.get(target) if info is None: print("这个道具没有配置功能") else: item_type = info["type"] item_value = info["value"] if item_type == "heal": player_hp += item_value print(f"你使用了 {target},恢复 {item_value} 点生命。当前生命:{player_hp}") backpack.remove(target) elif item_type == "attack": player_attack += item_value print(f"你装备了 {target},攻击 +{item_value}。当前攻击:{player_attack}") backpack.remove(target) elif item_type == "defense": print(f"你使用了 {target},获得一次防御效果。") backpack.remove(target) else: print("这个道具暂时没有可用效果") elif choice == "4": print(f"生命:{player_hp} | 攻击:{player_attack} | 背包数量:{len(backpack)}") elif choice == "5": print("游戏结束,欢迎下次再来。") break else: print("输入错误,请重新输入。") print()
六、课堂练习
练习1:功能描述补全
给 axe 和 hammer 增加更清晰的功能提示,例如:“砍树更快”“破石头更快”。
练习2:道具伤害值属性
给攻击类道具增加 damage 字段,并在使用时输出“本次额外伤害”。
练习3:安全访问改造
把代码里直接访问字典的地方,尽量改成 get(),观察程序更稳定。
七、本节课总结
- 我们学会了字典:用键值对保存“名字 -> 信息”。
- 我们完成了项目 v2.0:用字典实现道具功能映射。
下节课我们会继续优化数据结构,学习元组和集合,让背包系统更智能。