文字冒险游戏是许多程序员入门游戏开发的第一个项目类型。它不需要复杂的图形引擎,却能完整展现游戏设计的核心要素:剧情分支、状态管理和玩家互动。作为一名Python开发者,我们可以用不到200行代码实现一个功能完整的文字冒险游戏框架。
提示:本文假设读者已掌握Python基础语法,了解面向对象编程概念。所有代码兼容Python 3.6+版本。
文字冒险游戏的核心是"场景-选择"模型。每个场景包含:
python复制class Scene:
def __init__(self, description, choices=None):
self.description = description
self.choices = choices or {}
def add_choice(self, choice_text, next_scene):
self.choices[choice_text] = next_scene
这个基础架构可以扩展出更复杂的游戏机制:
游戏主循环需要处理以下核心逻辑:
python复制class GameEngine:
def __init__(self, start_scene):
self.current_scene = start_scene
self.inventory = []
self.game_over = False
def play(self):
while not self.game_over:
print("\n" + "-"*40)
print(self.current_scene.description)
if not self.current_scene.choices:
self.game_over = True
continue
for i, choice in enumerate(self.current_scene.choices, 1):
print(f"{i}. {choice}")
choice = input("你的选择: ")
self.handle_choice(choice)
def handle_choice(self, choice):
try:
choice_idx = int(choice) - 1
selected = list(self.current_scene.choices.values())[choice_idx]
self.current_scene = selected
except (ValueError, IndexError):
print("无效选择,请重新输入")
现在我们可以构建游戏场景图。这是一个简单的恐怖冒险游戏示例:
python复制# 创建场景
start = Scene("你在一间黑暗的房间里醒来,头痛欲裂。")
corridor = Scene("走廊尽头有一扇门,左侧是楼梯间")
kitchen = Scene("厨房里弥漫着腐臭味,冰箱门微微晃动")
basement = Scene("地下室堆满杂物,角落有个上锁的箱子")
# 设置场景连接
start.add_choice("摸索着向门口走去", corridor)
corridor.add_choice("进入厨房", kitchen)
corridor.add_choice("下楼去地下室", basement)
# 启动游戏
game = GameEngine(start)
game.play()
扩展Scene类和GameEngine类来支持物品交互:
python复制class Scene:
def __init__(self, description, items=None, choices=None):
self.items = items or []
# 其余初始化代码...
class GameEngine:
def __init__(self, start_scene):
# 新增物品相关命令
self.commands = {
"take": self.take_item,
"use": self.use_item
}
def take_item(self, item_name):
if item_name in self.current_scene.items:
self.inventory.append(item_name)
self.current_scene.items.remove(item_name)
print(f"你获得了 {item_name}")
else:
print("这里没有这个物品")
def use_item(self, item_name):
if item_name in self.inventory:
# 实现物品使用逻辑
pass
else:
print("你的背包里没有这个物品")
为游戏添加全局状态变量,实现更复杂的剧情分支:
python复制class GameEngine:
def __init__(self, start_scene):
self.flags = {} # 存储游戏状态
def check_condition(self, condition):
"""检查条件表达式 如: 'has_key and door_unlocked'"""
return eval(condition, {}, self.flags)
使用pickle模块实现简单的存档系统:
python复制import pickle
class GameEngine:
def save_game(self, filename):
with open(filename, 'wb') as f:
pickle.dump({
'scene': self.current_scene,
'inventory': self.inventory,
'flags': self.flags
}, f)
@classmethod
def load_game(cls, filename, scenes):
with open(filename, 'rb') as f:
data = pickle.load(f)
engine = cls(data['scene'])
engine.inventory = data['inventory']
engine.flags = data['flags']
return engine
text复制game/
├── engine.py # 游戏引擎核心
├── scenes/ # 场景定义
│ ├── chapter1.py
│ ├── chapter2.py
├── items.py # 物品系统
├── tests/ # 单元测试
└── main.py # 游戏入口
问题1:选择无效后游戏崩溃
问题2:场景间的循环引用导致内存泄漏
问题3:游戏存档过大
下面是一个完整的小游戏实现:
python复制from collections import defaultdict
class Scene:
def __init__(self, scene_id, description):
self.scene_id = scene_id
self.description = description
self.choices = []
self.items = []
self.conditions = defaultdict(list)
def add_choice(self, text, next_scene_id, condition=None):
self.choices.append({
'text': text,
'next': next_scene_id,
'condition': condition
})
class GameEngine:
def __init__(self, start_scene_id, scenes):
self.scenes = {s.scene_id: s for s in scenes}
self.current_scene = self.scenes[start_scene_id]
self.inventory = []
self.flags = {'has_key': False}
def get_available_choices(self):
return [
c for c in self.current_scene.choices
if not c['condition'] or self.flags.get(c['condition'])
]
def play(self):
while True:
print(f"\n{self.current_scene.description}")
if not self.get_available_choices():
print("\n游戏结束")
break
for i, choice in enumerate(self.get_available_choices(), 1):
print(f"{i}. {choice['text']}")
cmd = input("> ").strip().lower()
self.process_command(cmd)
def process_command(self, command):
if command.isdigit():
self.handle_choice(int(command))
elif command.startswith('take '):
self.take_item(command[5:])
elif command == 'inventory':
self.show_inventory()
else:
print("无效命令")
def handle_choice(self, choice_idx):
choices = self.get_available_choices()
try:
choice = choices[choice_idx - 1]
self.current_scene = self.scenes[choice['next']]
except (IndexError, KeyError):
print("无效选择")
# 游戏场景定义
scenes = [
Scene("start", "你在一间上锁的房间里醒来。桌上有一把钥匙。"),
Scene("hallway", "走廊里有三扇门:红色、蓝色和绿色。"),
Scene("red_room", "红色房间里有一个宝箱。"),
Scene("blue_room", "蓝色房间是死胡同。"),
Scene("exit", "恭喜你逃出来了!")
]
# 设置场景连接
scenes[0].add_choice("拿起钥匙", "start")
scenes[0].add_choice("检查门", "hallway", "has_key")
scenes[1].add_choice("进入红色房间", "red_room")
scenes[1].add_choice("进入蓝色房间", "blue_room")
scenes[1].add_choice("尝试绿色门", "exit", "has_key")
# 启动游戏
game = GameEngine("start", scenes)
game.play()
这个框架可以进一步扩展:
文字冒险游戏是学习游戏设计的绝佳起点。通过这个项目,你不仅能掌握Python面向对象编程,还能理解游戏状态管理、用户输入处理等核心概念。试着创作你自己的故事吧!