请你为我编写一个互动小说agent
- User
请你为我编写一个互动小说agent
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
请你为我编写一个互动小说agent
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
我来帮你设计一个互动小说Agent系统。这个系统将允许读者通过选择不同的选项来影响故事的发展。
import json
import random
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from enum import Enum
class StoryState(Enum):
"""故事状态枚举"""
ONGOING = "ongoing"
ENDED = "ended"
GAME_OVER = "game_over"
@dataclass
class Choice:
"""选项类"""
text: str
next_scene_id: str
requirements: Dict[str, any] = None # 选择此选项的前提条件
effects: Dict[str, any] = None # 选择此选项的效果
@dataclass
class Scene:
"""场景类"""
id: str
title: str
description: str
choices: List[Choice]
state: StoryState = StoryState.ONGOING
auto_effects: Dict[str, any] = None # 进入场景时自动产生的效果
class InteractiveStoryAgent:
"""互动小说Agent主类"""
def __init__(self, story_file: str = None):
self.current_scene_id = "start"
self.player_stats = {
"health": 100,
"courage": 50,
"wisdom": 50,
"items": []
}
self.story_history = []
self.scenes: Dict[str, Scene] = {}
if story_file:
self.load_story(story_file)
else:
self._create_default_story()
def _create_default_story(self):
"""创建默认故事"""
self.scenes = {
"start": Scene(
id="start",
title="神秘的森林入口",
description="""你站在一片古老森林的入口处。阳光透过树叶的缝隙洒下斑驳的光影。
前方有两条小路:左边的路看起来阴暗潮湿,右边的路则充满鸟语花香。
你的直觉告诉你,这个选择将决定你接下来的冒险。""",
choices=[
Choice(
text="走左边的阴暗小路",
next_scene_id="dark_path",
effects={"courage": 10}
),
Choice(
text="走右边的花香小路",
next_scene_id="bright_path",
effects={"wisdom": 10}
),
Choice(
text="原路返回",
next_scene_id="give_up"
)
]
),
"dark_path": Scene(
id="dark_path",
title="黑暗洞穴",
description="""你勇敢地选择了阴暗的小路。走了不久,你发现了一个神秘的洞穴。
洞口传来阵阵凉风,似乎有什么东西在里面等待着你。""",
choices=[
Choice(
text="进入洞穴探索",
next_scene_id="cave_explore",
requirements={"courage": 60}
),
Choice(
text="在洞口大声呼喊",
next_scene_id="cave_shout"
),
Choice(
text="绕过洞穴继续前进",
next_scene_id="bypass_cave"
)
],
auto_effects={"health": -10}
),
"bright_path": Scene(
id="bright_path",
title="精灵花园",
description="""沿着充满花香的小路前行,你来到了一个美丽的花园。
花园中央有一个清澈的泉水,一位精灵正在泉边休息。""",
choices=[
Choice(
text="向精灵打招呼",
next_scene_id="talk_to_elf",
effects={"wisdom": 20}
),
Choice(
text="悄悄靠近泉水",
next_scene_id="approach_spring"
),
Choice(
text="采摘一些花朵",
next_scene_id="pick_flowers"
)
],
auto_effects={"health": 20}
),
"give_up": Scene(
id="give_up",
title="故事结束",
description="你决定放弃这次冒险,转身离开了森林。也许下次你会更勇敢一些。",
choices=[],
state=StoryState.ENDED
)
}
# 添加更多场景...
self._add_more_scenes()
def _add_more_scenes(self):
"""添加更多故事场景"""
additional_scenes = {
"cave_explore": Scene(
id="cave_explore",
title="宝藏与危险",
description="""你鼓起勇气进入了洞穴。在深处,你发现了一个古老的宝箱!
但是,一只巨大的蝙蝠守护着它。""",
choices=[
Choice(
text="与蝙蝠战斗",
next_scene_id="fight_bat",
requirements={"courage": 70}
),
Choice(
text="尝试和平沟通",
next_scene_id="talk_to_bat",
requirements={"wisdom": 70}
),
Choice(
text="悄悄撤退",
next_scene_id="retreat_from_cave"
)
]
),
"talk_to_elf": Scene(
id="talk_to_elf",
title="精灵的祝福",
description="""精灵友好地回应了你的问候。"欢迎,旅行者。我可以给你一个祝福,
但你必须选择是要治愈之光还是智慧之泉。"""",
choices=[
Choice(
text="选择治愈之光",
next_scene_id="healing_blessing",
effects={"health": 50}
),
Choice(
text="选择智慧之泉",
next_scene_id="wisdom_blessing",
effects={"wisdom": 30}
)
]
)
}
self.scenes.update(additional_scenes)
def get_current_scene(self) -> Scene:
"""获取当前场景"""
return self.scenes.get(self.current_scene_id)
def display_scene(self) -> str:
"""显示当前场景"""
scene = self.get_current_scene()
if not scene:
return "错误:找不到当前场景"
# 应用自动效果
if scene.auto_effects:
self._apply_effects(scene.auto_effects)
output = f"\n{'='*50}\n"
output += f"【{scene.title}】\n\n"
output += f"{scene.description}\n\n"
# 显示玩家状态
output += f"当前状态:生命值:{self.player_stats['health']} | "
output += f"勇气:{self.player_stats['courage']} | "
output += f"智慧:{self.player_stats['wisdom']}\n"
if self.player_stats['items']:
output += f"物品:{', '.join(self.player_stats['items'])}\n"
output += f"{'='*50}\n\n"
# 显示可用选项
if scene.choices:
output += "你的选择:\n"
valid_choices = []
for i, choice in enumerate(scene.choices):
if self._check_requirements(choice.requirements):
valid_choices.append((i, choice))
output += f"{i+1}. {choice.text}\n"
else:
output += f"{i+1}. [需要满足条件] {choice.text}\n"
return output
def make_choice(self, choice_index: int) -> Tuple[bool, str]:
"""做出选择"""
scene = self.get_current_scene()
if not scene or not scene.choices:
return False, "当前场景没有可用选项"
if choice_index < 0 or choice_index >= len(scene.choices):
return False, "无效的选择"
choice = scene.choices[choice_index]
# 检查是否满足要求
if not self._check_requirements(choice.requirements):
return False, "你还不满足选择这个选项的条件"
# 应用选择效果
if choice.effects:
self._apply_effects(choice.effects)
# 记录历史
self.story_history.append({
"scene_id": self.current_scene_id,
"choice_index": choice_index,
"choice_text": choice.text
})
# 移动到下一个场景
self.current_scene_id = choice.next_scene_id
# 检查游戏是否结束
if self.player_stats["health"] <= 0:
return True, "你的生命值耗尽了。游戏结束。"
return True, "选择成功"
def _check_requirements(self, requirements: Dict[str, any]) -> bool:
"""检查是否满足要求"""
if not requirements:
return True
for stat, required_value in requirements.items():
if stat in self.player_stats:
if isinstance(self.player_stats[stat], list):
if required_value not in self.player_stats[stat]:
return False
elif self.player_stats[stat] < required_value:
return False
return True
def _apply_effects(self, effects: Dict[str, any]):
"""应用效果"""
for stat, value in effects.items():
if stat in self.player_stats:
if isinstance(self.player_stats[stat], list):
if value not in self.player_stats[stat]:
self.player_stats[stat].append(value)
else:
self.player_stats[stat] += value
# 确保数值在合理范围内
if stat == "health":
self.player_stats[stat] = max(0, min(100, self.player_stats[stat]))
def save_progress(self, filename: str):
"""保存游戏进度"""
save_data = {
"current_scene_id": self.current_scene_id,
"player_stats": self.player_stats,
"story_history": self.story_history
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(save_data, f, ensure_ascii=False, indent=2)
def load_progress(self, filename: str):
"""加载游戏进度"""
with open(filename, 'r', encoding='utf-8') as f:
save_data = json.load(f)
self.current_scene_id = save_data["current_scene_id"]
self.player_stats = save_data["player_stats"]
self.story_history = save_data["story_history"]
# 使用示例
def play_interactive_story():
"""运行互动小说"""
agent = InteractiveStoryAgent()
print("欢迎来到互动小说世界!")
print("在每个场景中,你需要做出选择来推动故事发展。")
print("你的选择将影响故事的走向和你的角色属性。\n")
while True:
# 显示当前场景
print(agent.display_scene())
# 检查游戏是否结束
current_scene = agent.get_current_scene()
if current_scene.state != StoryState.ONGOING:
print("故事结束!感谢游玩!")
break
# 获取玩家输入
try:
choice = int(input("请输入你的选择(输入数字):")) - 1
success, message = agent.make_choice(choice)
if not success:
print(f"\n{message}\n")
else:
print(f"\n{message}\n")
except ValueError:
print("\n请输入有效的数字!\n")
except KeyboardInterrupt:
print("\n\n游戏已暂停。")
save = input("是否保存进度?(y/n): ")
if save.lower() == 'y':
agent.save_progress("save_game.json")
print("进度已保存!")
break
if __name__ == "__main__":
play_interactive_story()
这个互动小说Agent系统包含以下特性:
你可以通过修改场景数据来创建自己的故事,或者扩展功能,比如添加物品系统、战斗系统等。需要我帮你实现特定的功能吗?