-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
917 lines (772 loc) · 34.2 KB
/
dashboard.py
File metadata and controls
917 lines (772 loc) · 34.2 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
# ──────────────────────────────────────────────────────────
# Project : Snake_AI
# File : dashboard.py
# Author : ProGen18
# Created : 23-02-2026
# Modified : 27-03-2026
# Purpose : Multi-panel performance monitoring dashboard
# ──────────────────────────────────────────────────────────
# ============================================================
# IMPORTS
# ============================================================
import os
import time as _time
from datetime import datetime
import matplotlib.backends.backend_agg as agg
import matplotlib.pyplot as plt
import numpy as np
import pygame
from widgets import Bouton, BoiteSaisie, StatCard, GraphiquePygame
# ============================================================
# DASHBOARD CORE
# ============================================================
# ╔══════════════════════════════════════════════════════════╗
# ║ Dashboard ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Pygame UI orchestration and panel management ║
# ║ • Real-time performance chart rendering ║
# ║ • Neural network internal state visualization ║
# ║ • Training control (Pause/Save/Load/Export) ║
# ╚══════════════════════════════════════════════════════════╝
class Dashboard:
"""
Central visualization and control hub for the Snake AI training process.
"""
def __init__(self, largeur: int = 1600, hauteur: int = 720):
"""
Initialize the dashboard UI components and layout.
Args:
largeur (int): Window width in pixels.
hauteur (int): Window height in pixels.
"""
pygame.init()
self.largeur = largeur
self.hauteur = hauteur
pygame.display.set_caption("Tableau de Bord - IA Snake")
self.ecran = pygame.display.set_mode((largeur, hauteur))
# --- Layout Metrics ---
self.largeur_menu = 250
self.hauteur_bas = 0
self.largeur_contenu = largeur - self.largeur_menu
self.hauteur_contenu = hauteur - self.hauteur_bas
self.quad_l = self.largeur_contenu // 2
self.quad_h = self.hauteur_contenu // 2
# --- Engine State ---
self.state = "RUNNING"
self.en_pause = False
# --- Rendering Surfaces ---
self.surface_jeu = pygame.Surface((self.quad_l, self.quad_h))
self.surface_plot = pygame.Surface((self.quad_l, self.quad_h))
self.surface_global = pygame.Surface((self.quad_l, self.quad_h))
self.surface_nn = pygame.Surface((self.quad_l, self.quad_h))
# --- Typography ---
self.font = pygame.font.SysFont("arial", 15)
self.font_titre = pygame.font.SysFont("arial", 18, bold=True)
self.font_small = pygame.font.SysFont("arial", 10)
self.font_group = pygame.font.SysFont("arial", 9, bold=True)
# --- Panels & Navigation ---
PANELS = ["JEU", "COURBE", "HISTORIQUE", "VISION"]
self._panels = ["JEU", "COURBE", "HISTORIQUE", "VISION"]
self._cycle = PANELS
self._graphique = GraphiquePygame(self.quad_l, self.quad_h)
self._scores_session = []
# --- History Caching ---
self._derniere_maj_historique = 0.0
self._img_historique = None
# --- Drag & Drop State ---
self.titre_offsets = {i: [5, self.quad_h - 30] for i in range(4)}
self.dragging_titre = None
self.drag_start_mouse = (0, 0)
self.drag_start_offset = (0, 0)
self.titre_widths = {i: 150 for i in range(4)}
# --- Pre-calculate Layout ---
self._stats = {}
self.boutons = []
self.auto_screen_active = False
self.screen_interval = 60
self.btn_auto_screen = None
self.lbl_interval = None
self.input_interval = None
self.btn_quitter = None
self.btn_confirmer = None
self.btn_annuler = None
self.boite_nom_fichier = None
self.liste_fichiers = []
self.snapshot = None
# --- Component Boot ---
self._init_interface()
self._init_graphiques()
self.texte_info = ""
# ============================================================
# INITIALIZATION
# ============================================================
def _init_interface(self) -> None:
"""Initialize the sidebar controls, buttons, and input fields."""
x, larg, h = 10, 230, 32
esp = 6
# --- 1. Statistics Cards ---
self._stats = {
"Parties": StatCard("Parties"),
"Record": StatCard("Record", couleur_valeur=(255, 215, 0)),
"Moy100": StatCard("Moy100", couleur_valeur=(0, 200, 220)),
"TPS": StatCard("TPS"),
"Temps": StatCard("Temps"),
"Epsilon": StatCard("Epsilon"),
}
# Vertical placement starting after cards
y = 10 + (6 * StatCard.HAUTEUR) + (esp * 6) + 30
self.boutons = []
def _btn(texte: str, action, couleur: tuple, couleur_s: tuple):
nonlocal y
b = Bouton(x, y, larg, h, texte, action, couleur, couleur_s)
self.boutons.append(b)
y += h + esp
return b
# --- 2. Action Buttons ---
_btn("[S] Sauvegarder", lambda: "OUVRIR_SAVE", (46, 139, 87), (60, 179, 113))
_btn("[L] Charger", lambda: "OUVRIR_LOAD", (70, 130, 180), (100, 149, 237))
self.btn_pause = _btn(
"[II] Pause", lambda: "TOGGLE_PAUSE", (180, 140, 0), (210, 170, 0)
)
_btn("[C] Capture", lambda: "SCREENSHOT", (147, 112, 219), (186, 85, 211))
_btn("[E] Export Excel", lambda: "EXPORT", (34, 139, 34), (50, 205, 50))
y += 20
# --- 3. Automation Controls ---
self.auto_screen_active = False
self.screen_interval = 60
self.btn_auto_screen = Bouton(
x,
y,
larg,
h,
"Auto: NON",
lambda: "TOGGLE_AUTO_SCREEN",
(100, 100, 100),
(120, 120, 120),
)
self.boutons.append(self.btn_auto_screen)
y += h + esp
self.lbl_interval = pygame.font.SysFont("arial", 13).render(
"Intervalle (s):", True, (180, 180, 180)
)
self.input_interval = BoiteSaisie(x + 110, y, 110, 28, texte="60")
y += 34
# --- 4. System Buttons ---
self.btn_quitter = Bouton(
x,
self.hauteur - 50,
larg,
h,
"Quitter",
lambda: "QUIT",
(205, 92, 92),
(255, 99, 71),
)
self.boutons.append(self.btn_quitter)
# Modal components
self.btn_confirmer = Bouton(
0, 0, 120, 35, "Valider", lambda: "CONFIRMER", (46, 139, 87), (60, 179, 113)
)
self.btn_annuler = Bouton(
0, 0, 120, 35, "Annuler", lambda: "ANNULER", (205, 92, 92), (255, 99, 71)
)
self.boite_nom_fichier = BoiteSaisie(
self.largeur // 2 - 100, self.hauteur // 2, 200, 40
)
self.liste_fichiers = []
self.snapshot = None
# ============================================================
# LAYOUT HELPERS
# ============================================================
def _panel_index(self, quadrant: int) -> int:
"""Get the current cycle index for a given quadrant."""
return self._cycle.index(self._panels[quadrant])
def _quad_positions(self) -> list:
"""Get top-left (x, y) coordinates for all four quadrants."""
return [
(self.largeur_menu, 0),
(self.largeur_menu + self.quad_l, 0),
(self.largeur_menu, self.quad_h),
(self.largeur_menu + self.quad_l, self.quad_h),
]
def _clic_titre(self, mx: int, my: int) -> None:
"""Cycle the panel type for a quadrant if clicked."""
zones = self._quad_positions()
for i, (qx, qy) in enumerate(zones):
if qx <= mx < qx + self.quad_l and qy <= my < qy + 22:
cur = self._cycle.index(self._panels[i])
self._panels[i] = self._cycle[(cur + 1) % len(self._cycle)]
return
def _init_graphiques(self) -> None:
"""Initialize Matplotlib backends for global history plots."""
plt.style.use("dark_background")
self.fig_local, self.ax_local = plt.subplots(figsize=(5, 3.5), dpi=100)
self.fig_global, self.ax_global = plt.subplots(figsize=(5, 3.5), dpi=100)
self.img_plot_local = None
self.img_plot_global = None
def __del__(self):
"""Cleanup matplotlib resources."""
try:
plt.close(self.fig_local)
plt.close(self.fig_global)
except:
pass
# ============================================================
# DATA UPDATES
# ============================================================
def update_info(
self, nb_parties: int, temps_total: float, epsilon: float, record: float
) -> None:
"""Deprecated? No-op in current implementation."""
def update_game(self, surface_jeu: pygame.Surface) -> None:
"""
Refresh the game view panel.
Args:
surface_jeu (pygame.Surface): The current frame from the game environment.
"""
for i, (qx, qy) in enumerate(self._quad_positions()):
if self._panels[i] != "JEU":
continue
# Clear background
self.ecran.fill((20, 20, 25), (qx, qy, self.quad_l, self.quad_h))
# Scale and center the game surface
gl, gh = surface_jeu.get_size()
echelle = min(self.quad_l / gl, self.quad_h / gh) * 0.95
nl, nh = int(gl * echelle), int(gh * echelle)
surf_e = pygame.transform.scale(surface_jeu, (nl, nh))
px = qx + (self.quad_l - nl) // 2
py = qy + (self.quad_h - nh) // 2
self.ecran.blit(surf_e, (px, py))
pygame.draw.rect(self.ecran, (100, 100, 100), (px, py, nl, nh), 1)
self._dessiner_cadre(qx, qy, "Vue du Jeu", i)
def update_stats(
self,
nb_parties: int,
temps_total: float,
epsilon: float,
record: float,
tps: int,
) -> None:
"""
Update the sidebar statistics cards.
Args:
nb_parties (int): Total games played.
temps_total (float): Total elapsed time in seconds.
epsilon (float): Current exploration rate.
record (float): All-time high score.
tps (int): Ticks per second (performance).
"""
h, m, s = (
int(temps_total // 3600),
int(temps_total % 3600 // 60),
int(temps_total % 60),
)
self._stats["Parties"].set_valeur(str(nb_parties))
self._stats["Record"].set_valeur(str(record))
self._stats["TPS"].set_valeur(str(tps))
self._stats["Temps"].set_valeur(f"{h:02d}:{m:02d}:{s:02d}")
self._stats["Epsilon"].set_valeur(f"{epsilon:.3f}")
self.texte_info = f"Parties: {nb_parties} | Record: {record} | Eps: {epsilon:.3f} | Temps: {h:02d}:{m:02d}:{s:02d}"
def update_courbe(
self, score: float, moy100: float, numero_partie: int, record: float
) -> None:
"""
Update the real-time performance graph and local session history.
Args:
score (float): Score of the latest game.
moy100 (float): Rolling average of last 100 games.
numero_partie (int): Current game index.
record (float): Current session record.
"""
self._graphique.ajouter_point(score, moy100, numero_partie)
self._graphique.set_record(record)
self._stats["Moy100"].set_valeur(f"{moy100:.1f}")
self._scores_session.append((numero_partie, score))
def update_plots(self, scores, moyennes, record):
"""Deprecated."""
def update_global_plot(self, tous_les_scores):
"""Deprecated."""
def _maj_historique_matplotlib(self, qx: int, qy: int, quad_index: int) -> None:
"""
Regenerate the static global history scatter plot using Matplotlib.
Args:
qx (int): Quadrant X coordinate.
qy (int): Quadrant Y coordinate.
quad_index (int): Index of the quadrant being drawn.
"""
data = self._scores_session
if not data:
return
xs = [p[0] for p in data]
ys = [p[1] for p in data]
# Subsampling for performance if data grows too large
if len(xs) > 10000:
import random
idx = sorted(random.sample(range(len(xs)), 5000))
xs = [xs[i] for i in idx]
ys = [ys[i] for i in idx]
plt.style.use("dark_background")
fig, ax = plt.subplots(figsize=(4, 3), dpi=80)
ax.scatter(xs, ys, s=6, alpha=0.5, c="#00CED1", edgecolors="none")
ax.set_title("Historique Global", fontsize=10, fontweight="bold")
ax.set_xlabel("Parties", fontsize=8)
ax.set_ylabel("Score", fontsize=8)
ax.grid(True, alpha=0.2)
# Blit Matplotlib surface to Pygame
canvas = agg.FigureCanvasAgg(fig)
canvas.draw()
raw = canvas.get_renderer().tostring_rgb()
taille = canvas.get_width_height()
surf = pygame.image.fromstring(raw, taille, "RGB")
self._img_historique = pygame.transform.scale(surf, (self.quad_l, self.quad_h))
plt.close(fig)
self.ecran.blit(self._img_historique, (qx, qy))
self._dessiner_cadre(qx, qy, "Historique Global", quad_index)
def update_nn(self, etat: np.ndarray) -> None:
"""
Visualize the input features of the neural network (Vision).
Args:
etat (np.ndarray): The 26 feature vector used for the state representation.
"""
self.surface_nn.fill((20, 20, 30))
# Feature definitions for labeling/coloring
FEATURES = [
("Dist", (255, 165, 0), False),
("Px", (255, 165, 0), True),
("Py", (255, 165, 0), True),
("DAv", (220, 60, 60), False),
("DDr", (220, 60, 60), False),
("DGa", (220, 60, 60), False),
("Faim", (240, 200, 50), False),
("PosX", (80, 190, 230), False),
("PosY", (80, 190, 230), False),
("FAv", (50, 210, 80), False),
("FDr", (50, 210, 80), False),
("FGa", (50, 210, 80), False),
("→", (160, 90, 220), False),
("↓", (160, 90, 220), False),
("←", (160, 90, 220), False),
("↑", (160, 90, 220), False),
("Lon", (0, 200, 180), False),
("MAv", (150, 150, 160), False),
("MDr", (150, 150, 160), False),
("MGa", (150, 150, 160), False),
("QX", (220, 110, 200), True),
("QY", (220, 110, 200), True),
("D2Av", (180, 50, 50), False),
("D2Dr", (180, 50, 50), False),
("D2Ga", (180, 50, 50), False),
("Den", (190, 130, 70), False),
]
GROUPES = [
("POMME", 0),
("DANGER", 3),
("FAIM/POS", 6),
("FLOOD", 9),
("DIR", 12),
("LON/MUR", 16),
("QUEUE", 20),
("DANG2", 22),
("DENS", 25),
]
GROUPES_FIN = [g[1] for g in GROUPES[1:]] + [26]
n = len(FEATURES)
marge_g = 8
marge_d = 8
marge_h = 18
marge_b = 30
zone_l = self.quad_l - marge_g - marge_d
zone_h = self.quad_h - marge_h - marge_b
n_groupes = len(GROUPES)
sep = 6
total_sep = (n_groupes - 1) * sep
largeur_bar = (zone_l - total_sep) / n
y_base = marge_h + zone_h
y_mid = marge_h + zone_h // 2
pygame.draw.line(
self.surface_nn,
(70, 70, 85),
(marge_g, y_base),
(self.quad_l - marge_d, y_base),
1,
)
def x_bar(i: int) -> int:
groupe_idx = 0
for gi, (_, debut) in enumerate(GROUPES):
if i >= debut:
groupe_idx = gi
return int(marge_g + i * largeur_bar + groupe_idx * sep)
w_bar = max(2, int(largeur_bar - 2))
if etat is not None:
# --- Draw Bars ---
for i, (nom, couleur, signe) in enumerate(FEATURES):
val = float(etat[i])
x = x_bar(i)
# Background track
pygame.draw.rect(
self.surface_nn,
(couleur[0] // 7, couleur[1] // 7, couleur[2] // 7),
(x, marge_h, w_bar, zone_h),
)
if signe:
# Bipolar visualization (centered)
h_moitie = zone_h // 2
hauteur = int(abs(val) * h_moitie)
if hauteur > 0:
y_rect = y_mid - hauteur if val >= 0 else y_mid
pygame.draw.rect(
self.surface_nn, couleur, (x, y_rect, w_bar, hauteur)
)
pygame.draw.line(
self.surface_nn,
(couleur[0] // 2, couleur[1] // 2, couleur[2] // 2),
(x, y_mid),
(x + w_bar, y_mid),
1,
)
else:
# Unipolar visualization (bottom-up)
val = max(0.0, min(1.0, val))
hauteur = int(val * zone_h)
if hauteur > 0:
pygame.draw.rect(
self.surface_nn,
couleur,
(x, y_base - hauteur, w_bar, hauteur),
)
# Label
lbl = self.font_small.render(nom, True, (170, 170, 170))
lbl_rect = lbl.get_rect(centerx=x + w_bar // 2, top=y_base + 4)
self.surface_nn.blit(lbl, lbl_rect)
# --- Draw Group Labels & Separators ---
for gi, (nom_g, debut) in enumerate(GROUPES):
fin = GROUPES_FIN[gi]
x_debut = x_bar(debut)
x_fin = x_bar(fin - 1) + w_bar
cx = (x_debut + x_fin) // 2
lbl_g = self.font_group.render(nom_g, True, FEATURES[debut][1])
self.surface_nn.blit(lbl_g, lbl_g.get_rect(centerx=cx, top=3))
if gi > 0:
sx = x_debut - sep // 2
pygame.draw.line(
self.surface_nn, (50, 50, 65), (sx, marge_h), (sx, y_base), 1
)
# Blit to quadrants
for i, (qx, qy) in enumerate(self._quad_positions()):
if self._panels[i] == "VISION":
self.ecran.blit(self.surface_nn, (qx, qy))
self._dessiner_cadre(qx, qy, "Vision IA", i)
# ============================================================
# FILE OPS & UI
# ============================================================
def _take_screenshot(self) -> None:
"""Capture the current dashboard state to a PNG file."""
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
nom = f"screenshots/capture_{ts}.png"
try:
pygame.image.save(self.ecran, nom)
print(f"📸 Screenshot : {nom}")
except Exception as e:
print(f"Erreur screenshot : {e}")
def _dessiner_cadre(self, x: int, y: int, titre: str, quad_index: int) -> None:
"""
Draw a stylized border and draggable label for a quadrant.
Args:
x (int): Top-left X.
y (int): Top-left Y.
titre (str): Text to display in the label.
quad_index (int): Quadrant ID (0-3).
"""
# Outer border
pygame.draw.rect(self.ecran, (60, 60, 70), (x, y, self.quad_l, self.quad_h), 2)
# Label background
w = len(titre) * 10 + 20
self.titre_widths[quad_index] = w
fond_titre = pygame.Surface((w, 25), pygame.SRCALPHA)
fond_titre.fill((30, 30, 40, 120))
txt = self.font_titre.render(titre, True, (220, 220, 220, 200))
txt.set_alpha(180)
fond_titre.blit(txt, (5, 3))
# Blit using user-defined offsets
ox, oy = self.titre_offsets[quad_index]
self.ecran.blit(fond_titre, (x + ox, y + oy))
def handle_input(self, event: pygame.event.Event):
"""
Process user interactions (clicks, drags, keystrokes).
Args:
event (pygame.event.Event): Pygame event object.
Returns:
Action keyword or tuple (e.g., 'QUIT', ('SAVE', 'name'), etc.)
"""
action = None
# --- 1. Label Dragging & Panel Cycling ---
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mx, my = event.pos
hit_label = False
for i, (qx, qy) in enumerate(self._quad_positions()):
ox, oy = self.titre_offsets[i]
tx, ty = qx + ox, qy + oy
w, h = self.titre_widths[i], 25
if tx <= mx <= tx + w and ty <= my <= ty + h:
self.dragging_titre = i
self.drag_start_mouse = (mx, my)
self.drag_start_offset = (ox, oy)
hit_label = True
break
if not hit_label:
self._clic_titre(mx, my)
elif event.type == pygame.MOUSEMOTION:
if self.dragging_titre is not None:
mx, my = event.pos
dx = mx - self.drag_start_mouse[0]
dy = my - self.drag_start_mouse[1]
self.titre_offsets[self.dragging_titre][0] = (
self.drag_start_offset[0] + dx
)
self.titre_offsets[self.dragging_titre][1] = (
self.drag_start_offset[1] + dy
)
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.dragging_titre = None
# --- 2. State-Dependent Logic ---
if self.state in ("RUNNING", "PAUSED"):
for btn in self.boutons:
res = btn.gerer_evenement(event)
if res == "OUVRIR_SAVE" and self.state == "RUNNING":
self.snapshot = self.ecran.copy()
self.state = "MENU_SAVE"
self.en_pause = True
self.boite_nom_fichier.texte = "mon_modele"
self.boite_nom_fichier.actif = True
elif res == "OUVRIR_LOAD" and self.state == "RUNNING":
self.snapshot = self.ecran.copy()
self.state = "MENU_LOAD"
self.en_pause = True
if not os.path.exists("./model"):
os.makedirs("./model")
self.liste_fichiers = [
f for f in os.listdir("./model") if f.endswith(".pth")
]
elif res == "SCREENSHOT":
self._take_screenshot()
elif res == "QUIT":
action = "QUIT"
elif res == "EXPORT":
action = "EXPORT"
elif res == "TOGGLE_AUTO_SCREEN":
self.auto_screen_active = not self.auto_screen_active
self.btn_auto_screen.texte = (
f"Auto: {'OUI' if self.auto_screen_active else 'NON'}"
)
self.btn_auto_screen.couleur = (
(46, 139, 87) if self.auto_screen_active else (100, 100, 100)
)
elif res == "TOGGLE_PAUSE":
if self.state == "RUNNING":
self.state = "PAUSED"
self.btn_pause.set_texte("[>] Resume")
self.btn_pause.set_couleur((46, 139, 87), (60, 179, 113))
else:
self.state = "RUNNING"
self.btn_pause.set_texte("[II] Pause")
self.btn_pause.set_couleur((180, 140, 0), (210, 170, 0))
if self.state == "RUNNING":
self.input_interval.gerer_evenement(event)
try:
val = int(self.input_interval.texte)
if val > 0:
self.screen_interval = val
except ValueError:
pass
elif self.state == "MENU_SAVE":
if self.btn_confirmer.gerer_evenement(event) == "CONFIRMER":
action, self.state, self.en_pause = (
("SAVE", self.boite_nom_fichier.texte),
"RUNNING",
False,
)
elif self.btn_annuler.gerer_evenement(event) == "ANNULER":
self.state, self.en_pause = "RUNNING", False
res = self.boite_nom_fichier.gerer_evenement(event)
if res:
action, self.state, self.en_pause = ("SAVE", res), "RUNNING", False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.state, self.en_pause = "RUNNING", False
elif self.state == "MENU_LOAD":
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.state, self.en_pause = "RUNNING", False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = event.pos
h_dialog = min(80 + len(self.liste_fichiers) * 35 + 40, 400)
y_dialog = (self.hauteur - h_dialog) // 2
y_start = y_dialog + 60
for i, f in enumerate(self.liste_fichiers):
y = y_start + (i * 35)
dw = 400
dx = (self.largeur - dw) // 2
if dx + 20 < mx < dx + dw - 20 and y < my < y + 30:
action, self.state, self.en_pause = (
("LOAD", f),
"RUNNING",
False,
)
break
return action
# ============================================================
# MAIN LOOP
# ============================================================
def update(self) -> None:
"""Main rendering loop: updates sidebar, panels, and modals."""
if self.state == "RUNNING":
# --- Draw Panels based on cycle ---
for i, (qx, qy) in enumerate(self._quad_positions()):
panel = self._panels[i]
if panel == "COURBE":
self.ecran.fill((15, 15, 20), (qx, qy, self.quad_l, self.quad_h))
self._graphique.dessiner(self.ecran, qx, qy)
self._dessiner_cadre(qx, qy, "Performance", i)
elif panel == "HISTORIQUE":
now = _time.time()
if now - self._derniere_maj_historique >= 5.0:
if self._scores_session:
self._derniere_maj_historique = now
self._maj_historique_matplotlib(qx, qy, i)
else:
self.ecran.fill(
(20, 20, 25), (qx, qy, self.quad_l, self.quad_h)
)
msg = self.font.render(
"En attente de données...", True, (80, 80, 90)
)
self.ecran.blit(
msg,
msg.get_rect(
center=(
qx + self.quad_l // 2,
qy + self.quad_h // 2,
)
),
)
self._dessiner_cadre(qx, qy, "Historique Global", i)
elif self._img_historique:
self.ecran.blit(self._img_historique, (qx, qy))
self._dessiner_cadre(qx, qy, "Historique Global", i)
else:
self.ecran.fill(
(20, 20, 25), (qx, qy, self.quad_l, self.quad_h)
)
self._dessiner_cadre(qx, qy, "Historique Global", i)
# --- Sidebar ---
pygame.draw.rect(
self.ecran, (40, 40, 50), (0, 0, self.largeur_menu, self.hauteur)
)
pygame.draw.line(
self.ecran,
(60, 60, 70),
(self.largeur_menu, 0),
(self.largeur_menu, self.hauteur),
2,
)
lbl = self.font_titre.render("STATS", True, (200, 200, 200))
self.ecran.blit(lbl, (10, 10))
y = 32
for card in self._stats.values():
card.dessiner(self.ecran, 10, y, 230)
y += StatCard.HAUTEUR + 4
# Exploration Bar
try:
eps_val = max(0.0, min(1.0, float(self._stats["Epsilon"]._valeur)))
except:
eps_val = 1.0
barre_y = y + 36
barre_l = int(eps_val * 230)
r, g = int(255 * eps_val), int(255 * (1 - eps_val))
pygame.draw.rect(
self.ecran, (r, g, 0), (10, barre_y, barre_l, 6), border_radius=3
)
pygame.draw.rect(
self.ecran, (60, 60, 70), (10, barre_y, 230, 6), 1, border_radius=3
)
y += 6
pygame.draw.line(self.ecran, (60, 60, 70), (10, y), (240, y))
self.ecran.blit(
self.font_titre.render("CONTRÔLES", True, (200, 200, 200)), (10, y + 4)
)
opts_y = self.btn_auto_screen.rect.y - 26
pygame.draw.line(self.ecran, (60, 60, 70), (10, opts_y), (240, opts_y))
self.ecran.blit(
self.font_titre.render("OPTIONS", True, (200, 200, 200)), (10, opts_y + 4)
)
self.ecran.blit(self.lbl_interval, (10, self.input_interval.rect.y + 5))
for btn in self.boutons:
btn.dessiner(self.ecran)
self.input_interval.dessiner(self.ecran)
# --- Modals ---
if self.state != "RUNNING" and self.snapshot:
self.ecran.blit(self.snapshot, (0, 0))
self._dessiner_fond_modal()
if self.state == "MENU_SAVE":
self._dessiner_dialogue_save()
elif self.state == "MENU_LOAD":
self._dessiner_dialogue_load()
pygame.display.flip()
# ============================================================
# DIALOGUES
# ============================================================
def _dessiner_fond_modal(self) -> None:
"""Draw a semi-transparent overlay for modal windows."""
s = pygame.Surface((self.largeur, self.hauteur), pygame.SRCALPHA)
s.fill((0, 0, 0, 220))
self.ecran.blit(s, (0, 0))
def _dessiner_dialogue_save(self) -> None:
"""Render the model saving popup."""
w, h = 450, 180
x, y = (self.largeur - w) // 2, (self.hauteur - h) // 2
pygame.draw.rect(self.ecran, (50, 50, 60), (x, y, w, h), border_radius=10)
pygame.draw.rect(self.ecran, (100, 100, 120), (x, y, w, h), 2, border_radius=10)
txt = self.font_titre.render("Nom de la sauvegarde :", True, (255, 255, 255))
self.ecran.blit(txt, (x + 20, y + 25))
self.boite_nom_fichier.rect.x = x + 50
self.boite_nom_fichier.rect.y = y + 70
self.boite_nom_fichier.rect.width = w - 100
self.boite_nom_fichier.dessiner(self.ecran)
indice = self.font.render("ECHAP pour annuler", True, (150, 150, 150))
self.ecran.blit(indice, (x + (w - indice.get_width()) // 2, y + 120))
self.btn_confirmer.rect.topleft = (x + 50, y + 115)
self.btn_annuler.rect.topleft = (x + w - 170, y + 115)
self.btn_confirmer.dessiner(self.ecran)
self.btn_annuler.dessiner(self.ecran)
def _dessiner_dialogue_load(self) -> None:
"""Render the model loading selection popup."""
w = 400
h = min(80 + len(self.liste_fichiers) * 35 + 40, 400)
x, y = (self.largeur - w) // 2, (self.hauteur - h) // 2
pygame.draw.rect(self.ecran, (50, 50, 60), (x, y, w, h), border_radius=10)
pygame.draw.rect(self.ecran, (100, 100, 120), (x, y, w, h), 2, border_radius=10)
txt = self.font_titre.render("Choisir un modèle :", True, (255, 255, 255))
self.ecran.blit(txt, (x + 20, y + 20))
if not self.liste_fichiers:
vide = self.font.render("Aucune sauvegarde trouvée", True, (200, 100, 100))
self.ecran.blit(vide, (x + (w - vide.get_width()) // 2, y + 70))
else:
y_start = y + 60
mx, my = pygame.mouse.get_pos()
for i, f in enumerate(self.liste_fichiers):
yf = y_start + i * 35
hover = (x + 20 < mx < x + w - 20) and (yf < my < yf + 30)
if hover:
pygame.draw.rect(
self.ecran,
(70, 130, 180),
(x + 20, yf, w - 40, 30),
border_radius=5,
)
ftxt = self.font.render(
f, True, (255, 255, 255) if hover else (200, 200, 200)
)
self.ecran.blit(ftxt, (x + 30, yf + 6))
indice = self.font.render("ECHAP pour annuler", True, (150, 150, 150))
self.ecran.blit(indice, (x + (w - indice.get_width()) // 2, y + h - 30))