summaryrefslogtreecommitdiffstatshomepage
path: root/examples/plugin_system_demo.py
blob: 1899b3455153666269bc02ffb41b0e825d22bf1f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import sys
import os
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from conventionalrp.plugins import PluginManager
from conventionalrp.core.parser import Parser

sys.path.insert(0, str(Path(__file__).parent / "plugins"))
from dice_analyzer_plugin import DiceAnalyzerPlugin
from combat_tracker_plugin import CombatTrackerPlugin


def demo_basic_plugin_usage():
    manager = PluginManager()
    
    dice_analyzer = DiceAnalyzerPlugin()
    dice_analyzer.initialize()
    manager.register_plugin(dice_analyzer)
    
    combat_tracker = CombatTrackerPlugin()
    combat_tracker.initialize()
    manager.register_plugin(combat_tracker)

    print("\nRegistered Plugins:")
    for plugin_info in manager.list_plugins():
        print(f"  - {plugin_info['name']} v{plugin_info['version']} (type: {plugin_info['type']})")
    
    stats = manager.get_statistics()
    print(f"\nPlugin Statistics: {stats}")


def demo_processor_plugin():
    manager = PluginManager()
    
    combat_tracker = CombatTrackerPlugin()
    combat_tracker.initialize()
    manager.register_plugin(combat_tracker)
    
    combat_log = [
        {"type": "dialogue", "speaker": "战士", "content": "我攻击兽人,造成12点伤害!"},
        {"type": "dialogue", "speaker": "法师", "content": "火球术!造成28点火焰伤害"},
        {"type": "dialogue", "speaker": "牧师", "content": "治疗之光,恢复15点生命值"},
        {"type": "dialogue", "speaker": "战士", "content": "重击!造成18点伤害"},
        {"type": "dialogue", "speaker": "牧师", "content": "群体治疗,恢复10点生命值"},
    ]

    print("\nProcessing Combat Log:")
    from conventionalrp.plugins.base import ProcessorPlugin
    processed_log = manager.execute_plugins(combat_log, plugin_type=ProcessorPlugin)
    
    for token in processed_log:
        if "combat_data" in token:
            print(f"  {token['speaker']}: {token['content']}")
            print(f"    -> {token['combat_data']}")
    
    print("\nCombat Summary:")
    summary = combat_tracker.get_combat_summary()
    print(f"  总伤害: {summary['total_damage']}")
    print(f"  总治疗: {summary['total_healing']}")
    print(f"  净伤害: {summary['net_damage']}")
    print("\n  角色统计:")
    for character, stats in summary['character_stats'].items():
        print(f"    {character}: 造成伤害={stats['damage_dealt']}, 治疗={stats['healing_done']}")


def demo_analyzer_plugin():
    manager = PluginManager()
    
    dice_analyzer = DiceAnalyzerPlugin()
    dice_analyzer.initialize()
    manager.register_plugin(dice_analyzer)
    
    dice_rolls = [
        {"type": "dice", "content": "d20=15", "result": 15},
        {"type": "success", "content": "检定成功"},
        {"type": "dice", "content": "d6=4", "result": 4},
        {"type": "dice", "content": "d20=20", "result": 20},
        {"type": "success", "content": "大成功!Critical hit!"},
        {"type": "dice", "content": "d20=1", "result": 1},
        {"type": "failure", "content": "大失败..."},
        {"type": "dice", "content": "d20=12", "result": 12},
        {"type": "dice", "content": "d6=3", "result": 3},
        {"type": "success", "content": "检定成功"},
    ]

    print("\nDice Roll Data:")
    for roll in dice_rolls:
        if roll["type"] == "dice":
            print(f"  {roll['content']}")
    
    from conventionalrp.plugins.base import AnalyzerPlugin
    analysis = manager.execute_plugins(dice_rolls, plugin_type=AnalyzerPlugin)
    
    print("\nAnalyze result:")
    print(f"  总投掷次数: {analysis['total_rolls']}")
    print(f"  骰子类型分布: {analysis['dice_types']}")
    print(f"  成功次数: {analysis['success_count']}")
    print(f"  失败次数: {analysis['failure_count']}")
    print(f"  大成功次数: {analysis['critical_hits']}")
    print(f"  大失败次数: {analysis['critical_fails']}")
    print(f"  成功率: {analysis['success_rate']:.1%}")
    print(f"  出现极值比率: {analysis['critical_rate']:.1%}")


def demo_plugin_enable_disable():
    manager = PluginManager()
    dice_analyzer = DiceAnalyzerPlugin()
    dice_analyzer.initialize()
    manager.register_plugin(dice_analyzer)
    
    combat_tracker = CombatTrackerPlugin()
    combat_tracker.initialize()
    manager.register_plugin(combat_tracker)

    print("\nInitial State:")
    for plugin_info in manager.list_plugins():
        print(f"  {plugin_info['name']}: {'Enabled' if plugin_info['enabled'] else 'Disabled'}")

    # Disable DiceAnalyzer
    print("\nDisabling DiceAnalyzer...")
    manager.disable_plugin("DiceAnalyzer")
    
    print("\nCurrent State:")
    for plugin_info in manager.list_plugins():
        print(f"  {plugin_info['name']}: {'Enabled' if plugin_info['enabled'] else 'Disabled'}")

    print("\nRe-enabling DiceAnalyzer...")
    manager.enable_plugin("DiceAnalyzer")

    print("\nFinal State:")
    for plugin_info in manager.list_plugins():
        print(f"  {plugin_info['name']}: {'Enabled' if plugin_info['enabled'] else 'Disabled'}")


def demo_plugin_discovery():
    plugin_dir = Path(__file__).parent / "plugins"
    manager = PluginManager(plugin_dirs=[str(plugin_dir)])

    print(f"\nSearching for plugins in directory: {plugin_dir}")
    discovered = manager.discover_plugins()

    print(f"\nFound {len(discovered)} plugin modules:")
    for module in discovered:
        print(f"  - {module}")

    print("\nLoading plugins...")
    for py_file in plugin_dir.glob("*.py"):
        if py_file.name.startswith("_"):
            continue
        
        plugin_class = manager.load_plugin_from_file(str(py_file))
        if plugin_class:
            print(f"  ✓ Successfully loaded: {py_file.name}")


def main():
    try:
        demo_basic_plugin_usage()
        demo_processor_plugin()
        demo_analyzer_plugin()
        demo_plugin_enable_disable()
        demo_plugin_discovery()
        
    except Exception as e:
        print(f"\n{e!r}: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()