-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1280 lines (1162 loc) · 48.8 KB
/
Copy pathmain.py
File metadata and controls
1280 lines (1162 loc) · 48.8 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
"""PageInvaders -- VIEW + CONTROLLER (pygame desktop app).
Reads model snapshots from engine.py via the EventBus (Observer pattern) and
never mutates the model directly except through its public commands
(doStep / reset). Persists reports through db.py (SQLite). No networking.
Screens:
MENU -- configure a run or pick a teaching scenario.
SIM -- animated simulation with live panels.
REPORT-- end-of-run summary overlay with a 'Save report' button and the
'Run all 3' headless comparison.
The animation is a clean, readable redesign (not the old Space-Invaders
canvas): an incoming page request glides down to a row of frame slots; a HIT
pulses the matching slot green, a FAULT flashes red and animates the eviction
(with a WRITE-BACK tag for dirty victims). Reference bits show as a ring,
dirty frames are amber, the chosen victim pulses.
Run from source: python main.py
"""
from __future__ import annotations
import math
import random
import sys
import pygame
import db
from engine import (
CFG,
Engine,
EventBus,
SCENARIOS,
build_config,
)
# --- window / layout constants ---------------------------------------------
WIDTH, HEIGHT = 1280, 720
FPS = 60
HUD_H = 62
RIGHT_W = 380
NARR_H = 70
AA_SCALE = 4
# --- palette (clean light theme) ------------------------------------------
C = {
"bg": (244, 246, 252), # very light blue-gray
"bg2": (228, 233, 246), # light blue-gray
"panel": (255, 255, 255), # white
"panel2": (238, 241, 250), # subtle gray
"line": (205, 211, 228), # border
"text": (28, 30, 40), # near-black
"muted": (95, 100, 115), # gray (darkened for contrast on light bg)
"alien": (0, 130, 72), # green: hit / good
"write": (160, 50, 160), # purple: write
"shield": (40, 100, 185), # blue: clean frame
"dirty": (195, 115, 25), # amber: dirty frame
"ring": (185, 145, 35), # gold: ref bit
"victim": (195, 40, 55), # red: fault / victim
"alert": (195, 40, 55), # red: alert
"accent": (0, 130, 72), # green accent
"paper": (255, 255, 255),
"ink": (28, 30, 40),
"loader": (88, 68, 200), # indigo: page loader
"disk": (195, 140, 38), # gold: disk
}
# --- alien sprite pixel-art patterns (symmetric, 11-wide) -----------------
ALIEN_PATTERNS = [
[ # Crab
" X X ",
" X X ",
" XXXXXXX ",
" XX XXX XX ",
"XXXXXXXXXXX",
"X XXXXXXX X",
"X X X X",
" XX XX ",
],
[ # Squid
" X X ",
" XXXXX ",
" XXXXXXX ",
" XX XXX XX ",
" XXXXXXXXX ",
" X X X X ",
" X X ",
" X X ",
],
[ # Octopus
" XXXXX ",
" XXXXXXXXX ",
"XXXXXXXXXXX",
"XXX XXX XXX",
"XXXXXXXXXXX",
" XXX XXX ",
" XX XX ",
"XX XX",
],
]
def _render_alien_surface(pattern: list[str], color: tuple,
pixel_size: int = 3) -> pygame.Surface:
"""Render a pixel-art alien pattern onto a transparent Surface."""
rows = len(pattern)
cols = max(len(r) for r in pattern)
surf = pygame.Surface((cols * pixel_size, rows * pixel_size), pygame.SRCALPHA)
for ry, row in enumerate(pattern):
for cx, ch in enumerate(row):
if ch == "X":
pygame.draw.rect(
surf, color,
(cx * pixel_size, ry * pixel_size, pixel_size, pixel_size),
)
return surf
def ease_out_cubic(t: float) -> float:
return 1 - (1 - t) ** 3
def clamp01(t: float) -> float:
return max(0.0, min(1.0, t))
def mix(a: tuple, b: tuple, t: float) -> tuple:
t = clamp01(t)
n = min(len(a), len(b))
return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(n))
def lerp_point(a, b, t: float) -> tuple[float, float]:
return (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)
class App:
def __init__(self) -> None:
pygame.init()
pygame.display.set_caption("PageInvaders -- Virtual Memory Simulator")
self.screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
self.clock = pygame.time.Clock()
self.fonts = {
"sm": self._make_font(("Segoe UI", "Arial"), 15),
"md": self._make_font(("Segoe UI", "Arial"), 18),
"lg": self._make_font(("Segoe UI", "Arial"), 24, bold=True),
"xl": self._make_font(("Segoe UI", "Arial"), 46, bold=True),
"mono": self._make_font(
("Cascadia Mono", "Consolas", "Courier New"), 24, bold=True),
"mono_sm": self._make_font(
("Cascadia Mono", "Consolas", "Courier New"), 14),
}
db.init()
self.running = False
self.state = "MENU"
self.engine: Engine | None = None
self.bus: EventBus | None = None
self.cfg: dict | None = None
self.playing = False
self.finished = False
self.report_open = False
self.speed = 5
self.acc_ms = 0.0
self.descend = 0.0
self.effects: list[dict] = []
self.narration = ("READY", C["muted"],
"Pick options and launch a simulation.")
self.save_msg = ""
self.compare = None
self.last_report = None
self.scenario_note = ""
self.menu = self._default_menu()
self.buttons: dict[str, pygame.Rect] = {}
self._step_pending = False
# --- page table scroll state ---
self._pt_scroll = 0
self._pt_area: pygame.Rect | None = None
# --- alien sprite assets ---
self._alien_surfs = self._build_alien_surfaces()
self._menu_aliens = self._init_menu_aliens()
self._sim_aliens: list[dict] = []
# --- pre-render alien surfaces at two fidelities -----------------------
def _build_alien_surfaces(self) -> dict:
menu_cols = [
(*C["alien"][:3], 50),
(*C["shield"][:3], 40),
(*C["loader"][:3], 40),
]
sim_cols = [
(*C["alien"][:3], 32),
(*C["shield"][:3], 26),
(*C["loader"][:3], 26),
]
hit_cols = [(*C["alien"][:3], 170)] * 3
fault_cols = [(*C["victim"][:3], 170)] * 3
menu = [_render_alien_surface(ALIEN_PATTERNS[i], menu_cols[i], 4)
for i in range(len(ALIEN_PATTERNS))]
sim = [_render_alien_surface(ALIEN_PATTERNS[i], sim_cols[i], 3)
for i in range(len(ALIEN_PATTERNS))]
sim_hit = [_render_alien_surface(ALIEN_PATTERNS[i], hit_cols[i], 3)
for i in range(len(ALIEN_PATTERNS))]
sim_fault = [_render_alien_surface(ALIEN_PATTERNS[i], fault_cols[i], 3)
for i in range(len(ALIEN_PATTERNS))]
return {"menu": menu, "sim": sim,
"sim_hit": sim_hit, "sim_fault": sim_fault}
def _init_menu_aliens(self) -> list[dict]:
aliens = []
cols, rows = 11, 5
sx, sy = 54, 46
start_x = (WIDTH - cols * sx) // 2
start_y = 180
for r in range(rows):
for c in range(cols):
aliens.append({
"base_x": start_x + c * sx,
"base_y": start_y + r * sy,
"pat": r % len(ALIEN_PATTERNS),
"phase": r * 0.4 + c * 0.18,
})
return aliens
def _init_sim_aliens(self) -> list[dict]:
left_w = WIDTH - RIGHT_W
aliens = []
for i in range(6):
aliens.append({
"x": float(random.randint(40, left_w - 80)),
"y": float(random.randint(HUD_H + 40, HEIGHT - NARR_H - 60)),
"vx": random.choice([-0.35, -0.25, 0.25, 0.35]),
"vy": random.choice([-0.18, 0.18]),
"pat": i % len(ALIEN_PATTERNS),
"phase": random.random() * 6.28,
"flash": 0,
"flash_type": None,
})
return aliens
def _make_font(self, names, size: int, bold: bool = False) -> pygame.font.Font:
for name in names:
path = pygame.font.match_font(name, bold=bold)
if path:
return pygame.font.Font(path, size)
return pygame.font.SysFont(names[0], size, bold=bold)
# --- menu model --------------------------------------------------------
def _default_menu(self) -> dict:
return {
"algoName": "LRU",
"pattern": "LOCALIZED",
"frameCount": 4,
"vpages": 16,
"length": 50,
"writeProb": 0.20,
"locality": 0.85,
"tlbEnabled": True,
"customVpns": None,
}
# =======================================================================
# run lifecycle
# =======================================================================
def start_run(self, cfg: dict) -> None:
self.cfg = cfg
self.bus = EventBus()
self.bus.subscribe("access", self.on_access)
self.engine = Engine(cfg, self.bus)
self.playing = True
self.finished = False
self.report_open = False
self.compare = None
self.save_msg = ""
self.effects = []
self.descend = 0.0
self.acc_ms = 0.0
self.narration = ("READY", C["muted"],
self.scenario_note
or "Space = play/pause, Right arrow = step.")
self.state = "SIM"
self._pt_scroll = 0
self._sim_aliens = self._init_sim_aliens()
def reset_run(self) -> None:
self.engine.reset()
self.playing = True
self.finished = False
self.report_open = False
self.compare = None
self.save_msg = ""
self.effects = []
self.descend = 0.0
self.narration = ("READY", C["muted"], "Simulation reset.")
def advance(self) -> None:
evt = self.engine.doStep()
if evt is None:
self.end_run()
def end_run(self) -> None:
self.playing = False
self.finished = True
self.last_report = self._build_report()
self.report_open = True
self.narration = ("DONE", C["alien"], "Run complete. Review the report.")
# --- Observer callback: model event -> transient visual effects --------
def on_access(self, e: dict) -> None:
self.descend = 0.0
target_pfn = None
if self.engine:
pte = self.engine.pageTable.get(e["vpn"])
if pte and pte.valid:
target_pfn = pte.pfn
self.effects.append({
"type": "route",
"result": e["result"],
"vpn": e["vpn"],
"is_write": e["is_write"],
"pfn": target_pfn,
"t": 0,
"life": 32 if e["result"] == "HIT" else 44,
})
if e["result"] == "HIT":
tag, col = "HIT", C["alien"]
if self.engine.tlbEnabled:
msg = ("TLB HIT -- translation cached, page-table walk skipped."
if e["tlbResult"] == "HIT"
else "TLB MISS but page resident -- walk found it.")
else:
msg = "Page resident -- served from RAM."
else:
if e["victimPfn"] is not None and e["victimVpn"] is not None:
self.effects.append({
"type": "victim", "pfn": e["victimPfn"], "t": 0,
"life": 40 if e["wasDirty"] else 24,
"dirty": e["wasDirty"],
})
tag, col = "FAULT", C["victim"]
if e["victimVpn"] is None:
msg = ("Page not resident -- loaded into a free frame "
"(no eviction yet).")
else:
msg = (f"Page fault -- evicted VPN {e['victimVpn']}"
+ (" (DIRTY -> write-back) "
if e["wasDirty"] else " (clean) ")
+ f"via {self.cfg['algoName']}, "
+ f"then loaded VPN {e['vpn']}.")
self.narration = (tag, col, msg)
# --- alien reaction ---
if self._sim_aliens:
idx = random.randint(0, len(self._sim_aliens) - 1)
a = self._sim_aliens[idx]
if e["result"] == "HIT":
a["flash"] = 22
a["flash_type"] = "hit"
else:
a["flash"] = 32
a["flash_type"] = "fault"
a["vx"] = random.choice([-1.8, 1.8])
a["vy"] = random.choice([-1.2, 1.2])
# =======================================================================
# main loop
# =======================================================================
def run(self) -> None:
self.running = True
while self.running:
dt = self.clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
self._on_key(event)
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self._on_click(event.pos)
elif event.type == pygame.MOUSEWHEEL:
self._on_scroll(event)
if self.state == "SIM":
self._update_sim(dt)
self._draw()
pygame.display.flip()
pygame.quit()
def _on_key(self, event) -> None:
if self.state != "SIM":
return
if event.key == pygame.K_SPACE and not self.finished:
self.playing = not self.playing
elif event.key == pygame.K_RIGHT and not self.finished:
self.playing = False
self._step_pending = True
elif event.key == pygame.K_ESCAPE:
self.report_open = False
self.state = "MENU"
def _on_scroll(self, event) -> None:
if self.state != "SIM" or self._pt_area is None:
return
if self._pt_area.collidepoint(pygame.mouse.get_pos()):
self._pt_scroll = max(0, self._pt_scroll - event.y * 2)
def _animations_busy(self) -> bool:
return any(fx["type"] in ("route", "victim") for fx in self.effects)
def _update_sim(self, dt: int) -> None:
interval = 700 - self.speed * 62
idle = not self._animations_busy()
if idle and not self.finished:
if self._step_pending:
self._step_pending = False
self.advance()
elif self.playing:
self.acc_ms += dt
if self.acc_ms >= interval:
self.acc_ms = 0
self.advance()
self.descend = min(1.0, self.descend + dt / max(120, interval * 0.6))
for fx in self.effects:
fx["t"] += 1
self.effects = [fx for fx in self.effects if fx["t"] < fx["life"]]
# --- update sim aliens ---
left_w = WIDTH - RIGHT_W
for a in self._sim_aliens:
a["x"] += a["vx"]
a["y"] += (a["vy"]
+ math.sin(pygame.time.get_ticks() / 800
+ a["phase"]) * 0.25)
if a["x"] < 10:
a["x"] = float(left_w - 50)
elif a["x"] > left_w - 40:
a["x"] = 10.0
if a["y"] < HUD_H + 10:
a["y"] = float(HEIGHT - NARR_H - 50)
elif a["y"] > HEIGHT - NARR_H - 30:
a["y"] = float(HUD_H + 10)
if a["flash"] > 0:
a["flash"] -= 1
if a["flash"] == 0 and a["flash_type"] is not None:
a["vx"] = random.choice([-0.35, -0.25, 0.25, 0.35])
a["vy"] = random.choice([-0.18, 0.18])
a["flash_type"] = None
# =======================================================================
# drawing helpers
# =======================================================================
def _text(self, key, s, color, x, y, center=False, right=False):
surf = self.fonts[key].render(str(s), True, color)
r = surf.get_rect()
if center:
r.center = (x, y)
elif right:
r.topright = (x, y)
else:
r.topleft = (x, y)
self.screen.blit(surf, r)
return r
def _soft_rect(self, rect, fill, border=None, border_width: int = 0,
radius: int = 6):
rect = pygame.Rect(rect)
if rect.width <= 0 or rect.height <= 0:
return
s = AA_SCALE
surf = pygame.Surface(
(rect.width * s, rect.height * s), pygame.SRCALPHA)
rr = pygame.Rect(0, 0, rect.width * s, rect.height * s)
pygame.draw.rect(surf, fill, rr, border_radius=radius * s)
if border and border_width > 0:
pygame.draw.rect(surf, border, rr,
width=border_width * s,
border_radius=radius * s)
if s != 1:
surf = pygame.transform.smoothscale(surf, rect.size)
self.screen.blit(surf, rect.topleft)
def _soft_circle(self, center, radius: int, color,
border=None, border_width: int = 0):
if radius <= 0:
return
s = AA_SCALE
size = radius * 2
surf = pygame.Surface((size * s, size * s), pygame.SRCALPHA)
c = (radius * s, radius * s)
pygame.draw.circle(surf, color, c, radius * s)
if border and border_width > 0:
pygame.draw.circle(surf, border, c, radius * s,
width=border_width * s)
if s != 1:
surf = pygame.transform.smoothscale(surf, (size, size))
self.screen.blit(surf,
(int(center[0] - radius), int(center[1] - radius)))
def _soft_polyline(self, points, color, width: int = 2):
if len(points) < 2:
return
pad = width * 3 + 6
minx = int(min(p[0] for p in points) - pad)
miny = int(min(p[1] for p in points) - pad)
maxx = int(max(p[0] for p in points) + pad)
maxy = int(max(p[1] for p in points) + pad)
bw = max(1, maxx - minx)
bh = max(1, maxy - miny)
s = AA_SCALE
surf = pygame.Surface((bw * s, bh * s), pygame.SRCALPHA)
pts = [(int((p[0] - minx) * s), int((p[1] - miny) * s))
for p in points]
pygame.draw.lines(surf, color, False, pts, max(1, width * s))
cap = max(1, width * s // 2)
for p in pts:
pygame.draw.circle(surf, color, p, cap)
if s != 1:
surf = pygame.transform.smoothscale(surf, (bw, bh))
self.screen.blit(surf, (minx, miny))
def _partial_path(self, points, progress: float):
progress = clamp01(progress)
if len(points) < 2:
return points
lengths = [math.dist(points[i], points[i + 1])
for i in range(len(points) - 1)]
total = sum(lengths)
if total <= 0:
return points[:1]
remaining = total * progress
out = [points[0]]
for i, length in enumerate(lengths):
a, b = points[i], points[i + 1]
if remaining >= length:
out.append(b)
remaining -= length
else:
out.append(lerp_point(a, b, remaining / max(1, length)))
break
return out
def _point_on_path(self, points, progress: float):
partial = self._partial_path(points, progress)
return partial[-1]
def _draw_beam(self, points, progress: float, color, width: int = 4):
pts = self._partial_path(points, progress)
if len(pts) < 2:
return
fade = 0.55 + 0.45 * math.sin(pygame.time.get_ticks() / 90) ** 2
self._soft_polyline(pts, (*color, int(70 * fade)), width + 8)
self._soft_polyline(pts, (*color, 180), width + 3)
self._soft_polyline(pts, (246, 252, 255, 235), max(1, width - 2))
def _button(self, label, x, y, w, h, key, enabled=True, fill=None):
rect = pygame.Rect(x, y, w, h)
bg = fill or C["panel2"]
border_col = C["line"]
if not enabled:
bg = C["panel"]
elif rect.collidepoint(pygame.mouse.get_pos()):
bg = mix(bg, (0, 0, 0), 0.08)
border_col = mix(C["line"], C["accent"], 0.45)
self._soft_rect(rect, bg, border_col, 1, radius=7)
col = C["text"] if enabled else C["muted"]
self._text("md", label, col, rect.centerx, rect.centery, center=True)
if enabled:
self.buttons[key] = rect
return rect
def _draw_exit_button(self) -> None:
rect = pygame.Rect(WIDTH - 50, 10, 36, 36)
hover = rect.collidepoint(pygame.mouse.get_pos())
fill = C["alert"] if hover else C["panel2"]
self._soft_rect(rect, fill,
C["alert"] if hover else C["line"], 1, radius=7)
a = (rect.x + 12, rect.y + 12)
b = (rect.right - 12, rect.bottom - 12)
c = (rect.right - 12, rect.y + 12)
d = (rect.x + 12, rect.bottom - 12)
self._soft_polyline([a, b], C["text"], 2)
self._soft_polyline([c, d], C["text"], 2)
self.buttons["exit_app"] = rect
def _draw(self) -> None:
self.buttons = {}
self.screen.fill(C["bg"])
if self.state == "MENU":
self._draw_menu()
else:
self._draw_sim()
if self.report_open:
self._draw_report()
self._draw_exit_button()
# --- MENU --------------------------------------------------------------
def _draw_menu(self) -> None:
# draw alien grid behind the form
t = pygame.time.get_ticks() / 1000.0
for al in self._menu_aliens:
ax = al["base_x"] + 28 * math.sin(t * 0.7 + al["phase"])
ay = al["base_y"] + 5 * math.sin(t * 1.4 + al["phase"] * 2.1)
surf = self._alien_surfs["menu"][al["pat"]]
self.screen.blit(surf, (int(ax), int(ay)))
# title with color-cycling glow
glow = 0.5 + 0.5 * math.sin(t * 1.6)
title_col = mix(C["alien"], (180, 255, 220), glow * 0.35)
self._text("xl", "PAGE INVADERS", title_col,
WIDTH // 2, 65, center=True)
self._text("md", "Virtual-memory simulator -- FIFO, LRU, OPT",
C["muted"], WIDTH // 2, 108, center=True)
cx = WIDTH // 2 - 260
y = 155
m = self.menu
# algorithm cycle button
self._text("sm", "Replacement algorithm", C["muted"], cx, y)
self._button(m["algoName"], cx, y + 20, 200, 38, "cycle_algo")
# pattern cycle button
self._text("sm", "Access pattern", C["muted"], cx + 260, y)
self._button(m["pattern"], cx + 260, y + 20, 220, 38, "cycle_pattern")
y += 82
# numeric steppers
self._stepper("Frames (2-10)", m["frameCount"], cx, y, "frames")
self._stepper("Virtual pages (4-32)", m["vpages"],
cx + 260, y, "vpages")
y += 74
self._stepper("Ref length (10-150)", m["length"], cx, y, "length")
self._stepper("Write prob", round(m["writeProb"], 2),
cx + 260, y, "wp")
y += 74
if m["pattern"] == "LOCALIZED":
self._stepper("Locality", round(m["locality"], 2), cx, y, "loc")
# TLB toggle
self._text("sm", "TLB", C["muted"], cx + 260, y)
self._button(
"ON" if m["tlbEnabled"] else "OFF",
cx + 260, y + 20, 130, 38, "toggle_tlb",
fill=C["panel2"] if not m["tlbEnabled"] else (210, 240, 224))
y += 84
# launch
self._button("LAUNCH SIMULATION", WIDTH // 2 - 170, y, 340, 48,
"launch", fill=(204, 236, 218))
y += 68
self._text("sm", "Scenarios:", C["muted"], cx, y)
labels = [("belady", "Belady"), ("textbook", "Textbook"),
("thrash", "Thrashing"), ("locality", "Locality")]
bx = cx + 96
for skey, lab in labels:
self._button(lab, bx, y - 6, 124, 36, f"scn_{skey}")
bx += 134
def _stepper(self, label, value, x, y, key):
self._text("sm", label, C["muted"], x, y)
self._button("-", x, y + 20, 36, 38, f"dec_{key}")
self._soft_rect(pygame.Rect(x + 40, y + 20, 130, 38),
C["panel"], C["line"], 1, radius=7)
self._text("md", value, C["alien"],
x + 40 + 65, y + 20 + 19, center=True)
self._button("+", x + 174, y + 20, 36, 38, f"inc_{key}")
# --- SIM ---------------------------------------------------------------
def _draw_sim(self) -> None:
eng = self.engine
# HUD
pygame.draw.rect(self.screen, C["bg2"],
pygame.Rect(0, 0, WIDTH, HUD_H))
pygame.draw.line(self.screen, C["line"], (0, HUD_H), (WIDTH, HUD_H))
self._text("lg", self.cfg["algoName"], C["alien"], 16, 16)
self._text("mono_sm",
f"step {eng.step}/{len(self.cfg['accesses'])}",
C["text"], 120, 22)
self._button("Pause" if self.playing else "Play",
226, 12, 84, 38, "play")
self._button("Step", 316, 12, 74, 38, "step")
self._button("Reset", 396, 12, 74, 38, "reset")
self._button(f"Speed {self.speed}", 476, 12, 96, 38, "speed")
self._button("Report", WIDTH - 414, 12, 90, 38, "report",
enabled=self.finished)
self._button("Run all 3", WIDTH - 318, 12, 96, 38, "compare")
self._button("TLB " + ("ON" if eng.tlbEnabled else "OFF"),
WIDTH - 216, 12, 84, 38, "tlb",
fill=(210, 240, 224) if eng.tlbEnabled else C["panel2"])
self._button("Menu", WIDTH - 126, 12, 72, 38, "menu")
# left animation area
left_w = WIDTH - RIGHT_W
self._draw_animation(eng, 0, HUD_H, left_w, HEIGHT - HUD_H - NARR_H)
# narration bar
ny = HEIGHT - NARR_H
pygame.draw.rect(self.screen, C["bg2"],
pygame.Rect(0, ny, left_w, NARR_H))
pygame.draw.line(self.screen, C["line"], (0, ny), (left_w, ny))
tag, col, msg = self.narration
# indicator dot
self._soft_circle((12, ny + 18), 5, col)
r = self._text("md", tag, col, 24, ny + 10)
self._text("sm", msg, C["text"], r.right + 12, ny + 14)
# right panels
self._draw_panels(eng, left_w, HUD_H, RIGHT_W, HEIGHT - HUD_H)
def _slot_rects(self, ox, oy, w, h, n: int) -> list[pygame.Rect]:
slot_y = oy + h - 160
sw = min(126, max(64, (w - 44) // max(1, n) - 14))
gap = (w - n * sw) / (n + 1)
return [
pygame.Rect(ox + int(gap + i * (sw + gap)), slot_y, sw, 106)
for i in range(n)
]
def _draw_station(self, rect, label: str, color,
active: bool = False) -> None:
rect = pygame.Rect(rect)
fill = mix(C["panel2"], color, 0.14 if active else 0.06)
border = color if active else C["line"]
bw = 2 if active else 1
self._soft_rect(rect, fill, border, bw, radius=9)
self._text("sm", label,
color if active else C["muted"],
rect.centerx, rect.centery, center=True)
def _draw_page_packet(self, center, vpn, color,
is_write: bool) -> None:
rect = pygame.Rect(0, 0, 54, 42)
rect.center = (int(center[0]), int(center[1]))
self._soft_rect(rect, C["paper"], color, 2, radius=7)
# page corner fold
self._soft_polyline(
[(rect.right - 15, rect.y + 4), (rect.right - 5, rect.y + 14),
(rect.right - 15, rect.y + 14), (rect.right - 15, rect.y + 4)],
(142, 154, 182, 180), 1,
)
self._text("mono", vpn, C["ink"],
rect.centerx, rect.centery + 2, center=True)
if is_write:
self._soft_circle((rect.right - 3, rect.y + 5), 10,
C["write"], C["paper"], 1)
self._text("mono_sm", "W", C["ink"],
rect.right - 3, rect.y + 5, center=True)
def _draw_animation(self, eng, ox, oy, w, h) -> None:
pygame.draw.rect(self.screen, C["bg"],
pygame.Rect(ox, oy, w, h))
# subtle background grid
for gy in range(oy + 42, oy + h - 80, 48):
self._soft_polyline([(ox + 30, gy), (ox + w - 30, gy)],
(*C["line"], 120), 1)
# --- draw ambient aliens behind everything ---
for a in self._sim_aliens:
pidx = a["pat"]
if a["flash"] > 0 and a["flash_type"] == "hit":
surf = self._alien_surfs["sim_hit"][pidx]
elif a["flash"] > 0 and a["flash_type"] == "fault":
surf = self._alien_surfs["sim_fault"][pidx]
else:
surf = self._alien_surfs["sim"][pidx]
self.screen.blit(surf, (int(a["x"]), int(a["y"])))
cx = ox + w // 2
request_pos = (cx, oy + 56)
tlb_rect = pygame.Rect(cx - 190, oy + 118, 138, 52)
pt_rect = pygame.Rect(cx + 48, oy + 118, 168, 52)
loader_rect = pygame.Rect(cx - 94, oy + 232, 188, 56)
disk_rect = pygame.Rect(ox + 36, oy + h - 126, 132, 60)
slot_rects = self._slot_rects(ox, oy, w, h, len(eng.frames))
route = next(
(fx for fx in self.effects if fx["type"] == "route"), None)
victim = next(
(fx for fx in self.effects if fx["type"] == "victim"), None)
active_pfn = route.get("pfn") if route else None
fault_active = bool(route and route["result"] == "FAULT")
dirty_writeback = bool(victim and victim.get("dirty"))
self._soft_circle(request_pos, 38,
(*C["accent"], 24), (*C["accent"], 90), 1)
self._draw_station(tlb_rect,
"TLB" if eng.tlbEnabled else "TLB OFF",
C["shield"], bool(route and eng.tlbEnabled))
self._draw_station(pt_rect, "PAGE TABLE",
C["alien"], bool(route))
self._draw_station(loader_rect, "PAGE LOADER",
C["loader"], fault_active)
self._draw_station(disk_rect, "DISK",
C["disk"], dirty_writeback)
self._soft_polyline(
[request_pos, tlb_rect.center, pt_rect.center],
(*C["line"], 70), 2)
self._soft_polyline(
[pt_rect.center, loader_rect.center],
(*C["line"], 58), 2)
for i, f in enumerate(eng.frames):
self._draw_slot(slot_rects[i], f,
victim and victim["pfn"] == i,
active_pfn == i)
if dirty_writeback and 0 <= victim["pfn"] < len(slot_rects):
k = ease_out_cubic(
clamp01(victim["t"] / victim["life"] * 1.25))
start = (slot_rects[victim["pfn"]].centerx,
slot_rects[victim["pfn"]].y + 8)
self._draw_beam(
[start, loader_rect.center, disk_rect.center],
k, C["disk"], 4)
if (route and route.get("pfn") is not None
and 0 <= route["pfn"] < len(slot_rects)):
target = (slot_rects[route["pfn"]].centerx,
slot_rects[route["pfn"]].y + 8)
path = [request_pos]
if eng.tlbEnabled:
path.append(tlb_rect.center)
path.append(pt_rect.center)
if route["result"] == "FAULT":
path.append(loader_rect.center)
path.append(target)
k = clamp01(route["t"] / route["life"])
progress = ease_out_cubic(clamp01(k * 1.22))
beam_col = (C["alien"] if route["result"] == "HIT"
else C["victim"])
packet_col = C["write"] if route["is_write"] else beam_col
self._draw_beam(path, progress, beam_col,
5 if route["result"] == "HIT" else 6)
self._draw_page_packet(
self._point_on_path(path, progress),
route["vpn"], packet_col, route["is_write"])
if route["result"] == "FAULT":
pulse = 1 - k
self._soft_circle(
loader_rect.center, int(24 + 14 * pulse),
(*C["victim"], int(50 + 80 * pulse)))
else:
acc = (eng.cfg["accesses"][eng.step]
if eng.step < len(eng.cfg["accesses"]) else None)
if acc and not self.finished:
bob = math.sin(pygame.time.get_ticks() / 340) * 3
col = C["write"] if acc.is_write else C["alien"]
self._draw_page_packet(
(request_pos[0], request_pos[1] + bob),
acc.vpn, col, acc.is_write)
# Re-draw station labels so beams don't obscure them.
self._text("sm",
"TLB" if eng.tlbEnabled else "TLB OFF",
C["shield"] if route and eng.tlbEnabled else C["muted"],
tlb_rect.centerx, tlb_rect.centery, center=True)
self._text("sm", "PAGE TABLE",
C["alien"] if route else C["muted"],
pt_rect.centerx, pt_rect.centery, center=True)
self._text("sm", "PAGE LOADER",
C["loader"] if fault_active else C["muted"],
loader_rect.centerx, loader_rect.centery, center=True)
self._text("sm", "DISK",
C["disk"] if dirty_writeback else C["muted"],
disk_rect.centerx, disk_rect.centery, center=True)
self._text("sm", "FRAMES", C["muted"],
ox + 28, slot_rects[0].y - 22)
if self.finished:
self._text("lg", "RUN COMPLETE", C["alien"],
cx, oy + 50, center=True)
def _draw_slot(self, rect, f, is_victim, is_target=False) -> None:
rect = pygame.Rect(rect)
empty = f.vpn is None
base = (C["panel"] if empty
else (C["dirty"] if f.dirty else C["shield"]))
border = (C["accent"] if is_target and not is_victim
else C["line"])
border_w = 2 if is_target else 1
self._soft_rect(rect, base, border, border_w, radius=9)
if not empty:
gloss = pygame.Rect(rect.x + 8, rect.y + 8,
rect.width - 16, 20)
self._soft_rect(gloss, (255, 255, 255, 34), radius=6)
if f.ref_bit and not empty:
self._soft_rect(rect.inflate(-4, -4), (0, 0, 0, 0),
C["ring"], 3, radius=7)
if is_victim:
puls = (0.30
+ 0.35
* abs(math.sin(pygame.time.get_ticks() / 120)))
self._soft_rect(rect, (*C["victim"], int(255 * puls)),
radius=9)
label = "free" if empty else f"VPN {f.vpn}"
ink = C["muted"] if empty else C["text"]
self._text("sm", label, ink,
rect.centerx, rect.y + 14, center=True)
self._text("mono", "-" if empty else f.vpn,
C["muted"] if empty else C["text"],
rect.centerx, rect.y + rect.height // 2, center=True)
self._text("sm", f"PFN {f.pfn}", ink,
rect.centerx, rect.y + rect.height - 18, center=True)
def _draw_panels(self, eng, ox, oy, w, h) -> None:
pygame.draw.rect(self.screen, C["bg2"],
pygame.Rect(ox, oy, w, h))
pygame.draw.line(self.screen, C["line"], (ox, oy), (ox, oy + h))
d = eng.derived()
m = eng.m
y = oy + 12
x = ox + 14
self._text("sm", "STATISTICS", C["muted"], x, y)
y += 24
stats = [
("Hits", m["hits"]),
("Faults (swap-in)", m["faults"]),
("Hit ratio", f"{d['hitRatio']*100:.1f}%"),
("TLB hit ratio",
f"{d['tlbHitRatio']*100:.1f}%"
if eng.tlbEnabled else "n/a"),
("EMAT (avg)", self._fmt_ns(d["avgEmat"])),
("Fault rate (20)", f"{d['windowFault']*100:.0f}%"),
("Swap-out (dirty)", m["dirty_evict"]),
("Evict (clean)", m["clean_evict"]),
]
for k, v in stats:
self._text("sm", k, C["muted"], x, y)
self._text("sm", v, C["alien"], ox + w - 14, y, right=True)
y += 22
# CPU utilization gauge
y += 8
util = max(0, 1 - d["windowFault"])
self._text("sm", "CPU utilization", C["muted"], x, y)
self._text("sm", f"{util*100:.0f}%",
C["alien"], ox + w - 14, y, right=True)
y += 22
gauge = pygame.Rect(x, y, w - 28, 16)
self._soft_rect(gauge, C["panel2"], radius=8)
fillc = (C["alert"] if util < 0.3
else (C["dirty"] if util < 0.6 else C["alien"]))
self._soft_rect(
pygame.Rect(x, y, int((w - 28) * util), 16), fillc, radius=8)
y += 32
# divider
pygame.draw.line(self.screen, C["line"],
(ox + 10, y), (ox + w - 10, y))
y += 12
# page table (styled visual table)
self._text("sm", "PAGE TABLE", C["muted"], x, y)
y += 22
# column positions relative to x
c_vpn = x + 6
c_pfn = x + 56
c_v = x + 116
c_d = x + 152
c_r = x + 188
c_last = x + 230
rw = w - 28 # row width
rh = 22 # row height
dot_r = 5 # dot radius
# header row
hdr_rect = pygame.Rect(x, y, rw, rh)
self._soft_rect(hdr_rect, C["panel2"], radius=4)
hdr_y = y + rh // 2
self._text("mono_sm", "VPN", C["muted"], c_vpn, hdr_y, center=True)
self._text("mono_sm", "PFN", C["muted"], c_pfn, hdr_y, center=True)
self._text("mono_sm", "V", C["muted"], c_v, hdr_y, center=True)
self._text("mono_sm", "D", C["muted"], c_d, hdr_y, center=True)
self._text("mono_sm", "R", C["muted"], c_r, hdr_y, center=True)
self._text("mono_sm", "Last", C["muted"], c_last, hdr_y, center=True)
y += rh + 2
# data rows (scrollable)
all_ptes = list(eng.pageTable.values())
total_rows = len(all_ptes)
avail_h = oy + h - 20 - y
max_visible = max(1, avail_h // (rh + 1))
max_scroll = max(0, total_rows - max_visible)
self._pt_scroll = max(0, min(self._pt_scroll, max_scroll))
# store the scrollable area for mouse-wheel hit testing
self._pt_area = pygame.Rect(x, y, rw, avail_h)
start = self._pt_scroll
end = min(total_rows, start + max_visible)
for idx in range(start, end):