当前位置: 首页 > news >正文

Python实战小游戏(二): 文字冒险游戏

引言

在Python入门到精通(二)中,我们了解基本的控制流以及重要的数据结构:列表、字典、 集合等。

现在编写一个小游戏对数据结构、控制流进行简单应用,巩固基础,加深理解。

文章目录

  • 引言
  • 文字冒险游戏说明
    • 一、游戏实现思路
    • 二、涉及数据结构
    • 三、代码实现及注释
  • 其他

文字冒险游戏说明

一、游戏实现思路

1)初始化游戏
创建游戏实例,初始化数据结构:
玩家状态字典
游戏地图(位置字典)
敌人列表
游戏结束标志

2)游戏主循环

游戏开始 ↓ 显示欢迎信息 ↓ 获取玩家姓名 ↓[游戏循环开始]↓ 显示状态(生命值/位置/背包) ↓ 获取玩家指令(移动/查看/拾取/使用/退出) ↓ 根据指令执行对应操作 ↓ 处理特殊事件(危险/谜题) ↓ 更新游戏状态 ↓[检查游戏结束条件](生命值<=0或玩家退出) ↓ 循环继续/游戏结束

3)核心功能流程
移动系统

输入移动方向 → 检查出口是否存在 → 更新位置 → 显示新位置描述 → 触发危险检查 → 触发谜题检查

战斗系统流程

遇到敌人 → 随机生成攻击值 → 计算伤害 → 更新生命值 → 检查是否死亡 → 更新游戏状态

物品系统流程

拾取:检查物品存在 → 移到背包 → 从地图移除 使用:检查背包 → 执行效果 → 移除物品(消耗品)

二、涉及数据结构

字典:
· self.player:存储玩家信息,包括姓名、生命值、物品清单和当前位置

self.player={"name":"",# 字符串:玩家姓名"health":100,# 整数:生命值"inventory":["手电筒"],# 列表:背包物品"location":"森林入口"# 字符串:当前位置}

· self.locations:存储每个位置的信息,包括描述、出口、物品、危险概率和谜题标志

self.locations={"森林入口":{"description":"...",# 位置描述"exits":{"北":"黑暗洞穴",...},# 出口映射"items":["木棍"],# 可拾取物品"danger":30,# 危险概率(可选)"puzzle":True# 谜题标志(可选)}}

列表:
· self.enemies:存储敌人类型

self.enemies=["哥布林","狼",...]# 敌人类型集合

· self.player[“inventory”]:存储玩家拥有的物品

self.player["inventory"]=["手电筒"]# 动态存储物品

· self.locations[location][“items”]:存储每个位置可拾取的物品

self.locations[location]["items"]=[]# 位置物品列表

字符串(String)
用于描述、名称等文本信息

三、代码实现及注释

importtimeimportrandomclassTextAdventureGame:# 初始化def__init__(self):# 初始化玩家属性,使用字典存储self.player={"name":"",# 玩家姓名"health":100,# 生命值"inventory":["手电筒"],# 背包,初始有一个手电筒"location":"森林入口"# 初始位置}# 游戏地图,使用字典存储每个位置的信息,每个位置也是一个字典self.locations={"森林入口":{"description":"你站在一片神秘的森林入口。阳光透过树叶洒下斑驳的光影。","exits":{"北":"黑暗洞穴","东":"古老神庙","西":"河边"},# 出口,用字典表示方向与位置的关系"items":["木棍"]# 该位置的物品列表},# 其他位置类似...}# 敌人列表self.enemies=["哥布林","狼","巨蜘蛛","骷髅战士"]# 游戏结束标志self.game_over=False# 缓慢打印文字,增加游戏氛围defprint_slowly(self,text,delay=0.03):forcharintext:print(char,end='',flush=True)time.sleep(delay)print()# 显示玩家状态defshow_status(self):print(f"\n{'='*50}")print(f"👤{self.player['name']}| ❤️ 生命值:{self.player['health']}")print(f"📍 位置:{self.player['location']}")# 如果背包不为空,则用逗号分隔物品,否则显示'空'print(f"🎒 背包:{', '.join(self.player['inventory'])ifself.player['inventory']else'空'}")print(f"{'='*50}")# 处理危险事件defhandle_danger(self):# 获取当前位置的危险概率,如果没有则默认为0danger_chance=self.locations[self.player["location"]].get("danger",0)# 根据危险概率随机决定是否遇到危险ifrandom.randint(1,100)<=danger_chance:enemy=random.choice(self.enemies)self.print_slowly(f"\n⚔️ 突然,一只{enemy}跳了出来!")# 简单的战斗系统:随机生成玩家和敌人的攻击力player_attack=random.randint(10,30)enemy_attack=random.randint(5,25)# 玩家受到伤害self.player["health"]-=enemy_attackprint(f"你造成了{player_attack}点伤害")print(f"{enemy}造成了{enemy_attack}点伤害")print(f"你的生命值:{self.player['health']}")# 检查玩家是否死亡ifself.player["health"]<=0:self.print_slowly("💀 你被击败了...游戏结束!")self.game_over=TruereturnFalseelse:print(f"你击败了{enemy}!")returnTruereturnFalse# 处理谜题defhandle_puzzle(self):# 检查当前位置是否有谜题ifself.locations[self.player["location"]].get("puzzle"):self.print_slowly("\n🧩 你发现了一个谜题!")self.print_slowly("古老的石板上刻着:'我始于结束,终于开始。我是什么?'")answer=input("你的答案是什么? ").strip().lower()# 允许一些答案变体ifanswerin["时间","时钟","沙漏","time","clock"]:self.print_slowly("✅ 石门缓缓打开,你获得了'神秘护符'!")self.player["inventory"].append("神秘护符")# 恢复生命值,但不超过150self.player["health"]=min(150,self.player["health"]+50)print("❤️ 生命值恢复了50点!")else:self.print_slowly("❌ 回答错误!什么也没有发生...")# 查看当前位置deflook_around(self):location_info=self.locations[self.player["location"]]self.print_slowly(f"\n{location_info['description']}")# 如果有物品,则显示iflocation_info.get("items"):self.print_slowly(f"你发现了:{', '.join(location_info['items'])}")# 显示出口self.print_slowly(f"出口:{', '.join(location_info['exits'].keys())}")# 移动到新位置defmove(self,direction):current=self.player["location"]exits=self.locations[current]["exits"]ifdirectioninexits:new_location=exits[direction]self.player["location"]=new_location self.print_slowly(f"\n🚶 你向{direction}走,来到了{new_location}")self.look_around()# 检查危险self.handle_danger()# 如果游戏没有结束,检查谜题ifnotself.game_over:self.handle_puzzle()returnTrueelse:self.print_slowly(f"\n❌ 那里没有路!")returnFalse# 拾取物品deftake_item(self,item):location=self.player["location"]items=self.locations[location].get("items",[])ifiteminitems:# 将物品从地图移到背包self.player["inventory"].append(item)items.remove(item)self.print_slowly(f"\n✅ 你拾取了{item}")returnTrueelse:self.print_slowly(f"\n❌ 这里没有{item}")returnFalse# 使用物品defuse_item(self,item):ifiteminself.player["inventory"]:ifitem=="神秘护符":self.print_slowly("\n✨ 神秘护符发出光芒,你感觉充满了力量!")# 使用护符恢复生命值,但不超过200self.player["health"]=min(200,self.player["health"]+100)print(f"❤️ 生命值恢复了100点!当前:{self.player['health']}")self.player["inventory"].remove(item)# 使用后移除else:self.print_slowly(f"\n🔧 你使用了{item},但似乎没什么效果...")returnTrueelse:self.print_slowly(f"\n❌ 你的背包里没有{item}")returnFalse# 主游戏循环defplay(self):self.print_slowly("🎮 欢迎来到文字冒险游戏!")self.player["name"]=input("请输入你的名字: ")self.print_slowly(f"\n你好,{self.player['name']}!开始你的冒险吧!")self.look_around()# 循环直至结束whilenotself.game_over:self.show_status()action=input("\n你要做什么?(移动/查看/拾取/使用/退出): ").strip().lower()ifaction=="移动":direction=input("往哪个方向?(北/南/东/西): ").strip()self.move(direction)elifaction=="查看":self.look_around()elifaction=="拾取":item=input("拾取什么物品?: ").strip()self.take_item(item)elifaction=="使用":item=input("使用什么物品?: ").strip()self.use_item(item)elifaction=="退出":self.print_slowly("👋 再见!欢迎下次再来冒险!")breakelse:self.print_slowly("❌ 我不明白这个指令...")# 如果是因为生命值耗尽而结束,显示游戏结束ifself.player["health"]<=0:self.print_slowly("\n💀 游戏结束!")# 运行游戏if__name__=="__main__":game=TextAdventureGame()game.play()

其他

print函数

基本语法:
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

参数说明:
objects:表示可以一次输出多个对象,用逗号分隔。
sep:用来间隔多个对象,默认是一个空格。
end:用来设定以什么结尾,默认是换行符(\n)。
file:要写入的文件对象,默认是标准输出(sys.stdout)。
flush:输出是否被强制刷新,默认False。

http://www.rkmt.cn/news/133441.html

相关文章:

  • Excalidraw线下Meetup组织指南:城市分会筹建
  • Bernstein–Vazirani 算法 的原理
  • Excalidraw A/B测试框架搭建:数据驱动迭代
  • Excalidraw新手引导优化:降低入门门槛
  • Excalidraw Open Collective运营情况透明度报告
  • Excalidraw非营利组织应用:公益项目规划工具
  • Excalidraw表单验证机制设计与用户体验平衡
  • MiniMax-M2:高效开源MoE模型,聚焦智能体任务
  • 快手KwaiCoder:动态推理深度的AutoThink模型
  • 机器人训练,数据模态之热成像,合成数据or真实数据?来自NASA月球车团队的服务方
  • WAN2.2-14B-Rapid-AllInOne:FP8全能视频加速模型
  • HunyuanImage-3.0:800亿MoE多模态图像生成模型开源
  • GraniStudio : TCP/IP(Socket)协议深度剖析
  • Wan2.2:MoE架构赋能高清视频创作
  • Excalidraw产品定位再思考:专注技术人群
  • GraniStudio : MC 协议深度剖析
  • Qwen3-235B双模式推理大模型发布:重新定义智能交互的效率与深度
  • Excalidraw备份恢复机制设计原则与实施步骤
  • 4、Windows 10 使用指南:系统设置、网络连接与账户创建
  • Nitro-E:304M参数极速图文扩散模型
  • Excalidraw能否用于游戏关卡设计原型绘制?
  • Qwen-Image-Edit-MeiTu:DiT赋能图像编辑新高度
  • PCB布线——电源
  • java包头市大学生家教信息中介平台springboot-vue
  • 腾讯开源Hunyuan-0.5B轻量化大模型
  • Whisper-base.en:68万小时训练的英文ASR模型
  • Qwen3-30B-A3B-Thinking-2507推理性能跃升
  • Kimi-Audio-7B:开源全能音频基础模型
  • 使用OpenLLM管理轻量级大模型服务
  • Janus-Pro-7B:自回归多模态理解生成一体化