aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/examples/custom_plugin.py
diff options
context:
space:
mode:
author简律纯 <i@jyunko.cn>2025-10-25 00:30:48 +0800
committer简律纯 <i@jyunko.cn>2025-10-25 00:30:48 +0800
commitcbc653ffd0ea9abf4360623dc7a7651e1a49cc61 (patch)
treeea3c396148158077bae3e77eaa9341f8c1990636 /examples/custom_plugin.py
parent08299b37dfda86e56e4f2b442f68ccd2da7a82e3 (diff)
downloadconventional_role_play-cbc653ffd0ea9abf4360623dc7a7651e1a49cc61.tar.gz
conventional_role_play-cbc653ffd0ea9abf4360623dc7a7651e1a49cc61.zip
feat: Implement plugin system with combat tracker and dice analyzer
- Added `plugin_system_demo.py` to demonstrate basic plugin usage, processing, and analysis. - Created `CombatTrackerPlugin` for tracking combat statistics including damage and healing. - Developed `DiceAnalyzerPlugin` for analyzing dice rolls and calculating success rates. - Introduced `renderer_demo.py` for rendering output in HTML, Markdown, and JSON formats. - Implemented `rule_system_demo.py` to showcase rule engine capabilities with various examples. - Established core rule engine functionality in `rules.py` with support for conditions and actions. - Enhanced base plugin structure in `base.py` to support different plugin types (Processor, Renderer, Analyzer). - Added custom exception handling in `exceptions.py` for better error management. - Configured logging setup in `logging_config.py` for improved logging capabilities. - Created unit tests in `test_rust_core.py` to validate core functionalities and performance.
Diffstat (limited to 'examples/custom_plugin.py')
-rw-r--r--examples/custom_plugin.py70
1 files changed, 12 insertions, 58 deletions
diff --git a/examples/custom_plugin.py b/examples/custom_plugin.py
index dd96311..5f77c41 100644
--- a/examples/custom_plugin.py
+++ b/examples/custom_plugin.py
@@ -1,14 +1,7 @@
-#!/usr/bin/env python3
-"""
-自定义插件示例
-演示如何创建和使用自定义插件来扩展 ConventionalRP 的功能
-"""
-
import sys
from typing import List, Dict, Any
from pathlib import Path
-# 添加 src 目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / "src"))
@@ -17,21 +10,12 @@ from conventionalrp.core.processor import Processor
class DiceRollAnalyzer:
- """骰子统计分析插件"""
+ """骰点统计分析插件"""
def __init__(self):
self.name = "Dice Roll Analyzer"
def analyze(self, parsed_data: List[Dict[str, Any]]) -> Dict[str, Any]:
- """
- 分析日志中的所有骰子投掷
-
- Args:
- parsed_data: 解析后的日志数据
-
- Returns:
- 统计结果
- """
stats = {
"total_rolls": 0,
"by_character": {},
@@ -65,15 +49,6 @@ class DialogueExtractor:
self.name = "Dialogue Extractor"
def extract(self, parsed_data: List[Dict[str, Any]]) -> List[Dict[str, str]]:
- """
- 提取所有角色对话
-
- Args:
- parsed_data: 解析后的日志数据
-
- Returns:
- 对话列表
- """
dialogues = []
for entry in parsed_data:
@@ -92,59 +67,38 @@ class DialogueExtractor:
def main():
- print("=" * 60)
- print("ConventionalRP 自定义插件示例")
- print("=" * 60)
-
- # 准备数据
example_dir = Path(__file__).parent
rules_file = example_dir / "rules" / "dnd5e_rules.json5"
log_file = example_dir / "logs" / "combat_log.txt"
-
- print("\n[1] 解析日志...")
+
+ print("\nLoading log...")
parser = Parser()
parser.load_rules(str(rules_file))
parsed_data = parser.parse_log(str(log_file))
- print(f"✓ 解析完成,共 {len(parsed_data)} 条记录")
+ print(f"Done, {len(parsed_data)} in total")
- # 使用骰子分析插件
- print("\n[2] 运行骰子统计分析插件...")
dice_analyzer = DiceRollAnalyzer()
dice_stats = dice_analyzer.analyze(parsed_data)
-
- print(f"\n骰子统计结果:")
+
+ print(f"\nStatistics:")
print(f" 总投掷次数: {dice_stats['total_rolls']}")
print(f"\n 按角色统计:")
for character, count in dice_stats['by_character'].items():
print(f" {character}: {count} 次")
- print(f"\n 按骰子类型统计:")
+ print(f"\n Statistics in Dice Types:")
for dice_type, count in dice_stats['dice_types'].items():
- print(f" d{dice_type}: {count} 次")
+ print(f" d{dice_type}: {count} times")
- # 使用对话提取插件
- print("\n[3] 运行对话提取插件...")
dialogue_extractor = DialogueExtractor()
dialogues = dialogue_extractor.extract(parsed_data)
-
- print(f"\n提取到 {len(dialogues)} 条对话:")
- for i, dialogue in enumerate(dialogues[:5], 1): # 只显示前5条
+
+ print(f"\nExtracted {len(dialogues)} dialogues:")
+ for i, dialogue in enumerate(dialogues[:5], 1): # Only show the first 5
print(f"\n [{i}] {dialogue['speaker']} ({dialogue['timestamp']})")
print(f" {dialogue['dialogue']}")
if len(dialogues) > 5:
- print(f"\n ... 还有 {len(dialogues) - 5} 条对话")
-
- print("\n" + "=" * 60)
- print("✓ 插件演示完成!")
- print("=" * 60)
- print("\n提示: 你可以创建自己的插件来实现:")
- print(" - 战斗统计分析")
- print(" - 角色行为分析")
- print(" - 关键词提取")
- print(" - 情感分析")
- print(" - 自动摘要生成")
- print(" - ... 以及更多!")
-
+ print(f"\n ... and {len(dialogues) - 5} more dialogues")
if __name__ == "__main__":
main()