DarshanScripts commited on
Commit
ed17564
·
verified ·
1 Parent(s): 5bbab3c

Upload stratego\game_analyzer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. stratego//game_analyzer.py +370 -0
stratego//game_analyzer.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Game Analyzer: Computes detailed statistics from CSV and uses LLM for strategic insights.
3
+
4
+ Flow:
5
+ 1. Read CSV game log
6
+ 2. Compute statistics (piece usage, repetitions, battles, etc.)
7
+ 3. Send structured summary to LLM
8
+ 4. Get Stratego-specific feedback
9
+ 5. Update prompt
10
+ """
11
+
12
+ import os
13
+ import csv
14
+ from typing import List, Dict, Optional
15
+ from dataclasses import dataclass, field
16
+ import ollama
17
+ from stratego.prompt_manager import PromptManager
18
+
19
+
20
+ @dataclass
21
+ class PlayerStats:
22
+ """Statistics for one player in a game."""
23
+ player_id: int
24
+ model_name: str = ""
25
+ total_moves: int = 0
26
+ valid_moves: int = 0
27
+ invalid_moves: int = 0
28
+
29
+ # Piece usage
30
+ moves_by_piece: Dict[str, int] = field(default_factory=dict) # piece_type -> count | number of moves that piece made
31
+
32
+ # Repetition analysis
33
+ move_counts: Dict[str, int] = field(default_factory=dict) # "A5 B5" -> count | how many times this exact move was made
34
+
35
+ # Direction stats
36
+ directions: Dict[str, int] = field(default_factory=dict) # N/S/E/W -> count | counts of move directions
37
+
38
+ # Invalid moves
39
+ invalid_moves_by_piece: Dict[str, int] = field(default_factory=dict)
40
+
41
+
42
+ @dataclass
43
+ class GameStats:
44
+ """Complete statistics for a game."""
45
+ game_id: str
46
+ total_turns: int = 0
47
+ winner: Optional[int] = None
48
+ loss_reason: str = ""
49
+ game_duration_seconds: float = 0
50
+
51
+ player_stats: Dict[int, PlayerStats] = field(default_factory=dict)
52
+
53
+ def __post_init__(self):
54
+ if not self.player_stats:
55
+ self.player_stats = {
56
+ 0: PlayerStats(player_id=0),
57
+ 1: PlayerStats(player_id=1)
58
+ }
59
+
60
+
61
+ def parse_csv_to_stats(csv_path: str) -> GameStats:
62
+ """
63
+ Parse game CSV and compute detailed statistics.
64
+
65
+ Args:
66
+ csv_path: Path to the game CSV file
67
+
68
+ Returns:
69
+ GameStats with computed statistics
70
+ """
71
+ if not os.path.exists(csv_path):
72
+ return GameStats(game_id="unknown")
73
+
74
+ game_id = os.path.basename(csv_path).replace(".csv", "")
75
+ stats = GameStats(game_id=game_id)
76
+
77
+ with open(csv_path, 'r', encoding='utf-8') as f:
78
+ reader = csv.DictReader(f)
79
+
80
+ for row in reader:
81
+ try:
82
+ player = int(row.get('player', 0))
83
+ turn = int(row.get('turn', 0))
84
+ move = row.get('move', '').strip()
85
+ piece_type = row.get('piece_type', 'Unknown')
86
+ from_pos = row.get('from_pos', '')
87
+ outcome = (row.get('outcome') or "").strip().lower()
88
+
89
+ if player not in stats.player_stats:
90
+ stats.player_stats[player] = PlayerStats(player_id=player)
91
+
92
+ ps = stats.player_stats[player]
93
+ ps.total_moves += 1
94
+ ps.model_name = row.get('model_name', '')
95
+
96
+ if outcome == "invalid":
97
+ ps.invalid_moves += 1
98
+ if piece_type:
99
+ ps.invalid_moves_by_piece[piece_type] = (
100
+ ps.invalid_moves_by_piece.get(piece_type, 0) + 1
101
+ )
102
+ stats.total_turns = max(stats.total_turns, turn)
103
+ continue
104
+
105
+ ps.valid_moves += 1
106
+
107
+ # Track piece usage
108
+ if piece_type:
109
+ ps.moves_by_piece[piece_type] = ps.moves_by_piece.get(piece_type, 0) + 1
110
+
111
+ # Track move repetitions
112
+ if move:
113
+ ps.move_counts[move] = ps.move_counts.get(move, 0) + 1
114
+
115
+ # Track direction (computed from positions)
116
+ direction = _compute_direction(from_pos, row.get('to_pos', ''))
117
+ if direction:
118
+ ps.directions[direction] = ps.directions.get(direction, 0) + 1
119
+
120
+ stats.total_turns = max(stats.total_turns, turn)
121
+
122
+ except Exception as e:
123
+ continue
124
+
125
+ return stats
126
+
127
+
128
+ def _compute_direction(from_pos: str, to_pos: str) -> str:
129
+ """Compute move direction from positions."""
130
+ if not from_pos or not to_pos:
131
+ return ""
132
+ try:
133
+ src_row = ord(from_pos[0]) - ord('A')
134
+ dst_row = ord(to_pos[0]) - ord('A')
135
+ src_col = int(from_pos[1:])
136
+ dst_col = int(to_pos[1:])
137
+
138
+ if dst_row < src_row:
139
+ return "N"
140
+ elif dst_row > src_row:
141
+ return "S"
142
+ elif dst_col > src_col:
143
+ return "E"
144
+ elif dst_col < src_col:
145
+ return "W"
146
+ except:
147
+ pass
148
+ return ""
149
+
150
+
151
+ def format_stats_for_llm(stats: GameStats, player_to_analyze: int) -> str:
152
+ """
153
+ Format statistics into a structured summary for LLM analysis.
154
+ """
155
+ ps = stats.player_stats.get(player_to_analyze)
156
+ if not ps:
157
+ return "No data available for this player."
158
+
159
+ lines = []
160
+ lines.append(f"=== STRATEGO GAME ANALYSIS FOR PLAYER {player_to_analyze} ===")
161
+ lines.append(f"Model: {ps.model_name}")
162
+ lines.append(f"Total turns: {stats.total_turns}")
163
+ lines.append(f"Player moves: {ps.total_moves}")
164
+ lines.append(f"Invalid moves: {ps.invalid_moves}")
165
+
166
+ # Winner info
167
+ if stats.winner is not None:
168
+ if stats.winner == player_to_analyze:
169
+ lines.append(f"Result: WON")
170
+ else:
171
+ lines.append(f"Result: LOST")
172
+ if stats.loss_reason:
173
+ lines.append(f"Loss reason: {stats.loss_reason}")
174
+
175
+ # Piece usage breakdown
176
+ lines.append("\n--- PIECE USAGE (valid moves only) ---")
177
+ total_piece_moves = sum(ps.moves_by_piece.values()) or 1
178
+ for piece, count in sorted(ps.moves_by_piece.items(), key=lambda x: -x[1])[:8]:
179
+ pct = (count / total_piece_moves) * 100
180
+ lines.append(f" {piece}: {count} moves ({pct:.1f}%)")
181
+
182
+ # Most repeated moves
183
+ lines.append("\n--- REPEATED MOVES (valid moves only) ---")
184
+ top_repeated = sorted(ps.move_counts.items(), key=lambda x: -x[1])[:5]
185
+ for move, count in top_repeated:
186
+ if count >= 3:
187
+ lines.append(f" '{move}' repeated {count} times")
188
+
189
+ # Direction analysis
190
+ if ps.directions:
191
+ lines.append("\n--- MOVE DIRECTIONS (valid moves only) ---")
192
+ total_dir = sum(ps.directions.values()) or 1
193
+ for d in ['N', 'S', 'E', 'W']:
194
+ count = ps.directions.get(d, 0)
195
+ pct = (count / total_dir) * 100
196
+ direction_name = {'N': 'Forward/North', 'S': 'Backward/South',
197
+ 'E': 'Right/East', 'W': 'Left/West'}.get(d, d)
198
+ lines.append(f" {direction_name}: {pct:.1f}%")
199
+
200
+ lines.append("\n--- INVALID MOVES (by piece) ---")
201
+ if ps.invalid_moves == 0:
202
+ lines.append(" None.")
203
+ else:
204
+ for piece, count in ps.invalid_moves_by_piece.items():
205
+ lines.append(f" {piece}: {count} invalid attempts")
206
+
207
+ return "\n".join(lines)
208
+
209
+
210
+ def analyze_with_llm(stats: GameStats, model_name: str = "mistral:7b", existing_improvements: Optional[List[str]] = None) -> List[str]:
211
+ """
212
+ Send structured stats to LLM for Stratego-specific analysis.
213
+
214
+ Returns list of feedback strings.
215
+ """
216
+ if existing_improvements is None:
217
+ existing_improvements = []
218
+ # Analyze player 0 (or the loser if there was one)
219
+ player_to_analyze = 0
220
+ if stats.winner == 0:
221
+ player_to_analyze = 1 # Analyze the loser for improvement
222
+
223
+ stats_summary = format_stats_for_llm(stats, player_to_analyze)
224
+
225
+ existing_block = ""
226
+ if existing_improvements:
227
+ existing_block = "EXISTING STRATEGIC IMPROVEMENTS (from previous games):\n"
228
+ for fb in existing_improvements:
229
+ existing_block += f"- {fb}\n"
230
+ else:
231
+ existing_block = "There are currently no saved strategic improvements from previous games.\n"
232
+
233
+ prompt = f"""You are an expert Stratego strategy coach. Analyze this game data and provide specific, actionable feedback.
234
+
235
+ STRATEGO RULES REMINDER:
236
+ - Pieces ranked 1 (Spy) to 10 (Marshal). Higher rank wins battles.
237
+ - Scout (rank 2) can move multiple squares and should be used to probe enemy.
238
+ - Miner (rank 3) can defuse Bombs.
239
+ - Spy (rank 1) can defeat Marshal if attacking first.
240
+ - Flag is the objective - capture enemy's Flag to win.
241
+ - Flag and Bombs cannot move.
242
+ - You cannot move your pieces diagonally.
243
+ - You can remove opponent's pieces by attacking them with higher-ranked pieces, but you cannot choose opponent's pieces to move directly.
244
+ - Bombs destroy any piece except Miner.
245
+ - In this log, some moves may be marked as 'invalid'. These are ILLEGAL moves that violate Stratego rules
246
+ (for example, attempting to move a Flag or Bomb, moving in an impossible way, moving upon its own pieces, trying to choose and control opponent's pieces to move directly, trying to move pieces diagonally). Treat these as serious mistakes
247
+ and explain clearly why they are illegal and how to avoid them.
248
+
249
+ {existing_block}
250
+
251
+ {stats_summary}
252
+
253
+ Your job:
254
+ - READ the existing improvements above carefully.
255
+ - DO NOT repeat semantically identical advice.
256
+ - If your advice overlaps with existing points, rephrase it to add NEW insights or more specific suggestions.
257
+ - If this game shows the same mistake as an existing improvement, you may reference it briefly, but focus on adding new details or strategies to address it in existing advice.
258
+ - If the game ended with illegal or invalid moves, look over the board and find out and state what was the problem and prioritize feedback on avoiding those mistakes.
259
+
260
+ Based on this data, provide EXACTLY 3 specific feedback points. Each must:
261
+ 1. Reference specific data from the stats (e.g., "Scout used 67% of the time")
262
+ 2. Explain WHY it's a problem in Stratego strategy
263
+ 3. Give a concrete improvement suggestion
264
+
265
+ Format each point on a new line starting with "•"
266
+ Be specific and use Stratego terminology correctly."""
267
+
268
+ try:
269
+ response = ollama.chat(
270
+ model=model_name,
271
+ messages=[{"role": "user", "content": prompt}],
272
+ options={"temperature": 0.3, "num_predict": 500}
273
+ )
274
+
275
+ content = response['message']['content']
276
+
277
+ # Extract bullet points
278
+ feedback = []
279
+ for line in content.split('\n'):
280
+ line = line.strip()
281
+ if line.startswith('•') or line.startswith('-') or line.startswith('*'):
282
+ clean = line.lstrip('•-* ').strip()
283
+ if clean and len(clean) > 20:
284
+ feedback.append(clean)
285
+
286
+ return feedback[:5]
287
+
288
+ except Exception as e:
289
+ print(f"LLM analysis failed: {e}")
290
+ return []
291
+
292
+ def analyze_and_update_prompt(
293
+ csv_path: str,
294
+ prompts_dir: str = "stratego/prompts",
295
+ logs_dir: str = "logs",
296
+ model_name: str = "mistral:7b",
297
+ models_used: List[str] = None,
298
+ game_duration_seconds: float = None,
299
+ winner: Optional[int] = None,
300
+ total_turns: int = 0
301
+ ):
302
+ """
303
+ Analyze game with computed stats + LLM and update prompt.
304
+ """
305
+ print("\n--- LLM Game Analysis ---")
306
+ print(f"Analyzing: {csv_path}")
307
+
308
+ # Step 1: Parse CSV and compute statistics
309
+ stats = parse_csv_to_stats(csv_path)
310
+ stats.winner = winner
311
+ stats.game_duration_seconds = game_duration_seconds or 0
312
+
313
+ if winner is not None and stats.total_turns > 0:
314
+ stats.loss_reason = "Flag captured or invalid move"
315
+
316
+ # Step 2: Print computed stats
317
+ print(f"\nGame Statistics:")
318
+ print(f" Total turns: {stats.total_turns}")
319
+ print(f" Winner: Player {winner}" if winner is not None else " Winner: Draw/Unknown")
320
+
321
+ for pid, ps in stats.player_stats.items():
322
+ print(f"\n Player {pid} ({ps.model_name}):")
323
+ print(f" Moves: {ps.total_moves}")
324
+ if ps.moves_by_piece:
325
+ top_piece = max(ps.moves_by_piece.items(), key=lambda x: x[1])
326
+ print(f" Most used piece: {top_piece[0]} ({top_piece[1]} times)")
327
+
328
+ # # Step 3: Get LLM feedback
329
+ # feedback = analyze_with_llm(stats, model_name)
330
+
331
+ # if not feedback:
332
+ # print("\nNo feedback generated.")
333
+ # return
334
+
335
+ # print(f"\nStrategic Feedback ({len(feedback)} points):")
336
+ # for fb in feedback:
337
+ # print(f" • {fb}")
338
+
339
+ # Step 4: Update prompt
340
+ manager = PromptManager(prompts_dir, logs_dir)
341
+
342
+ current_prompt_text = manager.get_current_prompt()
343
+ base_prompt_text = manager.get_base_prompt()
344
+
345
+ existing_improvements = manager.extract_improvements(current_prompt_text)
346
+
347
+ feedback = analyze_with_llm(
348
+ stats,
349
+ model_name,
350
+ existing_improvements=existing_improvements
351
+ )
352
+
353
+ merged_improvements = manager.merge_improvements(
354
+ existing_improvements,
355
+ [f"• {fb}" for fb in feedback],
356
+ limit=20
357
+ )
358
+ new_prompt = manager.build_prompt(base_prompt_text, merged_improvements)
359
+
360
+ manager.update_prompt(
361
+ new_prompt,
362
+ reason=f"LLM analysis after {'win' if winner == 0 else 'loss'}: {len(feedback)} insights",
363
+ models=models_used or [],
364
+ mistakes=feedback,
365
+ game_duration_seconds=game_duration_seconds,
366
+ total_turns=total_turns,
367
+ winner=winner
368
+ )
369
+
370
+ print("\nPrompt updated with strategic feedback.")