jsph-tg-rcore-tutorial-user 0.4.14

User-space apps for rCore Tutorial chapters
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
//! Pac-Man game with multi-process ghost AI via pipes and signals.
//!
//! Architecture: parent process renders and handles input; 4 child processes
//! each run one ghost's AI, communicating via pipe pairs and receiving
//! SIGUSR1/SIGUSR2 for frightened/eaten transitions.

use crate::{
    close, exit, fb_flush, fb_info, fb_write, fork, get_time, kill, open, pipe, pipe_read,
    pipe_write, read, sched_yield, sigaction, sigreturn, sleep, wait, write, OpenFlags,
    SignalAction, SignalNo, STDIN,
};

// ============================================================
// Constants
// ============================================================

// Maze dimensions
const MAZE_W: usize = 21;
const MAZE_H: usize = 21;
const CELL_SIZE: usize = 28;

// Framebuffer
const FB_W: usize = 1280;
const FB_H: usize = 800;

// Maze pixel offset (left-aligned with some padding)
const MAZE_PX_X: usize = 40;
const MAZE_PX_Y: usize = (FB_H - MAZE_H * CELL_SIZE) / 2;

// HUD position (right of maze)
const HUD_X: usize = MAZE_PX_X + MAZE_W * CELL_SIZE + 40;
const HUD_Y: usize = MAZE_PX_Y;

// Character size within cell (centered with padding)
const CHAR_SIZE: usize = 20;
const CHAR_PAD: usize = (CELL_SIZE - CHAR_SIZE) / 2;

// Tile buffer for fill_rect (8x8 = 256 bytes max — keep small to avoid stack overflow)
const TILE_SIZE: usize = 8;

// Timing (ticks at ~8 Hz game logic)
const FRAME_MS: usize = 125; // 8 ticks per second
const SCATTER_TICKS: u32 = 56; // 7 seconds
const CHASE_TICKS: u32 = 160; // 20 seconds
const FRIGHT_TICKS: u32 = 48; // 6 seconds
const READY_TICKS: u32 = 16; // 2 seconds
const DYING_TICKS: u32 = 8; // 1 second
const FLASH_TICKS: u32 = 16; // 2 seconds

// Directions
const DIR_UP: u8 = 0;
const DIR_RIGHT: u8 = 1;
const DIR_DOWN: u8 = 2;
const DIR_LEFT: u8 = 3;
const DIR_NONE: u8 = 255;

// Direction deltas: [dy, dx] for UP, RIGHT, DOWN, LEFT
const DX: [i8; 4] = [0, 1, 0, -1];
const DY: [i8; 4] = [-1, 0, 1, 0];

// Ghost indices
const BLINKY: usize = 0;
const PINKY: usize = 1;
const INKY: usize = 2;
const CLYDE: usize = 3;

// Ghost scatter corners (grid coords)
const SCATTER_TARGETS: [[u8; 2]; 4] = [
    [0, 20],  // Blinky: top-right
    [0, 0],   // Pinky: top-left
    [20, 20], // Inky: bottom-right
    [20, 0],  // Clyde: bottom-left
];

// Ghost house position
const GHOST_HOUSE_X: u8 = 10;
const GHOST_HOUSE_Y: u8 = 10;

// Pac-Man start position
const PAC_START_X: u8 = 10;
const PAC_START_Y: u8 = 15;

// Ghost start positions
const GHOST_START: [[u8; 2]; 4] = [
    [8, 10],  // Blinky: above ghost house
    [10, 9],  // Pinky: inside ghost house
    [10, 10], // Inky: inside ghost house
    [10, 11], // Clyde: inside ghost house
];

// Keyboard scancodes
const KEY_W: u8 = 17;
const KEY_A: u8 = 30;
const KEY_S: u8 = 31;
const KEY_D: u8 = 32;
const KEY_UP: u8 = 103;
const KEY_LEFT: u8 = 105;
const KEY_DOWN: u8 = 108;
const KEY_RIGHT: u8 = 106;
const KEY_SPACE: u8 = 57;
const KEY_Q: u8 = 16;
const KEY_ESC: u8 = 1;

// Scoring
const DOT_SCORE: u32 = 10;
const PELLET_SCORE: u32 = 50;
const GHOST_SCORES: [u32; 4] = [200, 400, 800, 1600];

// Initial lives
const INIT_LIVES: u32 = 3;

// Pipe protocol sizes
const PIPE_TO_GHOST: usize = 7;
const _PIPE_FROM_GHOST: usize = 1;

// ============================================================
// Colors (BGRA byte order)
// ============================================================

const BG_VOID: [u8; 4] = [0x00, 0x00, 0x00, 0xFF];
const PATH_COLOR: [u8; 4] = [0x08, 0x08, 0x08, 0xFF];
const WALL_FACE: [u8; 4] = [0xDE, 0x21, 0x21, 0xFF];
const WALL_EDGE: [u8; 4] = [0xFF, 0x52, 0x52, 0xFF];
const WALL_SHADOW: [u8; 4] = [0x80, 0x10, 0x10, 0xFF];
const DOT_COLOR: [u8; 4] = [0x97, 0xB8, 0xFF, 0xFF];
const PELLET_COLOR: [u8; 4] = [0xD0, 0xFF, 0xFF, 0xFF];
const PAC_BODY: [u8; 4] = [0x00, 0xD7, 0xFF, 0xFF];
const PAC_HIGHLIGHT: [u8; 4] = [0x50, 0xEE, 0xFF, 0xFF]; // brighter yellow center
const PAC_MOUTH: [u8; 4] = [0x08, 0x08, 0x08, 0xFF]; // same as path
const GHOST_COLORS: [[u8; 4]; 4] = [
    [0x00, 0x00, 0xFF, 0xFF], // Blinky: red
    [0xC0, 0x80, 0xFF, 0xFF], // Pinky: pink
    [0xDE, 0xFF, 0x00, 0xFF], // Inky: cyan
    [0x52, 0xB8, 0xFF, 0xFF], // Clyde: orange
];
const FRIGHT_BODY: [u8; 4] = [0xB8, 0x18, 0x18, 0xFF];
const GHOST_EYE_WHITE: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF];
const GHOST_EYE_PUPIL: [u8; 4] = [0x40, 0x10, 0x10, 0xFF];
const FRIGHT_EYE: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF];
const GATE_COLOR: [u8; 4] = [0xB4, 0x69, 0xFF, 0xFF]; // hot pink gate
const TEXT_COLOR: [u8; 4] = [0xD0, 0xE8, 0xFF, 0xFF]; // warm cream for score digits
const TEXT_GREEN: [u8; 4] = [0x60, 0xFF, 0x60, 0xFF]; // green for high score
const TEXT_LABEL: [u8; 4] = [0x60, 0x50, 0x80, 0xFF];
const TEXT_DIM: [u8; 4] = [0x40, 0x30, 0x50, 0xFF];
const HUD_BG: [u8; 4] = [0x10, 0x08, 0x08, 0xFF]; // dark HUD background
const HUD_BORDER: [u8; 4] = [0xDE, 0x21, 0x21, 0xFF]; // bright blue border (reuses WALL_FACE)
const READY_COLOR: [u8; 4] = [0x00, 0xD7, 0xFF, 0xFF];
const GAMEOVER_COLOR: [u8; 4] = [0x30, 0x30, 0xFF, 0xFF];

// ============================================================
// Maze layout
// ============================================================
// W=wall, D=dot, P=power pellet, E=empty, G=ghost house, T=tunnel

const CELL_WALL: u8 = 0;
const CELL_DOT: u8 = 1;
const CELL_PELLET: u8 = 2;
const CELL_EMPTY: u8 = 3;
const _CELL_GHOST: u8 = 4;
const _CELL_TUNNEL: u8 = 5;

#[rustfmt::skip]
static INITIAL_MAZE: [u8; MAZE_W * MAZE_H] = [
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,
    0,2,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,2,0,
    0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,
    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
    0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,1,0,
    0,1,1,1,1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,1,0,
    0,0,0,0,1,0,0,0,3,0,0,0,3,0,0,0,1,0,0,0,0,
    0,0,0,0,1,0,3,3,3,4,4,4,3,3,3,0,1,0,0,0,0,
    5,3,3,3,1,0,3,0,0,4,4,4,0,0,3,0,1,3,3,3,5,
    0,0,0,0,1,0,3,0,0,4,4,4,0,0,3,0,1,0,0,0,0,
    0,0,0,0,1,0,3,0,0,0,0,0,0,0,3,0,1,0,0,0,0,
    0,0,0,0,1,0,3,3,3,3,3,3,3,3,3,0,1,0,0,0,0,
    0,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,
    0,1,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,1,0,
    0,2,1,0,1,1,1,1,1,1,3,1,1,1,1,1,1,0,1,2,0,
    0,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,
    0,1,1,1,1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,1,0,
    0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,
    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
];

fn total_dots() -> u32 {
    let mut count = 0u32;
    let mut i = 0;
    while i < MAZE_W * MAZE_H {
        if INITIAL_MAZE[i] == CELL_DOT || INITIAL_MAZE[i] == CELL_PELLET {
            count += 1;
        }
        i += 1;
    }
    count
}

// ============================================================
// Font (5x7 bitmap, scale 2)
// ============================================================

const GLYPH_W: usize = 5;
const GLYPH_H: usize = 7;
const FONT_SCALE: usize = 2;
const CHAR_PX_W: usize = GLYPH_W * FONT_SCALE + 2;

#[rustfmt::skip]
const GLYPHS: [(u8, [u8; 7]); 40] = [
    (b'0', [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110]),
    (b'1', [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110]),
    (b'2', [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111]),
    (b'3', [0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110]),
    (b'4', [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010]),
    (b'5', [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110]),
    (b'6', [0b01110, 0b10000, 0b11110, 0b10001, 0b10001, 0b10001, 0b01110]),
    (b'7', [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000]),
    (b'8', [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110]),
    (b'9', [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b10001, 0b01110]),
    (b'A', [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001]),
    (b'B', [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110]),
    (b'C', [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110]),
    (b'D', [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110]),
    (b'E', [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111]),
    (b'F', [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000]),
    (b'G', [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110]),
    (b'H', [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001]),
    (b'I', [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110]),
    (b'K', [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001]),
    (b'L', [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111]),
    (b'M', [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001]),
    (b'N', [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001]),
    (b'O', [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110]),
    (b'P', [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000]),
    (b'R', [0b11110, 0b10001, 0b10001, 0b11110, 0b10010, 0b10001, 0b10001]),
    (b'S', [0b01110, 0b10001, 0b10000, 0b01110, 0b00001, 0b10001, 0b01110]),
    (b'T', [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100]),
    (b'U', [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110]),
    (b'V', [0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b01010, 0b00100]),
    (b'W', [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001]),
    (b'X', [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001]),
    (b'Y', [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100]),
    (b' ', [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000]),
    (b'-', [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000]),
    (b'!', [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100]),
    (b':', [0b00000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00100, 0b00000]),
    (b'.', [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100]),
    (b'Q', [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101]),
    (b'J', [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100]),
];

// ============================================================
// PRNG (xorshift32)
// ============================================================

static mut RNG_STATE: u32 = 12345;

fn xorshift32() -> u32 {
    unsafe {
        let mut x = RNG_STATE;
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        RNG_STATE = x;
        x
    }
}

fn seed_rng(s: u32) {
    unsafe {
        RNG_STATE = if s == 0 { 1 } else { s };
    }
}

// ============================================================
// Rendering helpers
// ============================================================

/// Fill a rectangle with a solid color using 16x16 tile writes.
fn fill_rect(x: usize, y: usize, w: usize, h: usize, color: [u8; 4]) {
    if w == 0 || h == 0 {
        return;
    }
    // Build a row of TILE_SIZE pixels
    let mut tile = [0u8; TILE_SIZE * TILE_SIZE * 4];
    for i in 0..TILE_SIZE * TILE_SIZE {
        tile[i * 4] = color[0];
        tile[i * 4 + 1] = color[1];
        tile[i * 4 + 2] = color[2];
        tile[i * 4 + 3] = color[3];
    }

    let mut ry = 0;
    while ry < h {
        let th = if ry + TILE_SIZE <= h {
            TILE_SIZE
        } else {
            h - ry
        };
        let mut rx = 0;
        while rx < w {
            let tw = if rx + TILE_SIZE <= w {
                TILE_SIZE
            } else {
                w - rx
            };
            fb_write(
                (x + rx) as u32,
                (y + ry) as u32,
                tw as u32,
                th as u32,
                tile.as_ptr(),
            );
            rx += TILE_SIZE;
        }
        ry += TILE_SIZE;
    }
}

/// Draw a single glyph character at pixel position.
/// Renders row-by-row (40-byte row buffer) to avoid a 560-byte sprite buffer.
fn draw_char(x: usize, y: usize, ch: u8, color: [u8; 4]) {
    let glyph = match GLYPHS.iter().find(|(c, _)| *c == ch.to_ascii_uppercase()) {
        Some((_, rows)) => rows,
        None => return,
    };
    let pw = GLYPH_W * FONT_SCALE; // 10
    for gr in 0..GLYPH_H {
        for sr in 0..FONT_SCALE {
            // One row: pw pixels * 4 bytes = 40 bytes
            let mut row_buf = [0u8; 10 * 4];
            for gc in 0..GLYPH_W {
                let on = (glyph[gr] >> (GLYPH_W - 1 - gc)) & 1 == 1;
                for sc in 0..FONT_SCALE {
                    let idx = (gc * FONT_SCALE + sc) * 4;
                    if on {
                        row_buf[idx] = color[0];
                        row_buf[idx + 1] = color[1];
                        row_buf[idx + 2] = color[2];
                        row_buf[idx + 3] = color[3];
                    }
                    // else leave as [0,0,0,0] (transparent/black)
                }
            }
            fb_write_row(x, y + gr * FONT_SCALE + sr, pw, &row_buf[..pw * 4]);
        }
    }
}

fn draw_string(x: usize, y: usize, s: &[u8], color: [u8; 4]) {
    for (i, &ch) in s.iter().enumerate() {
        draw_char(x + i * CHAR_PX_W, y, ch, color);
    }
}

fn draw_number(x: usize, y: usize, mut n: u32, color: [u8; 4]) {
    let mut d = [0u8; 10];
    let mut len = 0;
    if n == 0 {
        d[0] = b'0';
        len = 1;
    } else {
        while n > 0 {
            d[len] = b'0' + (n % 10) as u8;
            n /= 10;
            len += 1;
        }
        // Reverse
        let mut i = 0;
        while i < len / 2 {
            d.swap(i, len - 1 - i);
            i += 1;
        }
    }
    draw_string(x, y, &d[..len], color);
}

// ============================================================
// Maze helpers
// ============================================================

fn maze_idx(gx: u8, gy: u8) -> usize {
    gy as usize * MAZE_W + gx as usize
}

fn is_walkable(maze: &[u8], gx: i32, gy: i32) -> bool {
    // Handle tunnel wrapping
    if gy < 0 || gy >= MAZE_H as i32 {
        return false;
    }
    if gx < 0 || gx >= MAZE_W as i32 {
        // Tunnel row check
        return gy == 9; // row 9 has tunnels
    }
    let cell = maze[gy as usize * MAZE_W + gx as usize];
    cell != CELL_WALL
}

fn is_walkable_for_ghost(maze: &[u8], gx: i32, gy: i32) -> bool {
    if gy < 0 || gy >= MAZE_H as i32 {
        return false;
    }
    if gx < 0 || gx >= MAZE_W as i32 {
        return gy == 9;
    }
    let cell = maze[gy as usize * MAZE_W + gx as usize];
    cell != CELL_WALL
}

fn tunnel_wrap_x(gx: i32) -> u8 {
    if gx < 0 {
        (MAZE_W as i32 - 1) as u8
    } else if gx >= MAZE_W as i32 {
        0
    } else {
        gx as u8
    }
}

fn manhattan(x1: u8, y1: u8, x2: u8, y2: u8) -> u32 {
    let dx = if x1 > x2 { x1 - x2 } else { x2 - x1 } as u32;
    let dy = if y1 > y2 { y1 - y2 } else { y2 - y1 } as u32;
    dx + dy
}

fn opposite_dir(d: u8) -> u8 {
    match d {
        DIR_UP => DIR_DOWN,
        DIR_DOWN => DIR_UP,
        DIR_LEFT => DIR_RIGHT,
        DIR_RIGHT => DIR_LEFT,
        _ => DIR_NONE,
    }
}

// ============================================================
// Maze rendering
// ============================================================

/// Check if a neighbor cell in a given direction is not a wall.
fn neighbor_is_path(maze: &[u8], gx: usize, gy: usize, dir: u8) -> bool {
    let nx = gx as i32 + DX[dir as usize] as i32;
    let ny = gy as i32 + DY[dir as usize] as i32;
    if nx < 0 || nx >= MAZE_W as i32 || ny < 0 || ny >= MAZE_H as i32 {
        return true; // edges facing outside treated as corridor-facing for tunnel entrances
    }
    maze[ny as usize * MAZE_W + nx as usize] != CELL_WALL
}

fn draw_wall_cell(maze: &[u8], gx: usize, gy: usize) {
    let px = MAZE_PX_X + gx * CELL_SIZE;
    let py = MAZE_PX_Y + gy * CELL_SIZE;
    let cs = CELL_SIZE;
    let bevel: usize = 2;

    // Fill with shadow base
    fill_rect(px, py, cs, cs, WALL_SHADOW);

    // Add bright edge strips on sides facing corridors
    if neighbor_is_path(maze, gx, gy, DIR_UP) {
        fill_rect(px, py, cs, bevel, WALL_EDGE);
    }
    if neighbor_is_path(maze, gx, gy, DIR_DOWN) {
        fill_rect(px, py + cs - bevel, cs, bevel, WALL_EDGE);
    }
    if neighbor_is_path(maze, gx, gy, DIR_LEFT) {
        fill_rect(px, py, bevel, cs, WALL_EDGE);
    }
    if neighbor_is_path(maze, gx, gy, DIR_RIGHT) {
        fill_rect(px + cs - bevel, py, bevel, cs, WALL_EDGE);
    }

    // Interior face
    fill_rect(
        px + bevel,
        py + bevel,
        cs - bevel * 2,
        cs - bevel * 2,
        WALL_FACE,
    );
}

fn draw_path_cell(px: usize, py: usize) {
    fill_rect(px, py, CELL_SIZE, CELL_SIZE, PATH_COLOR);
}

fn draw_dot(gx: usize, gy: usize) {
    let px = MAZE_PX_X + gx * CELL_SIZE + CELL_SIZE / 2 - 2;
    let py = MAZE_PX_Y + gy * CELL_SIZE + CELL_SIZE / 2 - 2;
    fill_rect(px, py, 4, 4, DOT_COLOR);
}

fn draw_pellet(gx: usize, gy: usize, visible: bool) {
    let px = MAZE_PX_X + gx * CELL_SIZE + CELL_SIZE / 2 - 5;
    let py = MAZE_PX_Y + gy * CELL_SIZE + CELL_SIZE / 2 - 5;
    if visible {
        fill_rect(px, py, 10, 10, PELLET_COLOR);
    } else {
        fill_rect(px, py, 10, 10, PATH_COLOR);
    }
}

/// Draw the ghost house gate (top edge of ghost house, row 8, cols 9-11).
fn draw_ghost_house_gate(gx: usize, gy: usize) {
    let px = MAZE_PX_X + gx * CELL_SIZE;
    let py = MAZE_PX_Y + gy * CELL_SIZE;
    // Fill cell with path color
    fill_rect(px, py, CELL_SIZE, CELL_SIZE, PATH_COLOR);
    // Draw gate bar (hot pink) at the top of the cell, 4 pixels high
    fill_rect(px, py, CELL_SIZE, 4, GATE_COLOR);
}

fn draw_maze(maze: &[u8]) {
    for gy in 0..MAZE_H {
        for gx in 0..MAZE_W {
            let cell = maze[gy * MAZE_W + gx];
            let px = MAZE_PX_X + gx * CELL_SIZE;
            let py = MAZE_PX_Y + gy * CELL_SIZE;
            match cell {
                CELL_WALL => draw_wall_cell(maze, gx, gy),
                CELL_DOT => {
                    draw_path_cell(px, py);
                    draw_dot(gx, gy);
                }
                CELL_PELLET => {
                    draw_path_cell(px, py);
                    draw_pellet(gx, gy, true);
                }
                4 if gy == 8 && gx >= 9 && gx <= 11 => {
                    // Ghost house top gate
                    draw_ghost_house_gate(gx, gy);
                }
                _ => {
                    // EMPTY, GHOST interior, TUNNEL
                    draw_path_cell(px, py);
                }
            }
        }
    }
}

// ============================================================
// Character rendering
// ============================================================

fn cell_px(gx: u8, gy: u8) -> (usize, usize) {
    (
        MAZE_PX_X + gx as usize * CELL_SIZE + CHAR_PAD,
        MAZE_PX_Y + gy as usize * CELL_SIZE + CHAR_PAD,
    )
}

fn erase_cell(gx: u8, gy: u8) {
    let px = MAZE_PX_X + gx as usize * CELL_SIZE;
    let py = MAZE_PX_Y + gy as usize * CELL_SIZE;
    fill_rect(px, py, CELL_SIZE, CELL_SIZE, PATH_COLOR);
}

/// Write a single row of pixels using a small stack buffer, processing one
/// row at a time to avoid large sprite buffers.  The row buffer is
/// CHAR_SIZE * 4 = 80 bytes — trivial on the stack.
fn fb_write_row(x: usize, y: usize, w: usize, row_buf: &[u8]) {
    fb_write(x as u32, y as u32, w as u32, 1, row_buf.as_ptr());
}

/// Draw Pac-Man as a filled circle with rounded corners, a directional mouth,
/// and a brighter highlight in the center.
/// Renders row-by-row to avoid a 1600-byte sprite buffer on the stack.
fn draw_pacman(gx: u8, gy: u8, dir: u8, mouth_open: bool) {
    let (px, py) = cell_px(gx, gy);
    let cs = CHAR_SIZE; // 20
    let half = cs / 2;
    let r = half as i32;
    let r2 = r * r;

    for row in 0..cs {
        // One-row buffer: 20 pixels * 4 bytes = 80 bytes
        let mut row_buf = [0u8; 20 * 4];
        for col in 0..cs {
            let dy = row as i32 - r;
            let dx = col as i32 - r;
            let idx = col * 4;

            // Rounded corner check: skip 2x2 blocks at the four corners
            let in_corner = (row < 2 && col < 2)
                || (row < 2 && col >= cs - 2)
                || (row >= cs - 2 && col < 2)
                || (row >= cs - 2 && col >= cs - 2);

            let color = if in_corner || dx * dx + dy * dy > r2 {
                PATH_COLOR
            } else {
                // Check if in mouth wedge
                let in_mouth = if mouth_open {
                    match dir {
                        DIR_RIGHT => dx > 0 && dx <= 4 + r && dy.unsigned_abs() as i32 * 3 < dx * 2,
                        DIR_LEFT => dx < 0 && (-dx) <= 4 + r && dy.unsigned_abs() as i32 * 3 < (-dx) * 2,
                        DIR_UP => dy < 0 && (-dy) <= 4 + r && dx.unsigned_abs() as i32 * 3 < (-dy) * 2,
                        DIR_DOWN => dy > 0 && dy <= 4 + r && dx.unsigned_abs() as i32 * 3 < dy * 2,
                        _ => false,
                    }
                } else {
                    false
                };
                if in_mouth {
                    PAC_MOUTH
                } else {
                    let in_highlight = dx.unsigned_abs() <= 5 && dy.unsigned_abs() <= 5;
                    if in_highlight { PAC_HIGHLIGHT } else { PAC_BODY }
                }
            };
            row_buf[idx] = color[0];
            row_buf[idx + 1] = color[1];
            row_buf[idx + 2] = color[2];
            row_buf[idx + 3] = color[3];
        }
        fb_write_row(px, py + row, cs, &row_buf[..cs * 4]);
    }
}

/// Blend a highlight into a base color (simple additive lightening).
fn lighten_color(base: [u8; 4], amount: u8) -> [u8; 4] {
    let r = (base[0] as u16 + amount as u16).min(255) as u8;
    let g = (base[1] as u16 + amount as u16).min(255) as u8;
    let b = (base[2] as u16 + amount as u16).min(255) as u8;
    [r, g, b, base[3]]
}

/// Darken a color by a fixed amount.
fn darken_color(base: [u8; 4], amount: u8) -> [u8; 4] {
    let r = (base[0] as i16 - amount as i16).max(0) as u8;
    let g = (base[1] as i16 - amount as i16).max(0) as u8;
    let b = (base[2] as i16 - amount as i16).max(0) as u8;
    [r, g, b, base[3]]
}

/// Draw a ghost sprite with dome top, directional eyes, wavy skirt,
/// and special rendering for frightened/eaten states.
/// Renders row-by-row to avoid a 1600-byte sprite buffer on the stack.
fn draw_ghost(gx: u8, gy: u8, ghost_idx: usize, dir: u8, frightened: bool, eaten: bool) {
    let cs = CHAR_SIZE; // 20
    let half = cs / 2;

    let body_color = if frightened {
        FRIGHT_BODY
    } else {
        GHOST_COLORS[ghost_idx]
    };
    let highlight_color = lighten_color(body_color, 40);
    let dark_color = darken_color(body_color, 50);

    // Eye geometry
    let eye_y = 6usize;
    let eye_left_x = 3usize;
    let eye_right_x = 11usize;
    let eye_w = 6usize;
    let eye_h = 4usize;

    // Pupil offset by direction
    let (pdx, pdy): (i32, i32) = match dir {
        DIR_UP => (0, -1),
        DIR_DOWN => (0, 1),
        DIR_LEFT => (-1, 0),
        DIR_RIGHT => (1, 0),
        _ => (0, 0),
    };
    let pupil_cx = 3i32 + pdx;
    let pupil_cy = 1i32 + pdy;

    let cpx = MAZE_PX_X + gx as usize * CELL_SIZE + CHAR_PAD;
    let cpy = MAZE_PX_Y + gy as usize * CELL_SIZE + CHAR_PAD;

    for row in 0..cs {
        // One-row buffer: 20 pixels * 4 bytes = 80 bytes
        let mut row_buf = [0u8; 20 * 4];

        for col in 0..cs {
            let idx = col * 4;
            let mut color = PATH_COLOR;

            // --- Body ---
            if !eaten {
                let draw = if row < half {
                    let dy = row as i32 - half as i32;
                    let dx = col as i32 - half as i32;
                    let r = half as i32;
                    dx * dx + dy * dy <= r * r
                } else if row >= cs - 3 {
                    let bump_idx = col / 4;
                    let in_bump = bump_idx % 2 == 0;
                    if row == cs - 1 {
                        in_bump && col >= 1 && col < cs - 1
                    } else if row == cs - 2 {
                        col >= 1 && col < cs - 1
                    } else {
                        col >= 1 && col < cs - 1
                    }
                } else {
                    col >= 1 && col < cs - 1
                };

                if draw {
                    color = if row < half / 2 {
                        highlight_color
                    } else if row >= cs - 3 && (col / 4) % 2 != 0 && row >= cs - 2 {
                        dark_color
                    } else {
                        body_color
                    };
                }
            }

            // --- Eyes / face overlay ---
            if frightened && !eaten {
                // Frightened eyes: 2x1 white dots
                if row == eye_y + 1
                    && ((col == eye_left_x + 2)
                        || (col == eye_left_x + 3)
                        || (col == eye_right_x + 2)
                        || (col == eye_right_x + 3))
                {
                    color = FRIGHT_EYE;
                }
                // Frightened mouth zigzag
                if col >= 3 && col < 17 {
                    let mouth_y = 14usize;
                    let my_off: usize = if col % 4 == 1 || col % 4 == 3 { 1 } else { 0 };
                    if row == mouth_y + my_off {
                        color = FRIGHT_EYE;
                    }
                }
            } else {
                // Normal or eaten: eye whites
                if row >= eye_y && row < eye_y + eye_h {
                    let ey = row - eye_y;
                    if col >= eye_left_x && col < eye_left_x + eye_w {
                        color = GHOST_EYE_WHITE;
                    }
                    if col >= eye_right_x && col < eye_right_x + eye_w {
                        color = GHOST_EYE_WHITE;
                    }
                    // Pupils
                    let ex_in_left = col as i32 - eye_left_x as i32;
                    let ex_in_right = col as i32 - eye_right_x as i32;
                    let ey_i = ey as i32;
                    for ex_in in [ex_in_left, ex_in_right] {
                        let rx = ex_in - (pupil_cx - 1);
                        let ry = ey_i - pupil_cy;
                        if rx >= 0 && rx < 3 && ry >= 0 && ry < 2 {
                            if ex_in >= 0 && ex_in < eye_w as i32 {
                                color = GHOST_EYE_PUPIL;
                            }
                        }
                    }
                }
            }

            row_buf[idx] = color[0];
            row_buf[idx + 1] = color[1];
            row_buf[idx + 2] = color[2];
            row_buf[idx + 3] = color[3];
        }
        fb_write_row(cpx, cpy + row, cs, &row_buf[..cs * 4]);
    }
}

// ============================================================
// HUD rendering
// ============================================================

/// HUD panel width
const HUD_PANEL_W: usize = 200;
/// HUD panel height (matches maze height)
const HUD_PANEL_H: usize = MAZE_H * CELL_SIZE;

fn draw_hud_panel() {
    // Dark background panel
    fill_rect(HUD_X - 4, HUD_Y, HUD_PANEL_W, HUD_PANEL_H, HUD_BG);
    // 2px bright blue border on the left edge
    fill_rect(HUD_X - 4, HUD_Y, 2, HUD_PANEL_H, HUD_BORDER);
}

fn draw_hud_static() {
    // Draw the HUD panel background and border
    draw_hud_panel();

    // "1UP" label
    draw_string(HUD_X + 8, HUD_Y + 10, b"1UP", TEXT_LABEL);
    // "HIGH SCORE" label
    draw_string(HUD_X + 8, HUD_Y + 70, b"HIGH SCORE", TEXT_LABEL);
    // "LEVEL" label
    draw_string(HUD_X + 8, HUD_Y + 130, b"LEVEL", TEXT_LABEL);
    // "LIVES" label
    draw_string(HUD_X + 8, HUD_Y + 190, b"LIVES", TEXT_LABEL);

    // Controls
    let cy = HUD_Y + 300;
    draw_string(HUD_X + 8, cy, b"CONTROLS", TEXT_DIM);
    let dy: usize = 22;
    draw_string(HUD_X + 8, cy + dy, b"WASD  MOVE", TEXT_DIM);
    draw_string(HUD_X + 8, cy + dy * 2, b"SPC   PAUSE", TEXT_DIM);
    draw_string(HUD_X + 8, cy + dy * 3, b"Q     QUIT", TEXT_DIM);
}

/// Draw a small 8x8 Pac-Man icon for life display at given position.
/// Renders row-by-row (32-byte row buffer) to avoid a 256-byte sprite buffer.
fn draw_life_icon(x: usize, y: usize) {
    let sz: usize = 8;
    let half = sz / 2;
    let r = half as i32;
    let r2 = r * r;
    for row in 0..sz {
        let mut row_buf = [0u8; 8 * 4];
        for col in 0..sz {
            let dy = row as i32 - r;
            let dx = col as i32 - r;
            let color = if dx * dx + dy * dy <= r2 {
                let in_mouth = dx > 0 && dy.unsigned_abs() as i32 * 2 < dx;
                if in_mouth { HUD_BG } else { PAC_BODY }
            } else {
                HUD_BG
            };
            let idx = col * 4;
            row_buf[idx] = color[0];
            row_buf[idx + 1] = color[1];
            row_buf[idx + 2] = color[2];
            row_buf[idx + 3] = color[3];
        }
        fb_write_row(x, y + row, sz, &row_buf[..sz * 4]);
    }
}

fn draw_hud_values(score: u32, high_score: u32, lives: u32, level: u32) {
    // Clear value areas (on HUD_BG background)
    fill_rect(HUD_X + 8, HUD_Y + 35, 140, 18, HUD_BG);
    fill_rect(HUD_X + 8, HUD_Y + 95, 140, 18, HUD_BG);
    fill_rect(HUD_X + 8, HUD_Y + 155, 140, 18, HUD_BG);
    fill_rect(HUD_X + 8, HUD_Y + 215, 140, 18, HUD_BG);

    // Score in warm cream
    draw_number(HUD_X + 8, HUD_Y + 35, score, TEXT_COLOR);
    // High score in green
    draw_number(HUD_X + 8, HUD_Y + 95, high_score, TEXT_GREEN);
    // Level
    draw_number(HUD_X + 8, HUD_Y + 155, level, TEXT_COLOR);

    // Lives: draw as small Pac-Man icons
    let lives_y = HUD_Y + 215;
    let mut lx = HUD_X + 8;
    let max_lives = if lives > 10 { 10 } else { lives };
    for _ in 0..max_lives {
        draw_life_icon(lx, lives_y);
        lx += 14;
    }
}

// ============================================================
// High score persistence
// ============================================================

fn load_high_score() -> u32 {
    let fd = open("pacman_hi\0", OpenFlags::RDONLY);
    if fd < 0 {
        return 0;
    }
    let buf = [0u8; 4];
    let n = read(fd as usize, &buf);
    close(fd as usize);
    if n == 4 {
        u32::from_le_bytes(buf)
    } else {
        0
    }
}

fn save_high_score(score: u32) {
    let fd = open(
        "pacman_hi\0",
        OpenFlags::CREATE | OpenFlags::WRONLY | OpenFlags::TRUNC,
    );
    if fd >= 0 {
        let buf = score.to_le_bytes();
        write(fd as usize, &buf);
        close(fd as usize);
    }
}

// ============================================================
// Ghost AI (child process)
// ============================================================

// Statics for signal handlers in child processes
static mut FRIGHTENED_TICKS_LEFT: u32 = 0;
static mut RESPAWNING_FLAG: bool = false;

fn handle_power_pellet() {
    unsafe {
        FRIGHTENED_TICKS_LEFT = FRIGHT_TICKS;
    }
    sigreturn();
}

fn handle_eaten() {
    unsafe {
        RESPAWNING_FLAG = true;
    }
    sigreturn();
}

/// Pick the best direction toward a target, avoiding reverse and walls.
fn pick_best_direction(
    maze: &[u8],
    gx: u8,
    gy: u8,
    current_dir: u8,
    target_x: u8,
    target_y: u8,
) -> u8 {
    let rev = opposite_dir(current_dir);
    let mut best_dir = current_dir;
    let mut best_dist = u32::MAX;
    // Priority order: UP, LEFT, DOWN, RIGHT (classic Pac-Man tie-break)
    let order = [DIR_UP, DIR_LEFT, DIR_DOWN, DIR_RIGHT];

    for &d in order.iter() {
        if d == rev && current_dir != DIR_NONE {
            continue;
        }
        let nx = gx as i32 + DX[d as usize] as i32;
        let ny = gy as i32 + DY[d as usize] as i32;
        if is_walkable_for_ghost(maze, nx, ny) {
            let wx = tunnel_wrap_x(nx);
            let wy = if ny < 0 {
                0u8
            } else if ny >= MAZE_H as i32 {
                (MAZE_H - 1) as u8
            } else {
                ny as u8
            };
            let dist = manhattan(wx, wy, target_x, target_y);
            if dist < best_dist {
                best_dist = dist;
                best_dir = d;
            }
        }
    }
    best_dir
}

fn pick_random_direction(maze: &[u8], gx: u8, gy: u8, current_dir: u8) -> u8 {
    let rev = opposite_dir(current_dir);
    let mut dirs = [DIR_NONE; 4];
    let mut count = 0u8;

    for d in 0..4u8 {
        if d == rev && current_dir != DIR_NONE {
            continue;
        }
        let nx = gx as i32 + DX[d as usize] as i32;
        let ny = gy as i32 + DY[d as usize] as i32;
        if is_walkable_for_ghost(maze, nx, ny) {
            dirs[count as usize] = d;
            count += 1;
        }
    }

    if count == 0 {
        // Fallback: try reverse
        let nx = gx as i32 + DX[rev as usize] as i32;
        let ny = gy as i32 + DY[rev as usize] as i32;
        if is_walkable_for_ghost(maze, nx, ny) {
            return rev;
        }
        return current_dir;
    }
    dirs[(xorshift32() % count as u32) as usize]
}

/// Ghost child process main loop.
/// ghost_id: 0=Blinky, 1=Pinky, 2=Inky, 3=Clyde
/// read_fd: pipe to read state from parent
/// write_fd: pipe to write direction back to parent
fn ghost_main(ghost_id: usize, read_fd: usize, write_fd: usize) -> ! {
    // Seed RNG differently per ghost
    seed_rng((get_time() as u32).wrapping_add(ghost_id as u32 * 7919));

    // Register signal handlers
    let mut power_action = SignalAction::default();
    power_action.handler = handle_power_pellet as *const () as usize;
    let old = SignalAction::default();
    sigaction(SignalNo::SIGUSR1, &power_action, &old);

    let mut eaten_action = SignalAction::default();
    eaten_action.handler = handle_eaten as *const () as usize;
    sigaction(SignalNo::SIGUSR2, &eaten_action, &old);

    let mut current_dir: u8 = DIR_UP;
    let mut mode_tick: u32 = 0;
    let mut scatter_mode = true; // Start in scatter

    loop {
        // Read 7 bytes: pac_x, pac_y, pac_dir, ghost_x, ghost_y, blinky_x, blinky_y
        let mut state = [0u8; PIPE_TO_GHOST];
        let n = pipe_read(read_fd, &mut state);
        if n <= 0 {
            // Parent closed pipe -- exit
            exit(0);
            unreachable!();
        }

        let pac_x = state[0];
        let pac_y = state[1];
        let pac_dir = state[2];
        let gx = state[3];
        let gy = state[4];
        let blinky_x = state[5];
        let blinky_y = state[6];

        // Check respawning flag
        let respawning = unsafe { RESPAWNING_FLAG };
        if respawning {
            // Move toward ghost house
            let dir =
                pick_best_direction(&INITIAL_MAZE, gx, gy, current_dir, GHOST_HOUSE_X, GHOST_HOUSE_Y);
            current_dir = dir;
            // Check if arrived at ghost house
            if gx == GHOST_HOUSE_X && gy == GHOST_HOUSE_Y {
                unsafe {
                    RESPAWNING_FLAG = false;
                }
            }
            let out = [dir; 1];
            pipe_write(write_fd, &out);
            continue;
        }

        // Check frightened mode
        let frightened_ticks = unsafe { FRIGHTENED_TICKS_LEFT };
        if frightened_ticks > 0 {
            unsafe {
                FRIGHTENED_TICKS_LEFT = frightened_ticks - 1;
            }
            // Random movement when frightened
            let dir = pick_random_direction(&INITIAL_MAZE, gx, gy, current_dir);
            current_dir = dir;
            let out = [dir; 1];
            pipe_write(write_fd, &out);
            continue;
        }

        // Normal mode: scatter/chase alternation
        mode_tick += 1;
        if scatter_mode && mode_tick >= SCATTER_TICKS {
            scatter_mode = false;
            mode_tick = 0;
        } else if !scatter_mode && mode_tick >= CHASE_TICKS {
            scatter_mode = true;
            mode_tick = 0;
        }

        let (target_x, target_y) = if scatter_mode {
            (
                SCATTER_TARGETS[ghost_id][1],
                SCATTER_TARGETS[ghost_id][0],
            )
        } else {
            // Chase mode: each ghost has unique targeting
            match ghost_id {
                BLINKY => {
                    // Directly chase Pac-Man
                    (pac_x, pac_y)
                }
                PINKY => {
                    // Target 4 cells ahead of Pac-Man
                    let tx = pac_x as i32 + DX[pac_dir as usize % 4] as i32 * 4;
                    let ty = pac_y as i32 + DY[pac_dir as usize % 4] as i32 * 4;
                    (
                        tx.clamp(0, MAZE_W as i32 - 1) as u8,
                        ty.clamp(0, MAZE_H as i32 - 1) as u8,
                    )
                }
                INKY => {
                    // Vector from Blinky to 2-ahead-of-pac, doubled
                    let ahead_x = pac_x as i32 + DX[pac_dir as usize % 4] as i32 * 2;
                    let ahead_y = pac_y as i32 + DY[pac_dir as usize % 4] as i32 * 2;
                    let tx = ahead_x * 2 - blinky_x as i32;
                    let ty = ahead_y * 2 - blinky_y as i32;
                    (
                        tx.clamp(0, MAZE_W as i32 - 1) as u8,
                        ty.clamp(0, MAZE_H as i32 - 1) as u8,
                    )
                }
                CLYDE => {
                    // Chase when far (>8), scatter when close
                    let dist = manhattan(gx, gy, pac_x, pac_y);
                    if dist > 8 {
                        (pac_x, pac_y)
                    } else {
                        (
                            SCATTER_TARGETS[CLYDE][1],
                            SCATTER_TARGETS[CLYDE][0],
                        )
                    }
                }
                _ => (pac_x, pac_y),
            }
        };

        let dir = pick_best_direction(&INITIAL_MAZE, gx, gy, current_dir, target_x, target_y);
        current_dir = dir;
        let out = [dir; 1];
        pipe_write(write_fd, &out);
    }
}

// ============================================================
// Game state
// ============================================================

#[derive(Clone, Copy, PartialEq)]
enum GameState {
    Ready,
    Playing,
    Dying,
    LevelComplete,
    GameOver,
    Paused,
}

struct GhostInfo {
    x: u8,
    y: u8,
    dir: u8,
    pid: isize,
    write_fd: usize, // parent writes state to ghost
    read_fd: usize,  // parent reads direction from ghost
    frightened_ticks: u32,
    eaten: bool,
    prev_x: u8,
    prev_y: u8,
}

struct Game {
    maze: [u8; MAZE_W * MAZE_H],
    pac_x: u8,
    pac_y: u8,
    pac_dir: u8,
    pac_next_dir: u8,
    ghosts: [GhostInfo; 4],
    state: GameState,
    state_timer: u32,
    score: u32,
    high_score: u32,
    lives: u32,
    level: u32,
    dots_eaten: u32,
    total_dots: u32,
    mouth_open: bool,
    mouth_timer: u32,
    ghosts_eaten_combo: u32,
    prev_pac_x: u8,
    prev_pac_y: u8,
    pellet_blink: bool,
    pellet_blink_timer: u32,
    prev_score: u32,
    prev_lives: u32,
    prev_level: u32,
    prev_high_score: u32,
}

impl Game {
    fn reset_positions(&mut self) {
        self.pac_x = PAC_START_X;
        self.pac_y = PAC_START_Y;
        self.pac_dir = DIR_LEFT;
        self.pac_next_dir = DIR_LEFT;
        self.prev_pac_x = PAC_START_X;
        self.prev_pac_y = PAC_START_Y;

        for i in 0..4 {
            self.ghosts[i].x = GHOST_START[i][1];
            self.ghosts[i].y = GHOST_START[i][0];
            self.ghosts[i].dir = if i == 0 { DIR_LEFT } else { DIR_UP };
            self.ghosts[i].frightened_ticks = 0;
            self.ghosts[i].eaten = false;
            self.ghosts[i].prev_x = GHOST_START[i][1];
            self.ghosts[i].prev_y = GHOST_START[i][0];
        }

        self.ghosts_eaten_combo = 0;
    }

    fn reset_level(&mut self) {
        self.maze = INITIAL_MAZE;
        self.dots_eaten = 0;
        self.total_dots = total_dots();
        self.reset_positions();
    }

    /// Reset entire game state in-place (avoids creating a new Game on the stack).
    fn reset(&mut self) {
        self.maze = INITIAL_MAZE;
        self.pac_x = PAC_START_X;
        self.pac_y = PAC_START_Y;
        self.pac_dir = DIR_LEFT;
        self.pac_next_dir = DIR_LEFT;
        for i in 0..4 {
            self.ghosts[i].x = GHOST_START[i][1];
            self.ghosts[i].y = GHOST_START[i][0];
            self.ghosts[i].dir = if i == 0 { DIR_LEFT } else { DIR_UP };
            self.ghosts[i].pid = 0;
            self.ghosts[i].write_fd = 0;
            self.ghosts[i].read_fd = 0;
            self.ghosts[i].frightened_ticks = 0;
            self.ghosts[i].eaten = false;
            self.ghosts[i].prev_x = GHOST_START[i][1];
            self.ghosts[i].prev_y = GHOST_START[i][0];
        }
        self.state = GameState::Ready;
        self.state_timer = 0;
        self.score = 0;
        // high_score intentionally preserved
        self.lives = INIT_LIVES;
        self.level = 1;
        self.dots_eaten = 0;
        self.total_dots = total_dots();
        self.mouth_open = true;
        self.mouth_timer = 0;
        self.ghosts_eaten_combo = 0;
        self.prev_pac_x = PAC_START_X;
        self.prev_pac_y = PAC_START_Y;
        self.pellet_blink = true;
        self.pellet_blink_timer = 0;
        self.prev_score = u32::MAX;
        self.prev_lives = u32::MAX;
        self.prev_level = u32::MAX;
        self.prev_high_score = u32::MAX;
    }
}

// ============================================================
// Ghost process management
// ============================================================

fn spawn_ghosts(game: &mut Game) {
    for i in 0..4 {
        // Create pipes: parent_to_ghost and ghost_to_parent
        let mut p2g = [0usize; 2]; // [read_end, write_end]
        let mut g2p = [0usize; 2];
        pipe(&mut p2g);
        pipe(&mut g2p);

        let child_pid = fork();
        if child_pid == 0 {
            // Child process
            // Close unused ends
            close(p2g[1]); // close write end of parent-to-ghost
            close(g2p[0]); // close read end of ghost-to-parent

            ghost_main(i, p2g[0], g2p[1]);
            // ghost_main never returns
        } else {
            // Parent process
            close(p2g[0]); // close read end of parent-to-ghost
            close(g2p[1]); // close write end of ghost-to-parent

            game.ghosts[i].pid = child_pid;
            game.ghosts[i].write_fd = p2g[1]; // parent writes state here
            game.ghosts[i].read_fd = g2p[0]; // parent reads direction here
        }
    }
}

fn kill_ghosts(game: &mut Game) {
    for i in 0..4 {
        if game.ghosts[i].pid > 0 {
            // Close pipes first -- ghost will get EOF and exit
            close(game.ghosts[i].write_fd);
            close(game.ghosts[i].read_fd);
            // Wait for child to exit
            let mut exit_code: i32 = 0;
            wait(&mut exit_code as *mut i32);
            game.ghosts[i].pid = 0;
        }
    }
}

fn send_ghost_state(game: &Game, ghost_idx: usize) {
    let state = [
        game.pac_x,
        game.pac_y,
        game.pac_dir,
        game.ghosts[ghost_idx].x,
        game.ghosts[ghost_idx].y,
        game.ghosts[BLINKY].x,
        game.ghosts[BLINKY].y,
    ];
    pipe_write(game.ghosts[ghost_idx].write_fd, &state);
}

fn read_ghost_direction(game: &Game, ghost_idx: usize) -> u8 {
    let mut buf = [DIR_UP; 1];
    let n = pipe_read(game.ghosts[ghost_idx].read_fd, &mut buf);
    if n > 0 {
        buf[0]
    } else {
        game.ghosts[ghost_idx].dir
    }
}

// ============================================================
// Input handling
// ============================================================

fn poll_keyboard() -> u8 {
    let buf = [0u8; 1];
    let n = read(STDIN, &buf);
    if n > 0 && buf[0] != 0 {
        buf[0]
    } else {
        0
    }
}

fn keycode_to_dir(key: u8) -> u8 {
    match key {
        KEY_W | KEY_UP => DIR_UP,
        KEY_D | KEY_RIGHT => DIR_RIGHT,
        KEY_S | KEY_DOWN => DIR_DOWN,
        KEY_A | KEY_LEFT => DIR_LEFT,
        _ => DIR_NONE,
    }
}

// ============================================================
// Main game entry point
// ============================================================

// Static game instance — avoids putting ~700 bytes of Game on the 8 KiB stack.
static mut GAME: Game = Game {
    maze: INITIAL_MAZE,
    pac_x: PAC_START_X,
    pac_y: PAC_START_Y,
    pac_dir: DIR_LEFT,
    pac_next_dir: DIR_LEFT,
    ghosts: [
        GhostInfo {
            x: GHOST_START[0][1],
            y: GHOST_START[0][0],
            dir: DIR_LEFT,
            pid: 0,
            write_fd: 0,
            read_fd: 0,
            frightened_ticks: 0,
            eaten: false,
            prev_x: GHOST_START[0][1],
            prev_y: GHOST_START[0][0],
        },
        GhostInfo {
            x: GHOST_START[1][1],
            y: GHOST_START[1][0],
            dir: DIR_UP,
            pid: 0,
            write_fd: 0,
            read_fd: 0,
            frightened_ticks: 0,
            eaten: false,
            prev_x: GHOST_START[1][1],
            prev_y: GHOST_START[1][0],
        },
        GhostInfo {
            x: GHOST_START[2][1],
            y: GHOST_START[2][0],
            dir: DIR_UP,
            pid: 0,
            write_fd: 0,
            read_fd: 0,
            frightened_ticks: 0,
            eaten: false,
            prev_x: GHOST_START[2][1],
            prev_y: GHOST_START[2][0],
        },
        GhostInfo {
            x: GHOST_START[3][1],
            y: GHOST_START[3][0],
            dir: DIR_UP,
            pid: 0,
            write_fd: 0,
            read_fd: 0,
            frightened_ticks: 0,
            eaten: false,
            prev_x: GHOST_START[3][1],
            prev_y: GHOST_START[3][0],
        },
    ],
    state: GameState::Ready,
    state_timer: 0,
    score: 0,
    high_score: 0,
    lives: INIT_LIVES,
    level: 1,
    dots_eaten: 0,
    total_dots: 0, // set at runtime via reset()
    mouth_open: true,
    mouth_timer: 0,
    ghosts_eaten_combo: 0,
    prev_pac_x: PAC_START_X,
    prev_pac_y: PAC_START_Y,
    pellet_blink: true,
    pellet_blink_timer: 0,
    prev_score: u32::MAX,
    prev_lives: u32::MAX,
    prev_level: u32::MAX,
    prev_high_score: u32::MAX,
};

/// Entry point for the Pac-Man game.
pub fn run_game() {
    crate::println!("Pac-Man starting...");

    // Seed RNG
    seed_rng(get_time() as u32);

    // Get framebuffer info
    let (_fb_w, _fb_h) = fb_info();

    // Load high score
    let high_score = load_high_score();

    // Initialize game state (use static to keep ~700 bytes off the stack)
    let game = unsafe { &mut *(&raw mut GAME) };
    game.reset();
    game.high_score = high_score;

    // Clear screen
    fill_rect(0, 0, FB_W, FB_H, BG_VOID);

    // Draw initial maze
    draw_maze(&game.maze);

    // Draw HUD
    draw_hud_static();
    draw_hud_values(game.score, game.high_score, game.lives, game.level);

    // Spawn ghost processes
    spawn_ghosts(game);

    // Draw "READY!" text
    let ready_x = MAZE_PX_X + (MAZE_W * CELL_SIZE - 6 * CHAR_PX_W) / 2;
    let ready_y = MAZE_PX_Y + 13 * CELL_SIZE + CELL_SIZE / 2 - 7;
    draw_string(ready_x, ready_y, b"READY!", READY_COLOR);

    // Draw initial characters
    draw_pacman(game.pac_x, game.pac_y, game.pac_dir, true);
    for i in 0..4 {
        draw_ghost(
            game.ghosts[i].x,
            game.ghosts[i].y,
            i,
            game.ghosts[i].dir,
            false,
            false,
        );
    }
    fb_flush();

    game.state = GameState::Ready;
    game.state_timer = 0;

    let mut quit = false;
    let mut prev_state = game.state;
    let mut flash_count: u32 = 0;

    // Main game loop
    loop {
        let frame_start = get_time();

        // --- Input ---
        // Drain all pending key events
        loop {
            let key = poll_keyboard();
            if key == 0 {
                break;
            }
            // Only process key press (not release: bit 7 set means release)
            if key & 0x80 != 0 {
                continue;
            }

            match key {
                KEY_Q | KEY_ESC => {
                    quit = true;
                }
                KEY_SPACE => {
                    if game.state == GameState::Playing {
                        prev_state = GameState::Playing;
                        game.state = GameState::Paused;
                        // Draw PAUSED text
                        let px = MAZE_PX_X + (MAZE_W * CELL_SIZE - 6 * CHAR_PX_W) / 2;
                        let py = MAZE_PX_Y + 10 * CELL_SIZE;
                        draw_string(px, py, b"PAUSED", READY_COLOR);
                        fb_flush();
                    } else if game.state == GameState::Paused {
                        game.state = prev_state;
                        // Erase PAUSED text by redrawing those cells
                        for gx in 8..13 {
                            let cell = game.maze[10 * MAZE_W + gx];
                            let cpx = MAZE_PX_X + gx * CELL_SIZE;
                            let cpy = MAZE_PX_Y + 10 * CELL_SIZE;
                            if cell == CELL_WALL {
                                draw_wall_cell(&game.maze, gx, 10);
                            } else {
                                draw_path_cell(cpx, cpy);
                            }
                        }
                    } else if game.state == GameState::GameOver {
                        // Restart game (reset in-place to avoid stack allocation)
                        game.reset();
                        game.high_score = load_high_score();
                        game.state = GameState::Ready;
                        game.state_timer = 0;
                        // Respawn ghosts
                        kill_ghosts(game);
                        spawn_ghosts(game);
                        // Redraw everything
                        fill_rect(0, 0, FB_W, FB_H, BG_VOID);
                        draw_maze(&game.maze);
                        draw_hud_static();
                        draw_hud_values(game.score, game.high_score, game.lives, game.level);
                        draw_pacman(game.pac_x, game.pac_y, game.pac_dir, true);
                        for i in 0..4 {
                            draw_ghost(
                                game.ghosts[i].x,
                                game.ghosts[i].y,
                                i,
                                game.ghosts[i].dir,
                                false,
                                false,
                            );
                        }
                        let rx = MAZE_PX_X + (MAZE_W * CELL_SIZE - 6 * CHAR_PX_W) / 2;
                        let ry = MAZE_PX_Y + 13 * CELL_SIZE + CELL_SIZE / 2 - 7;
                        draw_string(rx, ry, b"READY!", READY_COLOR);
                        fb_flush();
                        continue;
                    }
                }
                _ => {
                    let d = keycode_to_dir(key);
                    if d != DIR_NONE {
                        game.pac_next_dir = d;
                    }
                }
            }
        }

        if quit {
            break;
        }

        // --- State machine ---
        match game.state {
            GameState::Ready => {
                game.state_timer += 1;
                if game.state_timer >= READY_TICKS {
                    game.state = GameState::Playing;
                    // Erase READY! text
                    for gx in 7..14 {
                        let cpx = MAZE_PX_X + gx * CELL_SIZE;
                        let cpy = MAZE_PX_Y + 13 * CELL_SIZE;
                        draw_path_cell(cpx, cpy);
                        // Redraw dot if present
                        let cell = game.maze[13 * MAZE_W + gx];
                        if cell == CELL_DOT {
                            draw_dot(gx, 13);
                        }
                    }
                }
            }
            GameState::Playing => {
                // --- Move Pac-Man ---
                // Try next direction first
                let nx = game.pac_x as i32 + DX[game.pac_next_dir as usize] as i32;
                let ny = game.pac_y as i32 + DY[game.pac_next_dir as usize] as i32;
                if is_walkable(&game.maze, nx, ny) {
                    game.pac_dir = game.pac_next_dir;
                }

                // Move in current direction
                let mx = game.pac_x as i32 + DX[game.pac_dir as usize] as i32;
                let my = game.pac_y as i32 + DY[game.pac_dir as usize] as i32;
                if is_walkable(&game.maze, mx, my) {
                    game.prev_pac_x = game.pac_x;
                    game.prev_pac_y = game.pac_y;
                    game.pac_x = tunnel_wrap_x(mx);
                    game.pac_y = if my < 0 {
                        0
                    } else if my >= MAZE_H as i32 {
                        (MAZE_H - 1) as u8
                    } else {
                        my as u8
                    };
                }

                // --- Eat dots/pellets ---
                let cell_idx = maze_idx(game.pac_x, game.pac_y);
                match game.maze[cell_idx] {
                    CELL_DOT => {
                        game.maze[cell_idx] = CELL_EMPTY;
                        game.score += DOT_SCORE;
                        game.dots_eaten += 1;
                    }
                    CELL_PELLET => {
                        game.maze[cell_idx] = CELL_EMPTY;
                        game.score += PELLET_SCORE;
                        game.dots_eaten += 1;
                        game.ghosts_eaten_combo = 0;

                        // Signal all ghosts: frightened mode
                        for i in 0..4 {
                            game.ghosts[i].frightened_ticks = FRIGHT_TICKS;
                            if game.ghosts[i].pid > 0 && !game.ghosts[i].eaten {
                                kill(game.ghosts[i].pid, SignalNo::SIGUSR1);
                            }
                        }
                    }
                    _ => {}
                }

                // --- Update ghost positions via pipes ---
                for i in 0..4 {
                    send_ghost_state(&game, i);
                }
                for i in 0..4 {
                    let new_dir = read_ghost_direction(&game, i);
                    game.ghosts[i].prev_x = game.ghosts[i].x;
                    game.ghosts[i].prev_y = game.ghosts[i].y;
                    game.ghosts[i].dir = new_dir;

                    let ngx = game.ghosts[i].x as i32 + DX[new_dir as usize] as i32;
                    let ngy = game.ghosts[i].y as i32 + DY[new_dir as usize] as i32;
                    if is_walkable_for_ghost(&INITIAL_MAZE, ngx, ngy) {
                        game.ghosts[i].x = tunnel_wrap_x(ngx);
                        game.ghosts[i].y = if ngy < 0 {
                            0
                        } else if ngy >= MAZE_H as i32 {
                            (MAZE_H - 1) as u8
                        } else {
                            ngy as u8
                        };
                    }
                }

                // Decrement ghost frightened ticks (parent tracking)
                for i in 0..4 {
                    if game.ghosts[i].frightened_ticks > 0 {
                        game.ghosts[i].frightened_ticks -= 1;
                    }
                }

                // --- Collision detection ---
                for i in 0..4 {
                    if game.ghosts[i].x == game.pac_x && game.ghosts[i].y == game.pac_y {
                        if game.ghosts[i].eaten {
                            // Already eaten, no interaction
                            continue;
                        }
                        if game.ghosts[i].frightened_ticks > 0 {
                            // Eat the ghost
                            game.ghosts[i].eaten = true;
                            let bonus = if (game.ghosts_eaten_combo as usize) < GHOST_SCORES.len()
                            {
                                GHOST_SCORES[game.ghosts_eaten_combo as usize]
                            } else {
                                1600
                            };
                            game.score += bonus;
                            game.ghosts_eaten_combo += 1;
                            // Signal ghost to respawn
                            if game.ghosts[i].pid > 0 {
                                kill(game.ghosts[i].pid, SignalNo::SIGUSR2);
                            }
                        } else {
                            // Pac-Man dies
                            game.state = GameState::Dying;
                            game.state_timer = 0;
                        }
                    }
                }

                // Check if ghost returned to ghost house after being eaten
                for i in 0..4 {
                    if game.ghosts[i].eaten
                        && game.ghosts[i].x == GHOST_HOUSE_X
                        && game.ghosts[i].y == GHOST_HOUSE_Y
                    {
                        game.ghosts[i].eaten = false;
                        game.ghosts[i].frightened_ticks = 0;
                    }
                }

                // --- Level complete ---
                if game.dots_eaten >= game.total_dots {
                    game.state = GameState::LevelComplete;
                    game.state_timer = 0;
                    flash_count = 0;
                }

                // Update high score
                if game.score > game.high_score {
                    game.high_score = game.score;
                }

                // Mouth animation
                game.mouth_timer += 1;
                if game.mouth_timer >= 2 {
                    game.mouth_open = !game.mouth_open;
                    game.mouth_timer = 0;
                }

                // Pellet blink (pulse every 4 ticks)
                game.pellet_blink_timer += 1;
                if game.pellet_blink_timer >= 4 {
                    game.pellet_blink = !game.pellet_blink;
                    game.pellet_blink_timer = 0;
                }
            }
            GameState::Dying => {
                game.state_timer += 1;
                if game.state_timer >= DYING_TICKS {
                    game.lives = game.lives.saturating_sub(1);
                    if game.lives == 0 {
                        game.state = GameState::GameOver;
                        // Save high score
                        if game.score > load_high_score() {
                            save_high_score(game.score);
                        }
                    } else {
                        game.reset_positions();
                        game.state = GameState::Ready;
                        game.state_timer = 0;

                        // Redraw maze (clear old positions)
                        draw_maze(&game.maze);
                        // Draw READY!
                        let rx = MAZE_PX_X + (MAZE_W * CELL_SIZE - 6 * CHAR_PX_W) / 2;
                        let ry = MAZE_PX_Y + 13 * CELL_SIZE + CELL_SIZE / 2 - 7;
                        draw_string(rx, ry, b"READY!", READY_COLOR);
                        // Draw characters at starting positions
                        draw_pacman(game.pac_x, game.pac_y, game.pac_dir, true);
                        for i in 0..4 {
                            draw_ghost(
                                game.ghosts[i].x,
                                game.ghosts[i].y,
                                i,
                                game.ghosts[i].dir,
                                false,
                                false,
                            );
                        }
                    }
                }
            }
            GameState::LevelComplete => {
                game.state_timer += 1;
                flash_count += 1;

                // Flash maze 3 times over FLASH_TICKS
                if flash_count % 4 < 2 {
                    // Draw walls in white
                    for gy in 0..MAZE_H {
                        for gx in 0..MAZE_W {
                            if game.maze[gy * MAZE_W + gx] == CELL_WALL {
                                let px = MAZE_PX_X + gx * CELL_SIZE;
                                let py = MAZE_PX_Y + gy * CELL_SIZE;
                                fill_rect(px, py, CELL_SIZE, CELL_SIZE, TEXT_COLOR);
                            }
                        }
                    }
                } else {
                    draw_maze(&game.maze);
                }

                if game.state_timer >= FLASH_TICKS {
                    game.level += 1;
                    game.reset_level();
                    game.state = GameState::Ready;
                    game.state_timer = 0;

                    // Redraw everything
                    draw_maze(&game.maze);
                    draw_pacman(game.pac_x, game.pac_y, game.pac_dir, true);
                    for i in 0..4 {
                        draw_ghost(
                            game.ghosts[i].x,
                            game.ghosts[i].y,
                            i,
                            game.ghosts[i].dir,
                            false,
                            false,
                        );
                    }
                    let rx = MAZE_PX_X + (MAZE_W * CELL_SIZE - 6 * CHAR_PX_W) / 2;
                    let ry = MAZE_PX_Y + 13 * CELL_SIZE + CELL_SIZE / 2 - 7;
                    draw_string(rx, ry, b"READY!", READY_COLOR);
                }
            }
            GameState::GameOver => {
                if game.state_timer == 0 {
                    // ── Game Over overlay ──
                    // Centered panel over the maze
                    let maze_cx = MAZE_PX_X + MAZE_W * CELL_SIZE / 2;
                    let panel_w: usize = 280;
                    let panel_h: usize = 200;
                    let panel_x = maze_cx - panel_w / 2;
                    let panel_y = MAZE_PX_Y + MAZE_H * CELL_SIZE / 2 - panel_h / 2;

                    // Dark panel background with blue border
                    fill_rect(panel_x - 4, panel_y - 4, panel_w + 8, panel_h + 8, WALL_EDGE);
                    fill_rect(panel_x - 2, panel_y - 2, panel_w + 4, panel_h + 4, WALL_SHADOW);
                    fill_rect(panel_x, panel_y, panel_w, panel_h, BG_VOID);

                    // "GAME OVER" title in red, centered
                    let title = b"GAME OVER";
                    let title_w = title.len() * CHAR_PX_W;
                    draw_string(panel_x + (panel_w - title_w) / 2, panel_y + 16, title, GAMEOVER_COLOR);

                    // Horizontal divider line
                    fill_rect(panel_x + 20, panel_y + 40, panel_w - 40, 2, WALL_EDGE);

                    // "SCORE" label and value
                    draw_string(panel_x + 20, panel_y + 54, b"SCORE", TEXT_LABEL);
                    draw_number(panel_x + 20, panel_y + 72, game.score, TEXT_COLOR);

                    // "HIGH" label and value
                    draw_string(panel_x + 150, panel_y + 54, b"HIGH", TEXT_LABEL);
                    draw_number(panel_x + 150, panel_y + 72, game.high_score, TEXT_GREEN);

                    // New high score indicator
                    if game.score >= game.high_score && game.score > 0 {
                        let msg = b"NEW HIGH SCORE!";
                        let msg_w = msg.len() * CHAR_PX_W;
                        draw_string(panel_x + (panel_w - msg_w) / 2, panel_y + 100, msg, PAC_BODY);
                    }

                    // "LEVEL" and level number
                    draw_string(panel_x + 20, panel_y + 128, b"LEVEL", TEXT_LABEL);
                    draw_number(panel_x + 90, panel_y + 128, game.level, TEXT_COLOR);

                    // Second divider
                    fill_rect(panel_x + 20, panel_y + 152, panel_w - 40, 2, WALL_EDGE);

                    // Restart prompt (blinks)
                    let prompt = b"PRESS SPACE";
                    let prompt_w = prompt.len() * CHAR_PX_W;
                    draw_string(panel_x + (panel_w - prompt_w) / 2, panel_y + 168, prompt, TEXT_DIM);
                }

                // Blink the "PRESS SPACE" prompt every 8 ticks
                if game.state_timer > 0 && game.state_timer % 8 == 0 {
                    let maze_cx = MAZE_PX_X + MAZE_W * CELL_SIZE / 2;
                    let panel_w: usize = 280;
                    let panel_y = MAZE_PX_Y + MAZE_H * CELL_SIZE / 2 - 100;
                    let panel_x = maze_cx - panel_w / 2;
                    let prompt = b"PRESS SPACE";
                    let prompt_w = prompt.len() * CHAR_PX_W;
                    let blink_on = (game.state_timer / 8) % 2 == 0;
                    let prompt_color = if blink_on { PELLET_COLOR } else { TEXT_DIM };
                    // Erase and redraw prompt area
                    fill_rect(panel_x + 10, panel_y + 166, panel_w - 20, 16, BG_VOID);
                    draw_string(panel_x + (panel_w - prompt_w) / 2, panel_y + 168, prompt, prompt_color);
                }

                game.state_timer += 1;
            }
            GameState::Paused => {
                // Do nothing, wait for space
            }
        }

        // --- Render ---
        if game.state == GameState::Playing || game.state == GameState::Dying {
            // Erase previous positions
            erase_cell(game.prev_pac_x, game.prev_pac_y);
            // Redraw dot/pellet if still present at previous position
            let prev_idx = maze_idx(game.prev_pac_x, game.prev_pac_y);
            if game.maze[prev_idx] == CELL_DOT {
                draw_dot(game.prev_pac_x as usize, game.prev_pac_y as usize);
            } else if game.maze[prev_idx] == CELL_PELLET {
                draw_pellet(
                    game.prev_pac_x as usize,
                    game.prev_pac_y as usize,
                    game.pellet_blink,
                );
            }

            for i in 0..4 {
                erase_cell(game.ghosts[i].prev_x, game.ghosts[i].prev_y);
                // Redraw dot/pellet at ghost's previous position
                let gidx = maze_idx(game.ghosts[i].prev_x, game.ghosts[i].prev_y);
                if game.maze[gidx] == CELL_DOT {
                    draw_dot(game.ghosts[i].prev_x as usize, game.ghosts[i].prev_y as usize);
                } else if game.maze[gidx] == CELL_PELLET {
                    draw_pellet(
                        game.ghosts[i].prev_x as usize,
                        game.ghosts[i].prev_y as usize,
                        game.pellet_blink,
                    );
                }
            }

            // Draw characters at new positions
            draw_pacman(game.pac_x, game.pac_y, game.pac_dir, game.mouth_open);
            for i in 0..4 {
                draw_ghost(
                    game.ghosts[i].x,
                    game.ghosts[i].y,
                    i,
                    game.ghosts[i].dir,
                    game.ghosts[i].frightened_ticks > 0,
                    game.ghosts[i].eaten,
                );
            }

            // Blink pellets
            for gy in 0..MAZE_H {
                for gx in 0..MAZE_W {
                    if game.maze[gy * MAZE_W + gx] == CELL_PELLET {
                        draw_pellet(gx, gy, game.pellet_blink);
                    }
                }
            }
        }

        // Update HUD only when values change
        if game.score != game.prev_score
            || game.high_score != game.prev_high_score
            || game.lives != game.prev_lives
            || game.level != game.prev_level
        {
            draw_hud_values(game.score, game.high_score, game.lives, game.level);
            game.prev_score = game.score;
            game.prev_high_score = game.high_score;
            game.prev_lives = game.lives;
            game.prev_level = game.level;
        }

        fb_flush();

        // --- Frame pacing ---
        let frame_end = get_time();
        let elapsed = (frame_end - frame_start) as usize;
        if elapsed < FRAME_MS {
            sleep(FRAME_MS - elapsed);
        } else {
            sched_yield();
        }
    }

    // Cleanup
    kill_ghosts(game);

    // Save high score on exit
    if game.score > load_high_score() {
        save_high_score(game.score);
    }

    crate::println!("Pac-Man exiting. Final score: {}", game.score);
}