-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction_processor.py
More file actions
324 lines (263 loc) · 12.6 KB
/
Copy pathaction_processor.py
File metadata and controls
324 lines (263 loc) · 12.6 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""
RabbitMQ-based action processing system for MCP MUD Game
"""
import pika
import json
import asyncio
import threading
from typing import Dict, Any, Callable, Optional, List
from datetime import datetime
import uuid
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_USER, RABBITMQ_PASS, QUEUES
class ActionProcessor:
def __init__(self, game_engine):
"""Initialize action processor with RabbitMQ connection"""
self.game_engine = game_engine
self.connection = None
self.channel = None
self.action_handlers = {}
self.running = False
self._setup_connection()
self._setup_queues()
self._register_action_handlers()
def _setup_connection(self):
"""Setup RabbitMQ connection"""
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
parameters = pika.ConnectionParameters(
host=RABBITMQ_HOST,
port=RABBITMQ_PORT,
credentials=credentials
)
try:
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
print("Connected to RabbitMQ successfully")
except Exception as e:
print(f"Failed to connect to RabbitMQ: {e}")
raise
def _setup_queues(self):
"""Setup RabbitMQ queues"""
for queue_name in QUEUES.values():
self.channel.queue_declare(queue=queue_name, durable=True)
print(f"Queue '{queue_name}' declared")
def _register_action_handlers(self):
"""Register action handlers for different action types"""
self.action_handlers = {
"move_character": self._handle_move_character,
"examine_object": self._handle_examine_object,
"attack_target": self._handle_attack_target,
"cast_spell": self._handle_cast_spell,
"use_item": self._handle_use_item,
"attempt_skill_check": self._handle_skill_check,
"rest_character": self._handle_rest_character,
"get_character_status": self._handle_get_character_status,
# DM actions
"generate_room": self._handle_generate_room,
"add_encounter": self._handle_add_encounter,
"create_custom_ability": self._handle_create_custom_ability,
"update_room_description": self._handle_update_room_description,
"get_dungeon_overview": self._handle_get_dungeon_overview
}
def queue_action(self, action_type: str, player_id: str, parameters: Dict[str, Any]) -> str:
"""Queue an action for processing"""
action_id = str(uuid.uuid4())
action_data = {
"action_id": action_id,
"action_type": action_type,
"player_id": player_id,
"parameters": parameters,
"timestamp": datetime.utcnow().isoformat(),
"status": "queued"
}
# Add to database queue
self.game_engine.db_manager.add_action(action_data)
# Send to RabbitMQ for processing
self.channel.basic_publish(
exchange='',
routing_key=QUEUES["actions"],
body=json.dumps(action_data),
properties=pika.BasicProperties(
delivery_mode=2, # Make message persistent
message_id=action_id,
timestamp=int(datetime.utcnow().timestamp())
)
)
print(f"Action {action_id} queued for player {player_id}")
return action_id
def start_processing(self):
"""Start processing actions from the queue"""
self.running = True
def callback(ch, method, properties, body):
try:
action_data = json.loads(body)
result = self._process_action(action_data)
# Acknowledge message
ch.basic_ack(delivery_tag=method.delivery_tag)
# Send result to events queue
self._send_event(action_data["player_id"], "action_result", result)
except Exception as e:
print(f"Error processing action: {e}")
# Reject message and don't requeue
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
# Set up consumer
self.channel.basic_qos(prefetch_count=1)
self.channel.basic_consume(
queue=QUEUES["actions"],
on_message_callback=callback
)
print("Action processor started. Waiting for actions...")
# Start consuming in a separate thread
def consume():
try:
self.channel.start_consuming()
except Exception as e:
print(f"Error in consumer: {e}")
consumer_thread = threading.Thread(target=consume)
consumer_thread.daemon = True
consumer_thread.start()
def stop_processing(self):
"""Stop processing actions"""
self.running = False
if self.channel and self.channel.is_open:
self.channel.stop_consuming()
if self.connection and self.connection.is_open:
self.connection.close()
def _process_action(self, action_data: Dict[str, Any]) -> Dict[str, Any]:
"""Process a single action"""
action_type = action_data["action_type"]
player_id = action_data["player_id"]
parameters = action_data["parameters"]
if action_type not in self.action_handlers:
return {
"success": False,
"error": f"Unknown action type: {action_type}",
"action_id": action_data["action_id"]
}
try:
handler = self.action_handlers[action_type]
result = handler(player_id, parameters)
result["action_id"] = action_data["action_id"]
result["timestamp"] = datetime.utcnow().isoformat()
return result
except Exception as e:
return {
"success": False,
"error": str(e),
"action_id": action_data["action_id"]
}
def _send_event(self, player_id: str, event_type: str, data: Dict[str, Any]):
"""Send event to events queue"""
event_data = {
"event_id": str(uuid.uuid4()),
"player_id": player_id,
"event_type": event_type,
"data": data,
"timestamp": datetime.utcnow().isoformat()
}
self.channel.basic_publish(
exchange='',
routing_key=QUEUES["events"],
body=json.dumps(event_data),
properties=pika.BasicProperties(delivery_mode=2)
)
# Action Handlers
def _handle_move_character(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle character movement"""
direction = parameters.get("direction")
if not direction:
return {"success": False, "error": "Direction not specified"}
return self.game_engine.move_character(player_id, direction)
def _handle_examine_object(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle object examination"""
target = parameters.get("target")
if not target:
return {"success": False, "error": "Target not specified"}
return self.game_engine.examine_object(player_id, target)
def _handle_attack_target(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle attack action"""
target = parameters.get("target")
weapon = parameters.get("weapon")
if not target:
return {"success": False, "error": "Target not specified"}
return self.game_engine.attack_target(player_id, target, weapon)
def _handle_cast_spell(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle spell casting"""
spell_name = parameters.get("spell_name")
target = parameters.get("target")
if not spell_name:
return {"success": False, "error": "Spell name not specified"}
return self.game_engine.cast_spell(player_id, spell_name, target)
def _handle_use_item(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle item usage"""
item_name = parameters.get("item_name")
target = parameters.get("target")
if not item_name:
return {"success": False, "error": "Item name not specified"}
return self.game_engine.use_item(player_id, item_name, target)
def _handle_skill_check(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle skill check"""
skill_type = parameters.get("skill_type")
target = parameters.get("target")
if not skill_type:
return {"success": False, "error": "Skill type not specified"}
return self.game_engine.attempt_skill_check(player_id, skill_type, target)
def _handle_rest_character(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle character rest"""
return self.game_engine.rest_character(player_id)
def _handle_get_character_status(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle character status request"""
return self.game_engine.get_character_status(player_id)
# DM Action Handlers
def _handle_generate_room(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle room generation"""
theme = parameters.get("theme", "dungeon_corridor")
difficulty = parameters.get("difficulty", "medium")
connections = parameters.get("connections", [])
return self.game_engine.generate_room(theme, difficulty, connections)
def _handle_add_encounter(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle encounter addition"""
room_id = parameters.get("room_id")
encounter_type = parameters.get("encounter_type")
if not room_id or not encounter_type:
return {"success": False, "error": "Room ID and encounter type required"}
return self.game_engine.add_encounter(room_id, encounter_type)
def _handle_create_custom_ability(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle custom ability creation"""
name = parameters.get("name")
description = parameters.get("description")
mechanics = parameters.get("mechanics")
if not all([name, description, mechanics]):
return {"success": False, "error": "Name, description, and mechanics required"}
return self.game_engine.create_custom_ability(name, description, mechanics)
def _handle_update_room_description(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle room description update"""
room_id = parameters.get("room_id")
new_description = parameters.get("new_description")
if not room_id or not new_description:
return {"success": False, "error": "Room ID and new description required"}
return self.game_engine.update_room_description(room_id, new_description)
def _handle_get_dungeon_overview(self, player_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Handle dungeon overview request"""
return self.game_engine.get_dungeon_overview()
def get_events_for_player(self, player_id: str, limit: int = 10) -> List[Dict[str, Any]]:
"""Get recent events for a player"""
events = []
def callback(ch, method, properties, body):
try:
event_data = json.loads(body)
if event_data.get("player_id") == player_id:
events.append(event_data)
if len(events) >= limit:
ch.stop_consuming()
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
print(f"Error processing event: {e}")
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
# Temporarily consume from events queue
self.channel.basic_consume(
queue=QUEUES["events"],
on_message_callback=callback
)
# Consume for a short time
self.connection.process_data_events(time_limit=1)
return events