Histrategy Agent
/install histrategy-agent
三國志略 (Histrategy) — Agent 游戏技能
AI 驱动的三国策略游戏。LLM 扮演谋士、将领、NPC 君主, 玩家用自然语言下达指令,运筹帷幄,逐鹿中原。
触发条件
当用户在 IM 中触发以下任一关键词时加载本技能:
明确命令:
/histrategy— 查看游戏状态或开始新游戏/new \x3C势力>— 开始新游戏(shu/cao/wu)/do \x3C决策>— 执行回合/plan— 获取谋士建议/status— 查看当前资源
三国话题关键词(自动检测用户意图):
- 三国、建安、赤壁、官渡、荆州、汉中、许昌、成都、建业、洛阳
- 曹操、刘备、孙权、诸葛亮、关羽、张飞、赵云、司马懿、周瑜、吕布
- 魏、蜀、吴、曹魏、蜀汉、东吴
- 下一回合、出兵、发展、外交、招兵、买粮、进攻、结盟
安装
从 PyPI(推荐)
pip install histrategy-sdk
从 GitHub 源码
git clone https://github.com/emergencescience/histrategy
cd histrategy
pip install -e .
配置 LLM API Key
export DEEPSEEK_API_KEY="sk-..." # 推荐,性价比最高
# 或
export OPENAI_API_KEY="sk-..."
# 或
export TONGYI_API_KEY="sk-..."
不配置 Key 则自动使用离线规则模式(无 LLM 叙事,但可正常游玩)。
核心设计:纯文件存储
游戏状态完全基于文件,不使用内存,不依赖网络:
~/.histrategy/rooms/
\x3C房间名>/
world_state.json # 完整游戏世界状态
turns.jsonl # 追加式回合日志
metadata.json # 元数据
每次回合流程:
- 从
world_state.json读取游戏状态 - 执行玩家决策(LLM 生成叙事 + 规则引擎计算结果)
- 将新状态写回
world_state.json - 追加回合记录到
turns.jsonl
这意味着即使 Agent 的 context 每天被清空,游戏进度也不会丢失。
下次加载时只需 Room.load(房间名) 即可恢复。
IM 机器人实现
基本模式
from histrategy_sdk import Room
# 用平台前缀 + 聊天 ID 生成唯一房间名
def get_room_name(platform: str, chat_id: str) -> str:
return f"{platform}-{chat_id}"
def handle_message(platform: str, chat_id: str, text: str) -> str | None:
"""处理用户消息,返回游戏回复。返回 None 表示不处理。"""
# 开始新游戏
if text.startswith("/new"):
faction = text.split()[1] # shu / cao / wu
room = Room.create(get_room_name(platform, chat_id), faction=faction)
intro = room.intro()
return intro["narrative"]
# 执行回合
elif text.startswith("/do"):
decision = text[4:] # 玩家的自然语言决策
room = Room.load(get_room_name(platform, chat_id))
result = room.play(decision)
return format_turn(result)
# 谋士建议
elif text == "/plan":
room = Room.load(get_room_name(platform, chat_id))
plan = room.plan()
suggestions = "\
".join(f"• {s}" for s in plan["suggestions"])
return f"**谋士献策**\
{suggestions}"
# 查看状态
elif text == "/status":
room = Room.load(get_room_name(platform, chat_id))
s = room.status()
return f"⚔️兵力:{s['strength']} 🍚粮草:{s['food']} 💰库金:{s['treasury']} ❤️士气:{s['morale']}"
return None
格式化回合结果
def format_turn(result: dict) -> str:
"""将 TurnResult 格式化为 IM 消息。"""
fs = result["faction_status"]
lines = [
f"## {result['year']}年{result['season']} · 第{result['turn']}回合",
result["narrative"],
f"\
⚔️兵力:{fs['strength']} 🍚粮草:{fs['food']} 💰库金:{fs['treasury']} ❤️士气:{fs['morale']}",
]
# 谋士建议
if result.get("new_suggestions"):
lines.append("\
**谋士献策**:")
for s in result["new_suggestions"][:3]:
title = s.split("—")[0].strip()[:60]
lines.append(f" • {title}")
# NPC 动向
if result.get("npc_actions"):
lines.append("\
**天下大势**:")
for action in result["npc_actions"][:5]:
lines.append(f" • {action}")
return "\
".join(lines)
多人模式
# 三人群聊,各选一势力
shu = Room.create("lobby-xxx/shu", faction="shu")
cao = Room.create("lobby-xxx/cao", faction="cao")
wu = Room.create("lobby-xxx/wu", faction="wu")
# 蜀汉玩家
result = shu.play("联吴抗曹,派诸葛亮出使东吴")
# 曹魏玩家
result = cao.play("先发制人,南下攻打荆州")
可用势力
| 势力 | faction 参数 | 君主 | 颜色 |
|---|---|---|---|
| 蜀汉 | shu |
刘备 | 🟢 |
| 曹魏 | cao |
曹操 | 🔵 |
| 东吴 | wu |
孙权 | 🔴 |
注意: faction 参数只能是 shu、cao、wu。不要用 wei、liubei、sunquan。
API 参考
Room 类
| 方法 | 说明 |
|---|---|
Room.create(name, faction) |
创建新房间 + 保存初始状态 |
Room.load(name) |
从磁盘加载已有房间 |
room.play(decision) |
执行回合 → 自动存盘 |
room.plan() |
获取谋士建议(不改变状态) |
room.intro() |
获取开场场景 |
room.status() |
获取当前资源快照 |
room.get_turn_history() |
读取所有历史回合 |
TurnResult 字段
| 字段 | 类型 | 说明 |
|---|---|---|
narrative |
str |
AI 生成的历史叙事 |
aftermath |
str |
资源变化摘要 |
state_changes |
dict |
数值变化 |
new_suggestions |
list[str] |
下回合策略建议 |
events_occurred |
list[str] |
角色事件 |
npc_actions |
list[str] |
NPC 势力行动 |
game_over |
`dict | None` |
faction_status |
dict |
资源和领地现状 |
token_usage |
dict |
LLM token 消耗 |
游戏规则要点
- 回合制:每回合 = 一个季节。春→夏→秋→冬
- 资源:兵力、粮草、库金、士气。粮草不足则兵力下降
- 内政:发展商业(增收入)、开垦农田(增粮产)、招募乡勇(增兵力)
- 军事:出征、防守、奇袭
- 外交:结盟、离间、劝降
- NPC 势力:AI 控制的其他势力会自主行动,相互征战
常见问题
| 问题 | 解决 |
|---|---|
| 回合很慢(60-90秒) | LLM 生成需要时间。向用户显示"谋士正在商议…" |
| Context 清空后进度丢失 | 不会。Room.load(房间名) 从文件恢复 |
| 多个用户同时操作 | 文件锁防止同时写入。串行处理即可 |
| 没有 API Key | 自动使用离线规则模式 |
| pip install 失败 | Python ≥ 3.10,pip install --upgrade pip |
源码与社区
- Make sure OpenClaw is installed (local or Docker)
- Run the install command in chat:
/install histrategy-agent - After installation, invoke the skill by name or use
/histrategy-agent - Provide required inputs per the skill's parameter spec and get structured output
What is Histrategy Agent?
三國志略 — AI驱动的三国策略游戏。Agent 安装 histrategy-sdk 后即可在飞书、Discord、Telegram 等 IM 中为主持游戏。纯文件存储,context 重置不丢进度。 It is an AI Agent Skill for Claude Code / OpenClaw, with 31 downloads so far.
How do I install Histrategy Agent?
Run "/install histrategy-agent" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.
Is Histrategy Agent free?
Yes, Histrategy Agent is completely free, licensed under MIT-0. You can download, install and use it at no cost.
Which platforms does Histrategy Agent support?
Histrategy Agent is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).
Who created Histrategy Agent?
It is built and maintained by emergencescience (@emergencescience); the current version is v1.0.0.