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

引言

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

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

文章目录

文字冒险游戏说明

一、游戏实现思路

1)初始化游戏

创建游戏实例,初始化数据结构:

玩家状态字典

游戏地图(位置字典)

敌人列表

游戏结束标志

2)游戏主循环

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

3)核心功能流程

移动系统

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

战斗系统流程

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

物品系统流程

python 复制代码
拾取:检查物品存在 → 移到背包 → 从地图移除

使用:检查背包 → 执行效果 → 移除物品(消耗品)

二、涉及数据结构

字典:

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

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

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

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

列表:

· self.enemies:存储敌人类型

python 复制代码
self.enemies = ["哥布林", "狼", ...]   # 敌人类型集合

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

python 复制代码
self.player["inventory"] = ["手电筒"]  # 动态存储物品

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

python 复制代码
self.locations[location]["items"] = []  # 位置物品列表

字符串(String)

用于描述、名称等文本信息

三、代码实现及注释

python 复制代码
import time
import random

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

相关推荐
咸鱼加辣2 小时前
【python面试】你x的启动?
开发语言·python
Blossom.1182 小时前
多模态大模型实战:从零实现CLIP与电商跨模态检索系统
python·web安全·yolo·目标检测·机器学习·目标跟踪·开源软件
EXtreme352 小时前
【数据结构】二叉树进阶:层序遍历不仅是按层打印,更是形态判定的利器!
c语言·数据结构·二叉树·bfs·广度优先搜索·算法思维·面试必考
小李小李快乐不已2 小时前
二叉树理论基础
数据结构·c++·算法·leetcode
wasp5202 小时前
AgentScope深入分析-设计模式与架构决策分分析
开发语言·python·agent·agentscope
仰泳的熊猫2 小时前
1149 Dangerous Goods Packaging
数据结构·c++·算法·pat考试
山土成旧客2 小时前
【Python学习打卡-Day26】函数的艺术(上):从基础定义到参数魔法
开发语言·python·学习
roman_日积跬步-终至千里2 小时前
【源码分析】StarRocks EditLog 写入与 Replay 完整流程分析
java·网络·python
gf13211112 小时前
python_检测音频人声片段
开发语言·python·音视频