-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvis.py
More file actions
1035 lines (913 loc) · 43.6 KB
/
vis.py
File metadata and controls
1035 lines (913 loc) · 43.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "aiofiles",
# "fastapi",
# "jinja2",
# "uvicorn[standard]",
# "watchdog",
# ]
# ///
import asyncio
import json
import logging
import time
from pathlib import Path
from typing import Dict, Optional
import aiofiles
import uvicorn
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from jinja2 import Template
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
# --- Configuration ---
BASE_DIR = Path("/tmp/alphasnake")
LIVE_DIR = BASE_DIR / "live"
STATIC_GAME_DIR = BASE_DIR
LOG_LEVEL = logging.INFO
HOST = "0.0.0.0"
PORT = 8000
# Ensure directories exist
LIVE_DIR.mkdir(parents=True, exist_ok=True)
STATIC_GAME_DIR.mkdir(parents=True, exist_ok=True)
# --- Logging Setup ---
logging.basicConfig(level=LOG_LEVEL, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# --- FastAPI App ---
app = FastAPI()
# --- HTML Template (Embedded) ---
# Note: Using Jinja2 Template for variable substitution within the string
html_template_str = """
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Snake Game Visualizer - {{ title_suffix }}</title>
<style>
/* --- CSS Variables for Theme --- */
:root {
--bg-color: #1a1a1a; /* Slightly lighter main background */
--surface-color: #242424; /* Cards, inputs background */
--muted-surface-color: #2d2d2d; /* Less prominent surfaces */
--border-color: #404040;
--text-color: #e0e0e0;
--text-muted-color: #aaaaaa;
--accent-a-primary: #ff5252; /* Red */
--accent-a-secondary: #c62828; /* Darker Red */
--accent-b-primary: #448aff; /* Blue */
--accent-b-secondary: #1565c0; /* Darker Blue */
--portal-color: #6a1b9a; /* Purple for portals */
--portal-highlight-color: #ab47bc;
--wall-color: #555555;
--grid-border-color: #333; /* Color for grid lines */
--font-sans: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
sans-serif;
--font-mono: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
--cell-size: 20px;
--grid-size: 32; /* Default, will be updated by JS */
}
body {
font-family: var(--font-sans);
max-width: 1000px;
margin: 20px auto; /* Add top/bottom margin */
padding: 20px;
background-color: var(--bg-color);
color: var(--text-color);
line-height: 1.6;
}
h1 {
text-align: center;
color: var(--text-color);
margin-bottom: 25px;
}
p {
color: var(--text-muted-color);
margin-bottom: 10px;
}
#game-info {
margin-bottom: 20px; /* Consistent spacing */
padding: 15px;
background-color: var(--surface-color);
border: 1px solid var(--border-color);
border-radius: 6px;
display: flex;
justify-content: space-between;
align-items: center; /* Vertically align items */
font-size: 0.95rem;
min-height: 40px; /* Ensure consistent height */
flex-wrap: wrap; /* Allow wrapping on smaller screens if needed */
}
#game-info > div {
flex: 1; /* Allow divs to take space */
text-align: center;
padding: 5px 10px; /* Add some padding, adjust vertical padding */
min-width: 120px; /* Give elements minimum width */
}
#game-info > div:first-child {
text-align: left;
}
#game-info > div:last-child {
text-align: right;
}
#heuristic-value, #buffer-size-value {
font-weight: bold;
}
#visualization {
display: grid;
grid-template-columns: repeat(var(--grid-size), var(--cell-size));
grid-template-rows: repeat(var(--grid-size), var(--cell-size));
margin-top: 20px;
border: 1px solid var(--grid-border-color); /* Outer border */
margin-left: auto; /* Center the grid */
margin-right: auto; /* Center the grid */
overflow: hidden; /* Prevent content spillover */
/* Set initial size based on default grid size */
width: calc(
var(--grid-size) * var(--cell-size) + (var(--grid-size) - 1) * 0px + 2px /* Adjusted for no gap */
);
height: calc(
var(--grid-size) * var(--cell-size) + (var(--grid-size) - 1) * 0px + 2px /* Adjusted for no gap */
);
}
.cell {
width: var(--cell-size);
height: var(--cell-size);
position: relative;
background-color: var(--muted-surface-color);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
box-sizing: border-box; /* Include border in size */
border-right: 1px solid var(--grid-border-color);
border-bottom: 1px solid var(--grid-border-color);
transition: background-color 0.1s ease; /* Faster transition */
}
/* Remove border from last column and row - adjusted for dynamic grid size */
.cell:nth-child(var(--grid-size)n) {
border-right: none;
}
#visualization > .cell:nth-last-child(-n + var(--grid-size)) {
border-bottom: none;
}
.wall { background-color: var(--wall-color); }
.apple {
width: calc(var(--cell-size) * 0.6); height: calc(var(--cell-size) * 0.6);
border-radius: 50%; background-color: var(--accent-a-primary);
box-shadow: 0 0 4px rgba(255, 82, 82, 0.7);
}
.trap-a, .trap-b {
font-size: calc(var(--cell-size) * 0.8); line-height: 1; font-weight: bold;
text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
}
.trap-a { color: var(--accent-a-primary); }
.trap-b { color: var(--accent-b-primary); }
.portal { background-color: var(--portal-color); cursor: pointer; }
.portal-highlight { background-color: var(--portal-highlight-color); box-shadow: 0 0 8px var(--portal-highlight-color); }
.snake-head {
width: calc(var(--cell-size) * 0.8); height: calc(var(--cell-size) * 0.8);
position: relative; display: flex; align-items: center; justify-content: center;
border-radius: 3px;
}
.snake-head-a { background-color: var(--accent-a-primary); color: white; box-shadow: 0 0 5px var(--accent-a-primary); }
.snake-head-b { background-color: var(--accent-b-primary); color: white; box-shadow: 0 0 5px var(--accent-b-primary); }
.snake-head-text { font-weight: bold; font-size: calc(var(--cell-size) * 0.6); }
.snake-body-a, .snake-body-b {
width: calc(var(--cell-size) * 0.7); height: calc(var(--cell-size) * 0.7);
border-radius: 2px; display: block; opacity: 0.8;
}
.snake-body-a { background-color: var(--accent-a-secondary); }
.snake-body-b { background-color: var(--accent-b-secondary); }
.snake-body-a span, .snake-body-b span { display: none; }
.arrow {
width: 0; height: 0; border-style: solid;
border-width: 0 calc(var(--cell-size) * 0.2) calc(var(--cell-size) * 0.35) calc(var(--cell-size) * 0.2);
border-color: transparent transparent currentColor transparent;
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
}
.north { transform: translate(-50%, -50%) rotate(0deg); }
.northeast { transform: translate(-50%, -50%) rotate(45deg); }
.east { transform: translate(-50%, -50%) rotate(90deg); }
.southeast { transform: translate(-50%, -50%) rotate(135deg); }
.south { transform: translate(-50%, -50%) rotate(180deg); }
.southwest { transform: translate(-50%, -50%) rotate(225deg); }
.west { transform: translate(-50%, -50%) rotate(270deg); }
.northwest { transform: translate(-50%, -50%) rotate(315deg); }
.tooltip {
position: absolute; bottom: calc(100% + 5px); left: 50%;
transform: translateX(-50%); background-color: #333; color: white;
padding: 6px 10px; border-radius: 4px; font-size: 12px;
font-weight: normal; white-space: nowrap; z-index: 10;
pointer-events: none; opacity: 0; transition: opacity 0.2s ease-in-out;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}
.cell:hover .tooltip:not(:empty) { opacity: 1; }
.player-a { color: var(--accent-a-primary); font-weight: bold; }
.player-b { color: var(--accent-b-primary); font-weight: bold; }
#ws-status {
font-size: 0.8em; padding: 2px 6px; border-radius: 4px;
margin-left: 10px; display: inline-block; vertical-align: middle;
}
#ws-status.connected { background-color: #4caf50; color: white; }
#ws-status.disconnected { background-color: #f44336; color: white; }
#ws-status.connecting { background-color: #ff9800; color: white; }
</style>
</head>
<body>
<h1>Snake Game Visualizer - {{ title_suffix }}</h1>
{% if error_message %}
<p style="color: var(--accent-a-primary); text-align: center;">
Error: {{ error_message }}
</p>
{% endif %}
<div id="game-info">
<div id="turn-info">Turn: --</div>
{% if is_live %}
<div id="heuristic-info">Heuristic: <span id="heuristic-value">--</span></div>
<div id="buffer-info">Buffer Size: <span id="buffer-size-value">--</span></div> {# <-- ADDED BUFFER SIZE DISPLAY #}
{% endif %}
<div id="player-info">Current Player: -- {% if is_live %}<span id="ws-status"></span>{% endif %}</div>
</div>
<div id="visualization">
{# Grid cells will be generated by JavaScript #}
</div>
{# Embed initial data for static view #}
<script id="initial-data" type="application/json">
{{ initial_game_state_json | safe if initial_game_state_json else 'null' }}
</script>
<script>
const visualization = document.getElementById("visualization");
const gameInfo = document.getElementById("game-info");
const turnInfoDiv = document.getElementById("turn-info");
const playerInfoDiv = document.getElementById("player-info");
const heuristicInfoDiv = document.getElementById("heuristic-info");
const heuristicValueSpan = document.getElementById("heuristic-value");
const bufferSizeValueSpan = document.getElementById("buffer-size-value"); // <-- Get buffer size span
const initialDataElement = document.getElementById("initial-data");
const wsStatusSpan = document.getElementById("ws-status");
const isLive = {{ is_live | lower }}; // Jinja2 boolean -> JS boolean
const wsUrl = "{{ websocket_url }}"; // Jinja2 variable
const directionClasses = {
North: "north", Northeast: "northeast", East: "east", Southeast: "southeast",
South: "south", Southwest: "southwest", West: "west", Northwest: "northwest",
};
let currentGridSize = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-size'), 10) || 32;
let cellsCache = {}; // Cache cell elements for faster updates
// --- Tooltip Positioning Logic ---
function setupTooltips() {
// Use event delegation on the visualization container
visualization.addEventListener("mouseenter", (event) => {
if (!event.target.classList.contains('cell')) return;
const cell = event.target;
const tooltip = cell.querySelector(".tooltip");
if (!tooltip || !tooltip.textContent) return;
const tooltipRect = tooltip.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const cellRect = cell.getBoundingClientRect(); // Get cell position
// Reset transform first
tooltip.style.transform = `translateX(-50%)`;
// Recalculate rect after reset might be needed if styles change significantly
const currentTooltipRect = tooltip.getBoundingClientRect();
// Check if tooltip goes outside the left edge
if (currentTooltipRect.left < 10) { // Add some padding
const leftOverflow = Math.abs(currentTooltipRect.left);
tooltip.style.transform = `translateX(calc(-50% + ${leftOverflow + 15}px))`;
}
// Check if tooltip goes outside the right edge
else if (currentTooltipRect.right > viewportWidth - 10) { // Add some padding
const rightOverflow = currentTooltipRect.right - viewportWidth;
tooltip.style.transform = `translateX(calc(-50% - ${rightOverflow + 15}px))`;
}
}, true); // Use capture phase
visualization.addEventListener("mouseleave", (event) => {
if (!event.target.classList.contains('cell')) return;
const cell = event.target;
const tooltip = cell.querySelector(".tooltip");
if (tooltip) {
// Optional: Reset transform on mouse leave if needed,
// but might cause flicker if re-entering quickly.
// tooltip.style.transform = `translateX(-50%)`;
}
}, true); // Use capture phase
}
// --- Game Rendering Logic ---
// <-- ADDED bufferSize parameter -->
function renderGame(gameState, heuristic = null, bufferSize = null) {
if (!gameState || !gameState.tiles) {
console.error("Invalid gameState received:", gameState);
visualization.innerHTML = `<p style="color: var(--accent-a-primary); padding: 20px;">Invalid game data received.</p>`;
// Reset info panel if game state is invalid
turnInfoDiv.textContent = `Turn: --`;
playerInfoDiv.innerHTML = `Current Player: -- ${isLive ? wsStatusSpan.outerHTML : ''}`;
if (isLive && heuristicValueSpan) heuristicValueSpan.textContent = '--';
if (isLive && bufferSizeValueSpan) bufferSizeValueSpan.textContent = '--'; // <-- Reset buffer size
return;
}
const {
tiles, trap_mask, portals, snake_a, snake_b,
turn_count, is_player_a, apple_timeline
} = gameState;
// -- Update Grid Size CSS Variable if necessary --
const newGridSize = tiles && tiles.length > 0 ? tiles.length : 32;
if (newGridSize !== currentGridSize) {
console.log(`Grid size changed from ${currentGridSize} to ${newGridSize}`);
currentGridSize = newGridSize;
document.documentElement.style.setProperty("--grid-size", currentGridSize);
// Adjust visualization container size (optional, grid handles layout)
const containerSize = `calc(${currentGridSize} * var(--cell-size) + (${currentGridSize} - 1) * 0px + 2px)`;
visualization.style.width = containerSize;
visualization.style.height = containerSize;
visualization.innerHTML = ''; // Clear grid if size changes
cellsCache = {}; // Clear cache
}
// Update game info
const currentPlayer = is_player_a ? "Player A" : "Player B";
const playerClass = is_player_a ? "player-a" : "player-b";
turnInfoDiv.textContent = `Turn: ${turn_count}`;
playerInfoDiv.innerHTML = `Current Player: <span class="${playerClass}">${currentPlayer}</span> ${isLive ? wsStatusSpan.outerHTML : ''}`; // Keep WS status if live
// Update Heuristic (only if live and element exists)
if (isLive && heuristic !== null && heuristicValueSpan) {
heuristicValueSpan.textContent = heuristic.toFixed(4);
let heuristicColor = 'var(--text-muted-color)';
if (heuristic > 0) heuristicColor = 'var(--accent-a-primary)';
else if (heuristic < 0) heuristicColor = 'var(--accent-b-primary)';
heuristicValueSpan.style.color = heuristicColor;
} else if (heuristicInfoDiv) {
heuristicInfoDiv.style.display = 'none'; // Hide if not live
}
// <-- UPDATE BUFFER SIZE (only if live and element exists) -->
if (isLive && bufferSize !== null && bufferSize !== undefined && bufferSizeValueSpan) {
bufferSizeValueSpan.textContent = bufferSize;
} else if (isLive && bufferSizeValueSpan) {
bufferSizeValueSpan.textContent = '--'; // Show default if value missing
}
// Ensure the parent div is visible only in live mode (handled by Jinja)
const bufferInfoDiv = document.getElementById("buffer-info");
if (bufferInfoDiv) {
bufferInfoDiv.style.display = isLive ? 'block' : 'none'; // Redundant due to Jinja but safe
}
// Convert snake segments (handle potential array format)
const snakeASegments = (snake_a?.segment_queue || []).map(seg => Array.isArray(seg) ? { x: seg[0], y: seg[1] } : seg);
const snakeBSegments = (snake_b?.segment_queue || []).map(seg => Array.isArray(seg) ? { x: seg[0], y: seg[1] } : seg);
// Create map of apple spawns
const appleSpawns = {};
(apple_timeline || []).forEach(([turn, point]) => {
const key = `${point.x},${point.y}`;
if (!appleSpawns[key] || turn < appleSpawns[key].turn) {
appleSpawns[key] = { turn, point };
}
});
// Create map of portal pairs
const portalPairs = {};
if (portals) {
for (let y = 0; y < currentGridSize; y++) {
if (!portals[y]) continue;
for (let x = 0; x < currentGridSize; x++) {
if (portals[y][x] !== null && portals[y][x] !== undefined) {
const dest = portals[y][x];
portalPairs[`${x},${y}`] = dest;
}
}
}
}
// --- Efficient Grid Update ---
const fragment = document.createDocumentFragment();
const cellsToUpdate = new Set(); // Track cells needing DOM update
for (let y = 0; y < currentGridSize; y++) {
if (!tiles[y]) continue;
for (let x = 0; x < currentGridSize; x++) {
if (tiles[y][x] === undefined) continue;
const cellKey = `${x},${y}`;
let cell = cellsCache[cellKey];
let tooltip;
// Create cell if it doesn't exist (initial render or grid resize)
if (!cell) {
cell = document.createElement("div");
cell.className = "cell";
cell.dataset.x = x;
cell.dataset.y = y;
tooltip = document.createElement("div");
tooltip.className = "tooltip";
cell.appendChild(tooltip);
cellsCache[cellKey] = cell;
fragment.appendChild(cell); // Add to fragment for bulk append later
} else {
tooltip = cell.querySelector(".tooltip");
// Reset cell content for update
cell.className = 'cell'; // Base class
while (cell.firstChild && cell.firstChild !== tooltip) {
cell.removeChild(cell.firstChild); // Remove old content except tooltip
}
tooltip.textContent = ''; // Clear tooltip
cellsToUpdate.add(cellKey); // Mark for potential update
}
let currentTooltipText = "";
// --- Determine Cell Content ---
let cellContentElement = null; // e.g., apple div, trap span, snake div
let cellClass = ''; // e.g., 'wall', 'portal'
// Check for portal first
const portalDest = portalPairs[cellKey];
if (portalDest) {
cellClass = 'portal';
currentTooltipText = `Portal to (${portalDest.x}, ${portalDest.y})`;
// Portal hover handled by event delegation now
}
// Add tile content
switch (tiles[y][x]) {
case "Wall":
cellClass = 'wall';
currentTooltipText = appendTooltip(currentTooltipText, "Wall");
break;
case "Apple":
cellContentElement = document.createElement("div");
cellContentElement.className = "apple";
currentTooltipText = appendTooltip(currentTooltipText, "Apple");
break;
default: // Empty or other tile type
// Check for future apple spawns
const appleKey = `${x},${y}`;
if (appleSpawns[appleKey] && appleSpawns[appleKey].turn > turn_count) {
currentTooltipText = appendTooltip(currentTooltipText, `Apple spawns on turn ${appleSpawns[appleKey].turn}`);
}
}
// Add traps (check trap_mask dimensions)
if (trap_mask && trap_mask[y] && trap_mask[y][x] !== undefined && trap_mask[y][x] !== 0) {
const trapValue = trap_mask[y][x];
if (Math.abs(trapValue) > turn_count) {
const trap = document.createElement("span");
trap.className = trapValue > 0 ? "trap-a" : "trap-b";
trap.textContent = "x";
// If other content exists, add trap next to it (might need adjustment)
cellContentElement = trap; // Replace or add logic to combine if needed
const turnsLeft = Math.abs(trapValue) - turn_count;
const player = trapValue > 0 ? "A" : "B";
currentTooltipText = appendTooltip(currentTooltipText, `Trap (${player}) expires in ${turnsLeft} turns`);
}
}
// Check for snake heads
const isSnakeAHead = snakeASegments[0]?.x === x && snakeASegments[0]?.y === y;
const isSnakeBHead = snakeBSegments[0]?.x === x && snakeBSegments[0]?.y === y;
if (isSnakeAHead) {
const head = document.createElement("div");
head.className = "snake-head snake-head-a";
const direction = snake_a?.current_direction;
if (direction && directionClasses[direction]) {
const arrow = document.createElement("div");
arrow.className = `arrow ${directionClasses[direction]}`;
head.appendChild(arrow);
} else {
const text = document.createElement("span");
text.className = "snake-head-text"; text.textContent = "A";
head.appendChild(text);
}
cellContentElement = head; // Head takes precedence
const length = (snake_a?.segment_queue?.length || 0) + (snake_a?.queued_length || 0);
currentTooltipText = appendTooltip(currentTooltipText, `Player A head (Length: ${length}, Sacrifice: ${snake_a?.sacrifice ?? 'N/A'})`);
} else if (isSnakeBHead) {
const head = document.createElement("div");
head.className = "snake-head snake-head-b";
const direction = snake_b?.current_direction;
if (direction && directionClasses[direction]) {
const arrow = document.createElement("div");
arrow.className = `arrow ${directionClasses[direction]}`;
head.appendChild(arrow);
} else {
const text = document.createElement("span");
text.className = "snake-head-text"; text.textContent = "B";
head.appendChild(text);
}
cellContentElement = head; // Head takes precedence
const length = (snake_b?.segment_queue?.length || 0) + (snake_b?.queued_length || 0);
currentTooltipText = appendTooltip(currentTooltipText, `Player B head (Length: ${length}, Sacrifice: ${snake_b?.sacrifice ?? 'N/A'})`);
} else {
// Check for snake body parts (only if not a head)
const isSnakeABody = snakeASegments.some((p, i) => i > 0 && p.x === x && p.y === y);
const isSnakeBBody = snakeBSegments.some((p, i) => i > 0 && p.x === x && p.y === y);
if (isSnakeABody) {
const body = document.createElement("span");
body.className = "snake-body-a";
cellContentElement = body;
currentTooltipText = appendTooltip(currentTooltipText, "Player A body");
} else if (isSnakeBBody) {
const body = document.createElement("span");
body.className = "snake-body-b";
cellContentElement = body;
currentTooltipText = appendTooltip(currentTooltipText, "Player B body");
}
}
// --- Apply Updates to Cell ---
if (cellClass) {
cell.classList.add(cellClass);
}
if (cellContentElement) {
// Insert content before the tooltip
cell.insertBefore(cellContentElement, tooltip);
}
tooltip.textContent = currentTooltipText;
} // end x loop
} // end y loop
// Append newly created cells (if any)
if (fragment.childNodes.length > 0) {
visualization.appendChild(fragment);
}
// Setup tooltips (only needs to be done once after initial full render)
if (visualization.children.length === currentGridSize * currentGridSize && !visualization.dataset.tooltipsSetup) {
setupTooltips();
visualization.dataset.tooltipsSetup = "true"; // Mark as setup
}
}
function appendTooltip(existingText, newText) {
if (!newText) return existingText;
return existingText ? `${existingText} | ${newText}` : newText;
}
// --- WebSocket Logic ---
let socket = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 10;
const reconnectInterval = 3000; // 3 seconds
function connectWebSocket() {
if (!isLive || !wsUrl) return;
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
console.log("WebSocket already open or connecting.");
return;
}
console.log(`Attempting to connect WebSocket (${reconnectAttempts + 1}/${maxReconnectAttempts})...`);
updateWsStatus("connecting", "Connecting...");
socket = new WebSocket(wsUrl);
socket.onopen = (event) => {
console.log("WebSocket connection established.");
updateWsStatus("connected", "Live");
reconnectAttempts = 0; // Reset attempts on successful connection
};
socket.onmessage = (event) => {
// console.log("WebSocket message received:", event.data);
try {
const data = JSON.parse(event.data);
// <-- Pass buffer_size to renderGame -->
if (data.board) {
renderGame(data.board, data.heuristic, data.buffer_size);
} else {
console.warn("Received WebSocket message without 'board' data:", data);
// Optionally render with null board to clear/show error state
renderGame(null, data.heuristic, data.buffer_size);
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
renderGame(null); // Render empty/error state
}
};
socket.onerror = (event) => {
console.error("WebSocket error:", event);
// The 'onclose' event will usually follow an error.
};
socket.onclose = (event) => {
console.log(`WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason || 'N/A'}`);
updateWsStatus("disconnected", "Offline");
socket = null; // Ensure socket is nullified
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
console.log(`Attempting to reconnect in ${reconnectInterval / 1000} seconds...`);
setTimeout(connectWebSocket, reconnectInterval);
} else {
console.error("Max WebSocket reconnect attempts reached.");
updateWsStatus("disconnected", "Failed");
}
};
}
function updateWsStatus(statusClass, statusText) {
// Find the span dynamically each time in case the playerInfoDiv content changes
const currentWsStatusSpan = document.getElementById("ws-status");
if (currentWsStatusSpan) {
currentWsStatusSpan.className = `status-${statusClass}`;
currentWsStatusSpan.textContent = statusText;
} else if (isLive && playerInfoDiv) {
// If span doesn't exist yet, create and append it
// This might happen if playerInfoDiv innerHTML was reset
const newSpan = document.createElement('span');
newSpan.id = 'ws-status';
newSpan.className = `status-${statusClass}`;
newSpan.textContent = statusText;
// Append after the player name span if possible, otherwise just append
const playerSpan = playerInfoDiv.querySelector('.player-a, .player-b');
if (playerSpan && playerSpan.nextSibling) {
playerInfoDiv.insertBefore(newSpan, playerSpan.nextSibling);
} else {
playerInfoDiv.appendChild(newSpan);
}
// Add a space before the status span for better formatting
newSpan.insertAdjacentText('beforebegin', ' ');
}
}
// --- Initial Load ---
document.addEventListener("DOMContentLoaded", () => {
if (isLive) {
// For live view, connect WebSocket. Initial render might be empty or show loading.
renderGame(null); // Render empty grid initially
connectWebSocket();
} else {
// For static view, parse and render the embedded initial data.
try {
const initialJson = initialDataElement.textContent.trim();
if (initialJson && initialJson !== 'null') {
const initialState = JSON.parse(initialJson);
// Static view doesn't have heuristic or buffer size from this source
renderGame(initialState, null, null);
} else {
console.warn("No initial game state data found for static view.");
visualization.innerHTML = `<p style="color: var(--text-muted-color); padding: 20px;">No game data loaded.</p>`;
renderGame(null); // Ensure info panel is also reset
}
} catch (error) {
console.error("Error parsing initial game state JSON:", error);
visualization.innerHTML = `<p style="color: var(--accent-a-primary); padding: 20px;">Error loading initial game data.</p>`;
renderGame(null); // Ensure info panel is also reset
}
}
});
</script>
</body>
</html>
"""
html_template = Template(html_template_str)
# --- WebSocket Management ---
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
self.latest_data: Optional[Dict] = None # Store latest full data packet
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
logger.info(f"WebSocket connected: {websocket.client}")
# Send the latest data immediately if available
if self.latest_data:
try:
await websocket.send_json(self.latest_data)
except Exception as e:
logger.warning(f"Failed to send initial data to new client: {e}")
def disconnect(self, websocket: WebSocket):
if websocket in self.active_connections:
self.active_connections.remove(websocket)
logger.info(f"WebSocket disconnected: {websocket.client}")
async def broadcast(self, data: dict):
self.latest_data = data # Update latest data
if self.active_connections:
# Use asyncio.gather for concurrent sending
results = await asyncio.gather(
*[
self._send_data(websocket, data)
for websocket in self.active_connections
],
return_exceptions=True, # Don't let one failure stop others
)
for i, result in enumerate(results):
if isinstance(result, Exception):
# Avoid index errors if a connection was removed during broadcast
if i < len(self.active_connections):
ws = self.active_connections[i]
logger.error(f"Failed to send data to {ws.client}: {result}")
# Optionally disconnect problematic clients here
# self.disconnect(ws)
# await ws.close()
else:
logger.error(
f"Failed to send data to a client (already disconnected?): {result}"
)
async def _send_data(self, websocket: WebSocket, data: dict):
"""Helper to send data and handle potential errors."""
try:
await websocket.send_json(data)
except WebSocketDisconnect:
self.disconnect(
websocket
) # Already handled by main loop, but good practice
except Exception as e:
# Raise exception to be caught by asyncio.gather
raise RuntimeError(f"Send error for {websocket.client}") from e
manager = ConnectionManager()
# --- Filesystem Watcher ---
class LiveJsonHandler(FileSystemEventHandler):
def __init__(self, queue: asyncio.Queue):
self.queue = queue
self.last_processed_time: float = 0
self.debounce_delay = 0.1 # 100ms debounce
def on_created(self, event: FileSystemEvent):
self._handle_event(event)
def on_modified(self, event: FileSystemEvent):
# Sometimes files are created then quickly modified
self._handle_event(event)
def _handle_event(self, event: FileSystemEvent):
if not event.is_directory and event.src_path.endswith(".json"):
try:
current_time = time.time()
# Basic debounce: ignore events too close together for the same file
# A more robust approach might track file modification times
if current_time - self.last_processed_time > self.debounce_delay:
logger.debug(f"Detected file event: {event.src_path}")
# Put the file path onto the async queue for processing
self.queue.put_nowait(Path(event.src_path))
self.last_processed_time = current_time
else:
logger.debug(f"Debounced file event: {event.src_path}")
except Exception as e:
logger.error(f"Error handling file event {event.src_path}: {e}")
async def watch_live_dir(queue: asyncio.Queue):
event_handler = LiveJsonHandler(queue)
observer = Observer()
observer.schedule(event_handler, str(LIVE_DIR), recursive=False)
observer.start()
logger.info(f"Started watching directory: {LIVE_DIR}")
try:
while True:
# Keep the watcher alive
await asyncio.sleep(1)
except KeyboardInterrupt:
observer.stop()
logger.info("Stopped watching directory.")
except Exception as e:
logger.error(f"Error in directory watcher: {e}")
observer.stop()
finally:
observer.join()
async def process_live_files(queue: asyncio.Queue):
"""Process files from the queue and broadcast updates."""
last_processed_file: Optional[Path] = None
last_mod_time: float = 0.0
while True:
file_path: Optional[Path] = None # Initialize file_path
try:
file_path = await queue.get()
logger.info(f"Processing file: {file_path}")
# Check modification time to handle potential rapid updates/duplicates
try:
current_mod_time = file_path.stat().st_mtime
except FileNotFoundError:
logger.warning(f"File disappeared before processing: {file_path}")
queue.task_done()
continue # Skip this file
# Only process if it's newer than the last processed file
# Or if it's a different file (though filenames are time-based)
# Allow processing if it's the same file but modified later
if file_path == last_processed_file and current_mod_time <= last_mod_time:
logger.debug(
f"Skipping older/same timestamp file: {file_path} ({current_mod_time} <= {last_mod_time})"
)
queue.task_done()
continue
# If it's a different file path, reset last_mod_time check baseline
elif file_path != last_processed_file and current_mod_time <= last_mod_time:
logger.debug(
f"Processing potentially older file (new path): {file_path} ({current_mod_time} vs last {last_mod_time})"
)
# Allow processing, but don't update last_mod_time yet
async with aiofiles.open(file_path, mode="r") as f:
content = await f.read()
game_data = json.loads(content)
# Validate expected structure (basic check)
# Now check for board, heuristic, AND buffer_size
if (
"board" in game_data
and "heuristic" in game_data
and "buffer_size" in game_data
):
await manager.broadcast(game_data)
logger.debug(f"Broadcasted update from: {file_path.name}")
last_processed_file = file_path
last_mod_time = (
current_mod_time # Update time only on successful broadcast
)
else:
missing_keys = [
k
for k in ["board", "heuristic", "buffer_size"]
if k not in game_data
]
logger.warning(
f"Invalid JSON structure in {file_path.name}: Missing keys: {', '.join(missing_keys)}"
)
except json.JSONDecodeError:
if file_path:
logger.error(f"Error decoding JSON from {file_path.name}")
except FileNotFoundError:
# Can happen if file is deleted between detection and processing
if file_path:
logger.warning(f"File not found during processing: {file_path.name}")
except Exception as e:
logger.error(
f"Error processing file {file_path.name if file_path else 'unknown'}: {e}",
exc_info=True, # Log traceback for unexpected errors
)
finally:
# Important: Mark task as done in the queue
queue.task_done()
# --- FastAPI Routes ---
@app.get("/", response_class=HTMLResponse)
async def get_root():
# Redirect root to /live for convenience
return HTMLResponse(
content='<html><head><meta http-equiv="refresh" content="0; url=/live"></head><body>Redirecting to <a href="/live">/live</a>...</body></html>'
)
@app.get("/live", response_class=HTMLResponse)
async def get_live_visualizer(request: Request):
"""Serves the visualizer page configured for live WebSocket updates."""
ws_scheme = "wss" if request.url.scheme == "https" else "ws"
ws_url = f"{ws_scheme}://{request.url.hostname}:{request.url.port}/ws/live"
content = html_template.render(
title_suffix="Live",
is_live=True,
websocket_url=ws_url,
initial_game_state_json="null", # No initial state for live view
error_message=None,
)
return HTMLResponse(content=content)
@app.get("/{game_id_str}", response_class=HTMLResponse)
async def get_static_visualizer(request: Request, game_id_str: str):
"""Serves the visualizer page with data loaded from a static JSON file."""
if not game_id_str.isdigit():
# Avoid trying to load files like 'favicon.ico'
raise HTTPException(status_code=404, detail="Game ID must be a number.")
game_id = int(game_id_str)
file_path = STATIC_GAME_DIR / f"{game_id}.json"
error_msg = None
game_state_json = "null"
if not file_path.is_file():
logger.warning(f"Static game file not found: {file_path}")
error_msg = f"Game file '{game_id}.json' not found in {STATIC_GAME_DIR}."
# Render the page anyway but show the error
# raise HTTPException(status_code=404, detail=f"Game file not found: {file_path.name}")
else:
try:
async with aiofiles.open(file_path, mode="r") as f:
content = await f.read()
# Validate JSON structure before passing
data = json.loads(content)
if isinstance(data, dict): # Basic check if it's an object
game_state_json = json.dumps(data) # Pass the full JSON
else:
error_msg = f"Invalid JSON structure in '{file_path.name}'. Expected a JSON object."
logger.error(error_msg)
except json.JSONDecodeError:
error_msg = f"Error decoding JSON from '{file_path.name}'."
logger.error(error_msg, exc_info=True)
except Exception as e:
error_msg = f"Error reading game file '{file_path.name}': {e}"
logger.error(error_msg, exc_info=True)
content = html_template.render(
title_suffix=f"Game {game_id}",
is_live=False,
websocket_url="", # No WS for static view
initial_game_state_json=game_state_json,
error_message=error_msg,
)
return HTMLResponse(content=content)
@app.websocket("/ws/live")
async def websocket_endpoint(websocket: WebSocket):
"""Handles WebSocket connections for live updates."""
await manager.connect(websocket)
try:
while True:
# Keep connection alive by waiting for a message (or timeout)
# This also implicitly handles client-side disconnects better
# than just sleeping. Set a long timeout if no messages expected.
# If the client sends pings, this will receive them.
await websocket.receive_text() # Wait for messages (or disconnect)
# If you expect pings, you might check the received text:
# text = await websocket.receive_text()
# if text != "ping": process other messages if needed
except WebSocketDisconnect:
logger.info(f"WebSocket {websocket.client} disconnected (expected).")
manager.disconnect(websocket)
except Exception as e: