三國志略 — AI驱动的三国策略游戏。Agent 安装 histrategy-sdk 后即可在飞书、Discord、Telegram 等 IM 中为主持游戏。纯文件存储,context 重置不丢进度。
---
name: histrategy-agent
description: 三國志略 — AI驱动的三国策略游戏。Agent 安装 histrategy-sdk 后即可在飞书、Discord、Telegram 等 IM 中为主持游戏。纯文件存储,context 重置不丢进度。
version: 1.0.0
---
# 三國志略 (Histrategy) — Agent 游戏技能
AI 驱动的三国策略游戏。LLM 扮演谋士、将领、NPC 君主,
玩家用自然语言下达指令,运筹帷幄,逐鹿中原。
## 触发条件
当用户在 IM 中触发以下任一关键词时加载本技能:
**明确命令:**
- `/histrategy` — 查看游戏状态或开始新游戏
- `/new <势力>` — 开始新游戏(shu/cao/wu)
- `/do <决策>` — 执行回合
- `/plan` — 获取谋士建议
- `/status` — 查看当前资源
**三国话题关键词(自动检测用户意图):**
- 三国、建安、赤壁、官渡、荆州、汉中、许昌、成都、建业、洛阳
- 曹操、刘备、孙权、诸葛亮、关羽、张飞、赵云、司马懿、周瑜、吕布
- 魏、蜀、吴、曹魏、蜀汉、东吴
- 下一回合、出兵、发展、外交、招兵、买粮、进攻、结盟
## 安装
### 从 PyPI(推荐)
```bash
pip install histrategy-sdk
```
### 从 GitHub 源码
```bash
git clone https://github.com/emergencescience/histrategy
cd histrategy
pip install -e .
```
### 配置 LLM API Key
```bash
export DEEPSEEK_API_KEY="sk-..." # 推荐,性价比最高
# 或
export OPENAI_API_KEY="sk-..."
# 或
export TONGYI_API_KEY="sk-..."
```
不配置 Key 则自动使用离线规则模式(无 LLM 叙事,但可正常游玩)。
## 核心设计:纯文件存储
游戏状态**完全基于文件**,不使用内存,不依赖网络:
```
~/.histrategy/rooms/
<房间名>/
world_state.json # 完整游戏世界状态
turns.jsonl # 追加式回合日志
metadata.json # 元数据
```
每次回合流程:
1. 从 `world_state.json` 读取游戏状态
2. 执行玩家决策(LLM 生成叙事 + 规则引擎计算结果)
3. 将新状态写回 `world_state.json`
4. 追加回合记录到 `turns.jsonl`
**这意味着即使 Agent 的 context 每天被清空,游戏进度也不会丢失。**
下次加载时只需 `Room.load(房间名)` 即可恢复。
## IM 机器人实现
### 基本模式
```python
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 = "\n".join(f"• {s}" for s in plan["suggestions"])
return f"**谋士献策**\n{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
```
### 格式化回合结果
```python
def format_turn(result: dict) -> str:
"""将 TurnResult 格式化为 IM 消息。"""
fs = result["faction_status"]
lines = [
f"## {result['year']}年{result['season']} · 第{result['turn']}回合",
result["narrative"],
f"\n⚔️兵力:{fs['strength']} 🍚粮草:{fs['food']} 💰库金:{fs['treasury']} ❤️士气:{fs['morale']}",
]
# 谋士建议
if result.get("new_suggestions"):
lines.append("\n**谋士献策**:")
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("\n**天下大势**:")
for action in result["npc_actions"][:5]:
lines.append(f" • {action}")
return "\n".join(lines)
```
### 多人模式
```python
# 三人群聊,各选一势力
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` |
## 源码与社区
- GitHub: https://github.com/emergencescience/histrategy
- PyPI: https://pypi.org/project/histrategy-sdk/
- Web 版: https://emergence.science/play/histrategy
don't have the plugin yet? install it then click "run inline in claude" again.