用 Python + Ollama (Qwen2.5) 开发一个 AI 修仙游戏
简介
本文将介绍如何使用 Python 和 Ollama (Qwen2.5 模型) 开发一个文字版修仙游戏。这个游戏具有以下特点:
- 完整的修仙世界观和成长体系
- 基于 AI 生成的动态剧情和事件
- 丰富的物品系统(功法、丹药、灵宝等)
- 社交系统(师门、家族关系等)
- 存档系统
技术栈
- Python 3.8+
- Ollama (Qwen2.5 模型)
- dataclasses 用于数据结构
- JSON 用于存档
项目结构
.
├── models.py # 数据模型
├── ai_interface.py # AI 接口
├── config.py # 配置文件
├── event_generator.py # 事件生成器
├── save_manager.py # 存档管理
├── game.py # 游戏主逻辑
└── xianxia.py # 入口文件
1. 数据模型设计
首先我们需要定义游戏中的基本数据结构。创建 models.py
:
from dataclasses import dataclass
from typing import List, Dict, Optional
@dataclass
class Character:
"""角色类"""
name: str
age: int
relationship: str # 关系:父/母/师父/朋友等
description: str = ""
status: str = "在世"
cultivation: str = "凡人"
death_age: int = 0
@dataclass
class Item:
"""物品类"""
name: str
description: str
type: str # 功法/丹药/灵石
level: int
effects: Dict[str, int]
# ... 其他数据类
2. AI 接口
创建 ai_interface.py
来处理与 Ollama 的交互:
import ollama
class OllamaAPI:
def __init__(self):
self.model = "qwen2.5"
def generate(self, prompt: str, model: str = None) -> str:
try:
if model:
self.model = model
response = ollama.chat(
model=self.model,
messages=[{'role': 'user', 'content': prompt}]
)
return response['message']['content']
except Exception as e:
print(f"Ollama 调用错误: {e}")
return None
3. 事件生成系统
创建 event_generator.py
来生成游戏事件:
class EventGenerator:
def __init__(self, ollama_api: OllamaAPI):
self.ollama = ollama_api
self.character_name = ""
def generate_yearly_description(self, character_info: Dict) -> str:
"""生成年度描述"""
prompt = f"""
作为修仙游戏的年度发展生成器,请根据以下角色信息生成一段详细的年度描述:
{character_info}
...
"""
return self.ollama.generate(prompt)
4. 存档系统
创建 save_manager.py
来处理游戏存档:
import json
from dataclasses import asdict
class SaveManager:
def __init__(self, save_file: str):
self.save_file = save_file
def save_game(self, game_state: dict):
"""保存游戏状态"""
with open(self.save_file, 'w', encoding='utf-8') as f:
json.dump(game_state, f, ensure_ascii=False, indent=2)
def load_game(self) -> dict:
"""加载游戏存档"""
try:
with open(self.save_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"加载存档失败: {e}")
return None
5. 游戏主逻辑
创建 game.py
实现主要游戏逻辑:
class XianXiaSim:
def __init__(self):
self.save_manager = SaveManager("xianxia_save.json")
self.ollama = OllamaAPI()
self.event_generator = EventGenerator(self.ollama)
# ... 初始化其他属性
def start_game(self):
"""开始游戏"""
print("欢迎来到修仙模拟器!")
# ... 游戏开始逻辑
def next_year(self):
"""进入下一年"""
# ... 年度更新逻辑
6. 游戏特色功能
6.1 灵根觉醒系统
def check_spirit_root(self):
"""检测灵根"""
print("\n==== 灵根觉醒仪式 ====")
# ... 灵根觉醒逻辑
6.2 修炼系统
def generate_path_events(self) -> List[Dict]:
"""生成修仙相关事件"""
# ... 修炼事件生成逻辑
6.3 物品系统
def add_item(self, item: Item):
"""添加物品到背包"""
# ... 物品添加逻辑
7. AI 生成内容
游戏中的大部分剧情和事件都由 AI 生成,例如:
- 年度发展描述
- 修炼事件
- 机缘际遇
- NPC 对话
示例提示词:
prompt = f"""
作为修仙游戏的年度发展生成器,请根据以下角色信息生成一段详细的年度描述。
注意:主角名字必须使用"{self.name}",不要使用其他名字。
角色信息:
{json.dumps(character_info, ensure_ascii=False, indent=2)}
要求:
1. 描述中必须使用"{self.name}"作为主角名字
2. 不要使用其他名字替代主角
3. 要体现门派生活特色
...
"""
总结
通过结合 Python 和 Ollama (Qwen2.5),我们实现了一个具有以下特点的修仙游戏:
- 动态生成的剧情和事件
- 完整的修仙世界观
- 丰富的游戏系统
- 可扩展的架构设计
这个项目展示了如何将 AI 技术应用到游戏开发中,创造出更加丰富和动态的游戏体验。
未来展望
可以考虑添加的功能:
- 更复杂的战斗系统
- 多分支剧情
- 更丰富的社交互动
- 更多的修炼体系
- 图形界面