You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用1-2个类结合JSON实现自定义冒险游戏的场景流转?

用JSON配置+单类重构Choose Your Own Adventure游戏

核心思路

把所有场景文本、分支逻辑从代码中剥离到JSON配置文件,用一个GameEngine类统一处理场景渲染、用户输入和分支跳转,完全避免硬编码场景方法。


1. 设计JSON配置结构

可以用一个全局配置文件(或按章节拆分多个文件),每个场景包含文本内容和选项列表,每个选项关联下一个场景ID。示例结构:

{
  "chapters": {
    "intro": {
      "start_scene": "scene_b",
      "scenes": {
        "scene_b": {
          "text": "你站在昏暗的走廊入口,面前有三条岔路:左边是闪烁微光的楼梯,中间是紧闭的木门,右边是通往地下室的铁栅门。",
          "options": [
            {"label": "1. 走左边楼梯", "next_scene": "scene_c"},
            {"label": "2. 推开中间木门", "next_scene": "scene_d"},
            {"label": "3. 拉开右边铁栅门", "next_scene": "scene_e"}
          ]
        },
        "scene_c": {
          "text": "楼梯尽头是一间书房,书桌上放着一本泛黄的日记,旁边有两个抽屉。",
          "options": [
            {"label": "1. 翻看日记", "next_scene": "scene_f"},
            {"label": "2. 打开左边抽屉", "next_scene": "scene_g"}
          ]
        },
        "scene_f": {
          "text": "日记里记录着这座老宅的秘密,你找到了离开的线索——游戏结束。",
          "options": []
        }
      }
    },
    "chapter_1": {
      "start_scene": "scene_1a",
      "scenes": {}
    }
  }
}

2. 实现GameEngine类

这个类负责加载配置、启动章节、循环处理场景逻辑:

import json
from clint.textui import prompt

class GameEngine:
    def __init__(self, config_path):
        # 加载全局游戏配置
        with open(config_path, 'r', encoding='utf-8') as f:
            self.game_config = json.load(f)
        self.current_chapter_data = None
        self.current_scene_id = None

    def start_chapter(self, chapter_id):
        # 初始化指定章节
        self.current_chapter_data = self.game_config['chapters'][chapter_id]
        self.current_scene_id = self.current_chapter_data['start_scene']
        self._run_scene_loop()

    def _run_scene_loop(self):
        # 场景循环:直到当前场景为空(章节结束)
        while self.current_scene_id is not None:
            scene = self.current_chapter_data['scenes'][self.current_scene_id]
            
            # 打印场景文本
            print(scene['text'])
            print("\n")

            # 处理无选项的结局场景
            if not scene.get('options'):
                print("章节结束!")
                self.current_scene_id = None
                continue

            # 提取选项标签供用户选择
            option_labels = [opt['label'] for opt in scene['options']]
            choice_str = prompt.options('请选择你的行动:', option_labels)
            
            # 根据选择获取下一个场景ID
            choice_idx = int(choice_str) - 1
            self.current_scene_id = scene['options'][choice_idx]['next_scene']

3. 使用示例

if __name__ == "__main__":
    # 初始化引擎并启动序章
    game_engine = GameEngine('game_config.json')
    game_engine.start_chapter('intro')

扩展优化点

  • 按章节拆分配置:如果章节内容过多,可将每个章节的场景单独存为JSON文件,在GameEngine中添加load_single_chapter方法加载。
  • 添加玩家状态:在配置中加入requires_condition字段(比如"requires_item": "old_key"),在GameEngine中维护玩家状态字典,判断是否允许进入场景。
  • 结局标记:在场景配置中加"is_end": true字段,触发特殊结束逻辑(比如显示结局评分)。

内容的提问来源于stack exchange,提问作者Julio Arellano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:51:20