-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidgets.py
More file actions
445 lines (366 loc) · 16.3 KB
/
widgets.py
File metadata and controls
445 lines (366 loc) · 16.3 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
# ──────────────────────────────────────────────────────────
# Project : Snake_AI
# File : widgets.py
# Author : ProGen18
# Created : 23-03-2026
# Modified : 27-03-2026
# Purpose : Defines reusable UI components like buttons, input boxes, and graphs
# ──────────────────────────────────────────────────────────
# ============================================================
# IMPORTS
# ============================================================
from collections import deque
import pygame
# ============================================================
# UI COMPONENTS
# ============================================================
# ╔══════════════════════════════════════════════════════════╗
# ║ Bouton ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Clickable button rendering and hover effects ║
# ║ • Execution of callback functions on click ║
# ╚══════════════════════════════════════════════════════════╝
class Bouton:
"""
Interactive button widget.
Attributes:
rect (pygame.Rect): Bounding box of the button.
texte (str): Button label.
action (callable): Function to call on click.
couleur (tuple): Default background color.
couleur_survol (tuple): Background color when hovered.
"""
def __init__(
self,
x: int,
y: int,
largeur: int,
hauteur: int,
texte: str,
action=None,
couleur: tuple = (70, 130, 180),
couleur_survol: tuple = (100, 160, 210),
):
"""
Initialize the Button.
Args:
x (int): X position.
y (int): Y position.
largeur (int): Button width.
hauteur (int): Button height.
texte (str): Text label.
action (callable): Callback function when clicked. Defaults to None.
couleur (tuple): Base color. Defaults to steel blue.
couleur_survol (tuple): Hover color. Defaults to light steel blue.
"""
self.rect = pygame.Rect(x, y, largeur, hauteur)
self.texte = texte
self.action = action
self.couleur = couleur
self.couleur_survol = couleur_survol
self._font = pygame.font.SysFont("arial", 18)
self.est_survole = False
def set_texte(self, texte: str) -> None:
"""
Update button label.
Args:
texte (str): New button text.
"""
self.texte = texte
def set_couleur(self, couleur: tuple, couleur_survol: tuple) -> None:
"""
Update button colors.
Args:
couleur (tuple): New base color.
couleur_survol (tuple): New hover color.
"""
self.couleur = couleur
self.couleur_survol = couleur_survol
def dessiner(self, surface: pygame.Surface) -> None:
"""
Draw the button to a surface.
Args:
surface (pygame.Surface): The game screen surface.
"""
# --- 1. Background ---
c = self.couleur_survol if self.est_survole else self.couleur
pygame.draw.rect(surface, c, self.rect, border_radius=6)
# --- 2. Border ---
pygame.draw.rect(surface, (180, 180, 180), self.rect, 1, border_radius=6)
# --- 3. Text ---
surf = self._font.render(self.texte, True, (255, 255, 255))
surface.blit(surf, surf.get_rect(center=self.rect.center))
def gerer_evenement(self, event: pygame.event.Event):
"""
Handle mouse motion and clicks.
Args:
event (pygame.event.Event): Triggered UI event.
Returns:
The callback result, or None.
"""
if event.type == pygame.MOUSEMOTION:
self.est_survole = self.rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.rect.collidepoint(event.pos):
if self.action:
return self.action()
return None
# ╔══════════════════════════════════════════════════════════╗
# ║ BoiteSaisie ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Text input field for user entry ║
# ║ • Keyboard event processing ║
# ╚══════════════════════════════════════════════════════════╝
class BoiteSaisie:
"""
Text input box widget.
Attributes:
rect (pygame.Rect): Bounding box of the input field.
actif (bool): Whether the field is currently focused.
"""
def __init__(self, x: int, y: int, largeur: int, hauteur: int, texte: str = ""):
"""
Initialize the Input Box.
Args:
x (int): X position.
y (int): Y position.
largeur (int): Field width.
hauteur (int): Field height.
texte (str): Initial text. Defaults to empty string.
"""
self.rect = pygame.Rect(x, y, largeur, hauteur)
self._texte = texte
self.actif = False
self._font = pygame.font.SysFont("arial", 18)
self._couleur_actif = pygame.Color("dodgerblue2")
self._couleur_inactif = pygame.Color("lightskyblue3")
@property
def texte(self) -> str:
"""
Returns:
str: The current text value.
"""
return self._texte
@texte.setter
def texte(self, value: str) -> None:
"""
Set a new text value.
Args:
value (str): Text to update the box with.
"""
self._texte = value
def gerer_evenement(self, event: pygame.event.Event) -> str | None:
"""
Handle focus and keyboard typing.
Args:
event (pygame.event.Event): Processing keyboard and mouse input events.
Returns:
str | None: Emits the text value on pressing Return.
"""
if event.type == pygame.MOUSEBUTTONDOWN:
self.actif = self.rect.collidepoint(event.pos)
if event.type == pygame.KEYDOWN and self.actif:
if event.key == pygame.K_RETURN:
return self._texte
elif event.key == pygame.K_BACKSPACE:
self._texte = self._texte[:-1]
else:
self._texte += event.unicode
return None
def dessiner(self, surface: pygame.Surface) -> None:
"""
Draw the input box.
Args:
surface (pygame.Surface): The game screen surface.
"""
c = self._couleur_actif if self.actif else self._couleur_inactif
pygame.draw.rect(surface, c, self.rect, 2)
surf = self._font.render(self._texte, True, c)
surface.blit(surf, (self.rect.x + 5, self.rect.y + 5))
# ╔══════════════════════════════════════════════════════════╗
# ║ StatCard ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Displaying simple key-value statistics ║
# ║ • Optional progress bar rendering ║
# ╚══════════════════════════════════════════════════════════╝
class StatCard:
"""
Small card widget to display a single metric.
Attributes:
HAUTEUR (int): Constant height of the card.
"""
HAUTEUR = 52
def __init__(
self, label: str, couleur_valeur: tuple = (255, 255, 255), mode: str = "normal"
):
"""
Initialize the Status Card.
Args:
label (str): Title of the metric.
couleur_valeur (tuple): Color of the displayed value. Defaults to white.
mode (str): Determines layout variation, e.g. 'barre'. Defaults to 'normal'.
"""
self._label = label
self._couleur_valeur = couleur_valeur
self._valeur = ""
self._mode = mode
self._font_label = pygame.font.SysFont("arial", 11)
self._font_valeur = pygame.font.SysFont("arial", 22, bold=True)
def set_valeur(self, valeur: str) -> None:
"""
Update the displayed value.
Args:
valeur (str): The value to display on the card.
"""
self._valeur = valeur
def dessiner(self, surface: pygame.Surface, x: int, y: int, largeur: int) -> None:
"""
Draw the stat card.
Args:
surface (pygame.Surface): The game screen surface.
x (int): X position.
y (int): Y position.
largeur (int): Card width.
"""
# --- 1. Background & Text ---
pygame.draw.rect(
surface, (35, 35, 45), (x, y, largeur, self.HAUTEUR), border_radius=4
)
lbl = self._font_label.render(self._label, True, (140, 140, 140))
surface.blit(lbl, (x + 8, y + 5))
val = self._font_valeur.render(self._valeur, True, self._couleur_valeur)
surface.blit(val, (x + 8, y + 22))
# --- 2. Optional Progress Bar ---
if self._mode == "barre" and self._valeur:
try:
ratio = float(self._valeur)
except ValueError:
ratio = 0.0
ratio = max(0.0, min(1.0, ratio))
barre_y = y + 46
barre_l = int(ratio * largeur)
r = int(255 * ratio)
g = int(255 * (1 - ratio))
pygame.draw.rect(
surface, (r, g, 0), (x, barre_y, barre_l, 4), border_radius=2
)
pygame.draw.rect(
surface, (60, 60, 70), (x, barre_y, largeur, 4), 1, border_radius=2
)
# ╔══════════════════════════════════════════════════════════╗
# ║ GraphiquePygame ║
# ╠══════════════════════════════════════════════════════════╣
# ║ Handles: ║
# ║ • Live plotting of scores and averages using Pygame ║
# ║ • Rendering axes, lines, and record indicators ║
# ╚══════════════════════════════════════════════════════════╝
class GraphiquePygame:
"""
Live line graph component rendered natively in Pygame.
Attributes:
_scores (deque): Sliding window of recent scores.
_moyennes (deque): Sliding window of recent averages.
_numeros (deque): Corresponding game indices.
"""
def __init__(self, largeur: int, hauteur: int):
"""
Initialize the Graph Plotting area.
Args:
largeur (int): Width of the plot area.
hauteur (int): Height of the plot area.
"""
self._l = largeur
self._h = hauteur
self._scores = deque(maxlen=2000)
self._moyennes = deque(maxlen=2000)
self._numeros = deque(maxlen=2000)
self._record = 0.0
self._font = pygame.font.SysFont("arial", 10)
def ajouter_point(self, score: float, moy: float, numero_partie: int) -> None:
"""
Add a new data point to the graph.
Args:
score (float): Round score.
moy (float): 100-round moving average.
numero_partie (int): The game index.
"""
self._scores.append(score)
self._moyennes.append(moy)
self._numeros.append(numero_partie)
def set_record(self, record: float) -> None:
"""
Update the all-time high score for drawing the refernce line.
Args:
record (float): Highest score so far.
"""
self._record = record
def dessiner(self, surface: pygame.Surface, x: int, y: int) -> None:
"""
Draw the entire graph plot.
Args:
surface (pygame.Surface): The game screen to draw on.
x (int): Top-left graph bounding box X.
y (int): Top-left graph bounding box Y.
"""
# --- 1. Background ---
marge = pygame.Rect(x, y, self._l, self._h)
pygame.draw.rect(surface, (15, 15, 20), marge)
if len(self._scores) < 2:
msg = self._font.render("En attente de données...", True, (80, 80, 90))
surface.blit(msg, msg.get_rect(center=marge.center))
return
# --- 2. Chart Layout Setup ---
pad_g, pad_d, pad_h, pad_b = 35, 10, 10, 25
zl = self._l - pad_g - pad_d
zh = self._h - pad_h - pad_b
x0, y0 = x + pad_g, y + pad_h
scores = list(self._scores)
moyennes = list(self._moyennes)
numeros = list(self._numeros)
y_max = max(max(scores), 1.0)
# --- 3. Grid Lines & Y-Axis Labels ---
for i in range(1, 5):
gy = y0 + zh - int(i / 4 * zh)
pygame.draw.line(surface, (40, 40, 50), (x0, gy), (x0 + zl, gy))
lbl = self._font.render(f"{y_max * i / 4:.0f}", True, (80, 80, 90))
surface.blit(lbl, (x + 2, gy - 5))
# Helper to map data points to pixel coordinates
def to_px(idx, val):
px = x0 + int(idx / (len(scores) - 1) * zl)
py = y0 + zh - int(val / y_max * zh)
return (px, max(y0, min(y0 + zh, py)))
# --- 4. Plot Lines ---
pts_s = [to_px(i, v) for i, v in enumerate(scores)]
pygame.draw.lines(surface, (60, 140, 220), False, pts_s, 1)
pts_m = [to_px(i, v) for i, v in enumerate(moyennes)]
pygame.draw.lines(surface, (255, 140, 0), False, pts_m, 2)
# --- 5. Record Line (Dashed) ---
if self._record > 0:
ry = y0 + zh - int(self._record / y_max * zh)
ry = max(y0, min(y0 + zh, ry))
for dx in range(0, zl, 8):
# NOTE: Drawing short dashed lines across width
pygame.draw.line(
surface, (255, 215, 0), (x0 + dx, ry), (x0 + min(dx + 4, zl), ry)
)
# --- 6. X-Axis Labels & Legend ---
lbl_min = self._font.render(str(numeros[0]), True, (80, 80, 90))
lbl_max = self._font.render(str(numeros[-1]), True, (80, 80, 90))
surface.blit(lbl_min, (x0, y0 + zh + 5))
surface.blit(lbl_max, (x0 + zl - lbl_max.get_width(), y0 + zh + 5))
# Legend (Scores = Blue, Moy100 = Orange)
pygame.draw.line(
surface, (60, 140, 220), (x0, y0 + zh + 18), (x0 + 12, y0 + zh + 18)
)
surface.blit(
self._font.render("Score", True, (60, 140, 220)), (x0 + 14, y0 + zh + 13)
)
pygame.draw.line(
surface, (255, 140, 0), (x0 + 60, y0 + zh + 18), (x0 + 72, y0 + zh + 18), 2
)
surface.blit(
self._font.render("Moy100", True, (255, 140, 0)), (x0 + 74, y0 + zh + 13)
)