summaryrefslogtreecommitdiffstats
path: root/src/game.rs
blob: 133a43fdde9a3e354f3db339c649d0d4e03102e1 (plain) (blame)
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
use rand::Rng;

// --------------- game state machine ---------------

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum GameState {
    WaitingForInput,
    AnimatingPlayer,
    AnimatingEnemies,
    ResolvingTurn,
    GameOver,
}

// --------------- maze grid ---------------

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Cell {
    Wall,
    Passage,
    Exit,
}

/// An item the player can pick up.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PickupType {
    Food,
    Pill,
    Bandage,
    Weapon { base_damage: u32 },
}

/// Something occupying a maze cell (other than walls).
#[derive(Clone)]
pub enum Entity {
    #[allow(dead_code)]
    Enemy {
        hp: u32,
        max_hp: u32,
        damage: u32,
    },
    Hallucination {
        persistent: bool,
        hp: u32,
    },
    Pickup(PickupType),
    HallucinatedPickup(PickupType),
}

/// An item carried in the player's inventory.
#[derive(Clone, Copy)]
pub struct InventoryItem {
    pub pickup: PickupType,
    pub is_hallucination: bool,
}

pub struct Maze {
    cells: Vec<Cell>,
    entities: Vec<Option<Entity>>,
    width: usize,
    height: usize,
    pub exit_x: usize,
    pub exit_y: usize,
}

/// A rectangular room placed on the grid.
struct Room {
    x: usize,  // top-left column
    y: usize,  // top-left row
    w: usize,  // interior width  (cells)
    h: usize,  // interior height (cells)
    cx: usize, // centre column (for corridor connections)
    cy: usize, // centre row
}

impl Maze {
    /// Generate a rooms-and-corridors dungeon for the given Depth.
    pub fn generate(depth: u64, rng: &mut impl Rng) -> (Self, (f64, f64)) {
        let size = grid_size_for_depth(depth);
        let room_target = room_count_for_size(size);

        let w = size;
        let h = size;
        let mut cells = vec![Cell::Wall; w * h];

        // ---- Phase 1: place rooms ----
        let mut rooms: Vec<Room> = Vec::new();
        let max_attempts = 300;

        for _ in 0..max_attempts {
            if rooms.len() >= room_target {
                break;
            }

            let rw = rng.random_range(3usize..=6);
            let rh = rng.random_range(3usize..=6);

            // Keep rooms away from the outer border by at least 2 cells
            // so corridors have room to connect to them.
            if rw + 2 >= w || rh + 2 >= h {
                continue;
            }
            let rx = rng.random_range(2..(w - rw - 2));
            let ry = rng.random_range(2..(h - rh - 2));

            // Check overlap with 1-cell buffer.
            let mut overlaps = false;
            for room in &rooms {
                if rx < room.x + room.w + 1
                    && rx + rw + 1 > room.x
                    && ry < room.y + room.h + 1
                    && ry + rh + 1 > room.y
                {
                    overlaps = true;
                    break;
                }
            }

            if !overlaps {
                // Carve room interior.
                for dy in 0..rh {
                    for dx in 0..rw {
                        cells[(ry + dy) * w + (rx + dx)] = Cell::Passage;
                    }
                }

                rooms.push(Room {
                    x: rx,
                    y: ry,
                    w: rw,
                    h: rh,
                    cx: rx + rw / 2,
                    cy: ry + rh / 2,
                });
            }
        }

        // We need at least 2 rooms.
        if rooms.len() < 2 {
            // Fallback: force-place two small rooms.
            rooms.clear();
            cells.fill(Cell::Wall);
            for i in 0..2 {
                let rx = 2 + i * (w - 8);
                let ry = 2 + i * (h - 8);
                let rw = 4;
                let rh = 4;
                for dy in 0..rh {
                    for dx in 0..rw {
                        let px = (rx + dx).min(w - 1);
                        let py = (ry + dy).min(h - 1);
                        cells[py * w + px] = Cell::Passage;
                    }
                }
                rooms.push(Room {
                    x: rx,
                    y: ry,
                    w: rw,
                    h: rh,
                    cx: rx + rw / 2,
                    cy: ry + rh / 2,
                });
            }
        }

        // ---- Phase 2: connect rooms with a spanning tree (Prim) ----
        let mut connected = vec![false; rooms.len()];
        connected[0] = true;
        let mut edges: Vec<(usize, usize, usize)> = Vec::new(); // (dist, from, to)

        loop {
            edges.clear();
            for (i, ri) in rooms.iter().enumerate() {
                if !connected[i] {
                    continue;
                }
                for (j, rj) in rooms.iter().enumerate() {
                    if connected[j] {
                        continue;
                    }
                    let dist = manhattan(
                        ri.cx as isize,
                        ri.cy as isize,
                        rj.cx as isize,
                        rj.cy as isize,
                    );
                    edges.push((dist as usize, i, j));
                }
            }

            if edges.is_empty() {
                break;
            }

            edges.sort_by_key(|e| e.0);
            // Pick from the nearest few for variety.
            let pick = rng.random_range(0..(edges.len().min(3)));
            let (_dist, from, to) = edges[pick];

            carve_corridor(
                &mut cells,
                w,
                rooms[from].cx,
                rooms[from].cy,
                rooms[to].cx,
                rooms[to].cy,
                rng,
            );
            connected[to] = true;
        }

        // ---- Phase 3: add a few extra connections for loops ----
        let extra_connections = (rooms.len() / 5).max(1);
        for _ in 0..extra_connections {
            let a = rng.random_range(0..rooms.len());
            let b = rng.random_range(0..rooms.len());
            if a != b {
                let dist = manhattan(
                    rooms[a].cx as isize,
                    rooms[a].cy as isize,
                    rooms[b].cx as isize,
                    rooms[b].cy as isize,
                );
                // Only add short extra connections to avoid spaghetti.
                if dist < (w as isize + h as isize) / 4 {
                    carve_corridor(
                        &mut cells,
                        w,
                        rooms[a].cx,
                        rooms[a].cy,
                        rooms[b].cx,
                        rooms[b].cy,
                        rng,
                    );
                }
            }
        }

        // ---- Phase 4: place exit in the room farthest from start ----
        let start_room_idx = 0; // first room placed is near top-left
        let mut farthest = 0;
        let mut farthest_dist = 0.0f64;
        for (i, room) in rooms.iter().enumerate() {
            if i == start_room_idx {
                continue;
            }
            let dx = room.cx as f64 - rooms[start_room_idx].cx as f64;
            let dy = room.cy as f64 - rooms[start_room_idx].cy as f64;
            let d = (dx * dx + dy * dy).sqrt();
            if d > farthest_dist {
                farthest_dist = d;
                farthest = i;
            }
        }

        let exit_room = &rooms[farthest];
        let exit_x = exit_room.cx;
        let exit_y = exit_room.cy;
        cells[exit_y * w + exit_x] = Cell::Exit;

        // Player starts in the first room.
        let start_x = rooms[start_room_idx].cx as f64 + 0.5;
        let start_y = rooms[start_room_idx].cy as f64 + 0.5;

        // ---- Phase 5: place entities ----
        let mut entities: Vec<Option<Entity>> = vec![None; w * h];
        place_entities(
            &cells,
            &mut entities,
            w,
            h,
            depth,
            start_x as usize,
            start_y as usize,
            rng,
        );

        (
            Self {
                cells,
                entities,
                width: w,
                height: h,
                exit_x,
                exit_y,
            },
            (start_x, start_y),
        )
    }

    #[inline]
    pub fn is_wall(&self, y: usize, x: usize) -> bool {
        self.cells
            .get(y * self.width + x)
            .map_or(true, |&c| c == Cell::Wall)
    }

    /// Floating-point query — out-of-bounds is treated as wall.
    #[inline]
    pub fn is_passage_at_float(&self, x: f64, y: f64) -> bool {
        let xi = x as usize;
        let yi = y as usize;
        if xi >= self.width || yi >= self.height {
            return false;
        }
        self.cells[yi * self.width + xi] != Cell::Wall
    }

    #[inline]
    pub fn is_exit(&self, x: f64, y: f64) -> bool {
        let xi = x as usize;
        let yi = y as usize;
        if xi >= self.width || yi >= self.height {
            return false;
        }
        self.cells[yi * self.width + xi] == Cell::Exit
    }

    pub fn width(&self) -> usize {
        self.width
    }
    pub fn height(&self) -> usize {
        self.height
    }

    // ---- entity accessors ----

    /// Get the entity at grid coordinates, if any.
    pub fn entity_at(&self, x: usize, y: usize) -> Option<&Entity> {
        self.entities
            .get(y * self.width + x)
            .and_then(|e| e.as_ref())
    }

    /// Mutable reference to entity at grid coordinates.
    pub fn entity_at_mut(&mut self, x: usize, y: usize) -> Option<&mut Entity> {
        self.entities
            .get_mut(y * self.width + x)
            .and_then(|e| e.as_mut())
    }

    /// Remove and return the entity at grid coordinates.
    pub fn take_entity(&mut self, x: usize, y: usize) -> Option<Entity> {
        self.entities
            .get_mut(y * self.width + x)
            .and_then(|e| e.take())
    }

    /// Check if a cell is occupied by any entity.
    #[allow(dead_code)]
    pub fn is_occupied(&self, x: usize, y: usize) -> bool {
        self.entity_at(x, y).is_some()
    }

    /// Check if the entity at a cell is a persistent hallucination.
    #[allow(dead_code)]
    pub fn is_persistent_hallucination(&self, x: usize, y: usize) -> bool {
        matches!(
            self.entity_at(x, y),
            Some(Entity::Hallucination {
                persistent: true,
                ..
            })
        )
    }
}

// ---- Maze helpers ----

fn grid_size_for_depth(depth: u64) -> usize {
    match depth {
        1..=3 => 33,
        4..=7 => 41,
        8..=12 => 49,
        _ => 57,
    }
}

fn room_count_for_size(size: usize) -> usize {
    match size {
        33 => 8,
        41 => 12,
        49 => 16,
        _ => 20,
    }
}

fn manhattan(x1: isize, y1: isize, x2: isize, y2: isize) -> isize {
    (x1 - x2).abs() + (y1 - y2).abs()
}

/// Carve an L-shaped corridor between two points.  Randomly picks
/// horizontal-first or vertical-first, and widens to 2 cells occasionally.
fn carve_corridor(
    cells: &mut Vec<Cell>,
    grid_w: usize,
    x1: usize,
    y1: usize,
    x2: usize,
    y2: usize,
    rng: &mut impl Rng,
) {
    let cx = x1 as isize;
    let cy = y1 as isize;
    let tx = x2 as isize;
    let ty = y2 as isize;

    let wide = rng.random_bool(0.3); // 30% chance of 2-wide corridor

    if rng.random_bool(0.5) {
        // Horizontal, then vertical.
        carve_line(cells, grid_w, cx, cy, tx, cy, wide);
        carve_line(cells, grid_w, tx, cy, tx, ty, wide);
    } else {
        // Vertical, then horizontal.
        carve_line(cells, grid_w, cx, cy, cx, ty, wide);
        carve_line(cells, grid_w, cx, ty, tx, ty, wide);
    }
}

/// Carve a straight line of passages from (x1,y1) to (x2,y2).
/// If `wide` is true, also clears the adjacent parallel cell.
fn carve_line(
    cells: &mut Vec<Cell>,
    grid_w: usize,
    x1: isize,
    y1: isize,
    x2: isize,
    y2: isize,
    wide: bool,
) {
    let dx = (x2 - x1).signum();
    let dy = (y2 - y1).signum();
    let steps = (x2 - x1).abs().max((y2 - y1).abs());

    let perp_dx = -dy; // perpendicular for widening
    let perp_dy = dx;

    let mut x = x1;
    let mut y = y1;

    for _ in 0..=steps {
        if x >= 0 && x < grid_w as isize && y >= 0 && y < grid_w as isize {
            cells[y as usize * grid_w + x as usize] = Cell::Passage;
        }
        if wide {
            let wx = x + perp_dx;
            let wy = y + perp_dy;
            if wx >= 0 && wx < grid_w as isize && wy >= 0 && wy < grid_w as isize {
                cells[wy as usize * grid_w + wx as usize] = Cell::Passage;
            }
        }
        x += dx;
        y += dy;
    }
}

/// Place enemies, hallucinations, and pickups in random passage cells.
fn place_entities(
    cells: &[Cell],
    entities: &mut [Option<Entity>],
    w: usize,
    h: usize,
    depth: u64,
    start_x: usize,
    start_y: usize,
    rng: &mut impl Rng,
) {
    // Collect eligible passage cells (not start, not exit).
    let mut candidates: Vec<(usize, usize)> = Vec::new();
    for y in 1..h - 1 {
        for x in 1..w - 1 {
            if cells[y * w + x] == Cell::Passage && !(x == start_x && y == start_y) {
                candidates.push((x, y));
            }
        }
    }

    if candidates.is_empty() {
        return;
    }

    // Shuffle for random placement.
    shuffle_slice(&mut candidates, rng);
    let mut next = 0usize;

    // --- real enemies ---
    let enemy_count = 3 + depth as usize * 2;
    for _ in 0..enemy_count {
        if next >= candidates.len() {
            break;
        }
        let (x, y) = candidates[next];
        next += 1;

        let (hp_range, damage) = enemy_stats_for_depth(depth);
        let max_hp = rng.random_range(hp_range.0..=hp_range.1);
        let dmg = if damage.0 == damage.1 {
            damage.0
        } else {
            rng.random_range(damage.0..=damage.1)
        };

        entities[y * w + x] = Some(Entity::Enemy {
            hp: max_hp,
            max_hp,
            damage: dmg,
        });
    }

    // --- hallucinations (1-2 per level) ---
    let hall_count = rng.random_range(1..=2);
    for _ in 0..hall_count {
        if next >= candidates.len() {
            break;
        }
        let (x, y) = candidates[next];
        next += 1;
        entities[y * w + x] = Some(Entity::Hallucination {
            persistent: false,
            hp: 1,
        });
    }

    // --- real pickups ---
    let pickup_count = 2 + (depth as usize / 2);
    for i in 0..pickup_count {
        if next >= candidates.len() {
            break;
        }
        let (x, y) = candidates[next];
        next += 1;

        let pt = if i == 0 && depth % 2 == 0 {
            // Guaranteed weapon every even depth.
            let base_dmg = 2 + depth as u32 / 3;
            PickupType::Weapon {
                base_damage: base_dmg,
            }
        } else {
            random_pickup_type(rng, false)
        };

        entities[y * w + x] = Some(Entity::Pickup(pt));
    }

    // --- hallucinated pickups ---
    let fake_count = if depth >= 3 {
        rng.random_range(1..=2)
    } else {
        0
    };
    for _ in 0..fake_count {
        if next >= candidates.len() {
            break;
        }
        let (x, y) = candidates[next];
        next += 1;
        let pt = random_pickup_type(rng, true);
        entities[y * w + x] = Some(Entity::HallucinatedPickup(pt));
    }
}

fn enemy_stats_for_depth(depth: u64) -> ((u32, u32), (u32, u32)) {
    match depth {
        1 => ((1, 1), (1, 1)),
        2..=3 => ((2, 3), (1, 1)),
        4..=6 => ((3, 5), (1, 2)),
        7..=9 => ((5, 8), (2, 2)),
        _ => ((8, 12), (2, 3)),
    }
}

fn random_pickup_type(rng: &mut impl Rng, include_weapon: bool) -> PickupType {
    let roll = rng.random_range(0..100);
    if include_weapon && roll < 15 {
        PickupType::Weapon {
            base_damage: rng.random_range(2..=4),
        }
    } else if roll < 45 {
        PickupType::Food
    } else if roll < 75 {
        PickupType::Pill
    } else {
        PickupType::Bandage
    }
}

/// Fisher-Yates shuffle on a slice.
fn shuffle_slice<T>(slice: &mut [T], rng: &mut impl Rng) {
    for i in (1..slice.len()).rev() {
        let j = rng.random_range(0..=i);
        slice.swap(i, j);
    }
}

// --------------- player ---------------

pub struct Player {
    pub x: f64,
    pub y: f64,
    pub angle: f64, // radians, 0 = +x (east), π/2 = +y (south)
}

impl Player {
    pub fn new(x: f64, y: f64, angle: f64) -> Self {
        Self { x, y, angle }
    }
}

// --------------- top-level game ---------------

const MOVE_DURATION: f64 = 0.18; // seconds to walk one tile
const TURN_DURATION: f64 = 0.12; // seconds for a 90° turn
const ENEMY_ANIM_DURATION: f64 = 0.10; // seconds for enemy movement
const ATTACK_DURATION: f64 = 0.12; // seconds for attack lunge

/// An enemy movement queued for animation.
#[derive(Clone)]
struct EnemyMove {
    from_x: usize,
    from_y: usize,
    to_x: usize,
    to_y: usize,
    entity: Entity,
}

pub const MAX_HP: u32 = 5;
pub const MAX_SANITY: u32 = 100;
pub const MAX_WEAKNESS: u32 = 100;

pub struct Game {
    pub maze: Maze,
    pub player: Player,
    pub wall_texture: Vec<u32>,
    pub floor_texture: Vec<u32>,
    pub exit_texture: Vec<u32>,

    // ---- turn-based resources ----
    pub hp: u32,
    pub max_hp: u32,
    pub sanity: u32,   // 0..100
    pub weakness: u32, // 0..100; max = HP drain

    /// Whole turns elapsed (displayed in HUD as heartbeats).
    pub heartbeat_count: u64,

    // ---- state machine ----
    pub state: GameState,

    // ---- score tracking ----
    pub kills: u64,
    pub depth: u64,

    // ---- weapon & inventory ----
    pub weapon_base_damage: u32,
    pub inventory: [Option<InventoryItem>; 4],
    pub selected_slot: usize,

    // ---- message log ----
    pub message: String,
    pub message_turns: u32,

    // ---- animation: player movement ----
    pub moving: bool,
    move_start: (f64, f64),
    move_target: (f64, f64),
    move_t: f64, // 0.0 → 1.0

    // ---- animation: player turn ----
    pub turning: bool,
    turn_start: f64,
    turn_delta: f64, // signed radians to rotate
    turn_t: f64,

    // ---- animation: enemies ----
    enemy_anim_t: f64,
    enemy_moves: Vec<EnemyMove>,

    /// Enemies that already retaliated this turn (skip their independent attack).
    acted_this_turn: Vec<(usize, usize)>,

    // ---- animation: attack ----
    pub attacking: bool,
    pub attack_t: f64,
    attack_base_x: f64,
    attack_base_y: f64,

    // ---- screen flash ----
    pub flash_color: u32,
    pub flash_alpha: f64,

    // ---- controls overlay ----
    pub show_controls: bool,

    // ---- death screen ----
    pub death_frames: u32,

    // ---- horror effects ----
    frame_counter: u64,
}

fn smoothstep(t: f64) -> f64 {
    t * t * (3.0 - 2.0 * t)
}

impl Game {
    pub fn new() -> Self {
        let mut rng = rand::rng();
        let depth = 1;
        let (maze, (start_x, start_y)) = Maze::generate(depth, &mut rng);
        let player = Player::new(start_x, start_y, 0.0); // facing east
        let wall_texture = crate::texture::generate_wall_texture(&mut rng);
        let floor_texture = crate::texture::generate_floor_texture(&mut rng);
        let exit_texture = crate::texture::generate_exit_texture(&mut rng);

        Self {
            maze,
            player,
            wall_texture,
            floor_texture,
            exit_texture,
            hp: MAX_HP,
            max_hp: MAX_HP,
            sanity: MAX_SANITY,
            weakness: 0,
            heartbeat_count: 0,
            state: GameState::WaitingForInput,
            kills: 0,
            depth: 1,
            weapon_base_damage: 1, // fists
            inventory: [None; 4],
            selected_slot: 0,
            message: String::new(),
            message_turns: 0,
            moving: false,
            move_start: (0.0, 0.0),
            move_target: (0.0, 0.0),
            move_t: 0.0,
            turning: false,
            turn_start: 0.0,
            turn_delta: 0.0,
            turn_t: 0.0,
            enemy_anim_t: 0.0,
            enemy_moves: Vec::new(),
            acted_this_turn: Vec::new(),
            attacking: false,
            attack_t: 0.0,
            attack_base_x: 0.0,
            attack_base_y: 0.0,
            flash_color: 0,
            flash_alpha: 0.0,
            show_controls: true,
            death_frames: 0,
            frame_counter: 0,
        }
    }

    // ---- state transitions ------------------------------------------------

    /// Returns true if the player may act right now.
    pub fn can_act(&self) -> bool {
        self.state == GameState::WaitingForInput && !self.turning
    }

    /// Advance animations by `dt` seconds.  Called every frame.
    /// Returns true when the current animation phase finishes and we should
    /// advance the state machine.
    pub fn update_animation(&mut self, dt: f64) -> bool {
        self.frame_counter = self.frame_counter.wrapping_add(1);

        // Flash always fades, regardless of state.
        if self.flash_alpha > 0.0 {
            self.flash_alpha = (self.flash_alpha - dt * 4.0).max(0.0);
        }

        // Turn animation runs independently — turning never consumes a turn.
        if self.turning {
            self.turn_t += dt / TURN_DURATION;
            if self.turn_t >= 1.0 {
                self.player.angle =
                    (self.turn_start + self.turn_delta).rem_euclid(2.0 * std::f64::consts::PI);
                self.turning = false;
            } else {
                let t = smoothstep(self.turn_t);
                self.player.angle = self.turn_start + self.turn_delta * t;
            }
        }

        match self.state {
            GameState::AnimatingPlayer => {
                let mut done = true;

                // Animate tile-to-tile walk.
                if self.moving {
                    self.move_t += dt / MOVE_DURATION;
                    if self.move_t >= 1.0 {
                        self.player.x = self.move_target.0;
                        self.player.y = self.move_target.1;
                        self.moving = false;
                    } else {
                        let t = smoothstep(self.move_t);
                        self.player.x =
                            self.move_start.0 + (self.move_target.0 - self.move_start.0) * t;
                        self.player.y =
                            self.move_start.1 + (self.move_target.1 - self.move_start.1) * t;
                        done = false;
                    }
                }

                // Animate attack lunge.
                if self.attacking {
                    self.attack_t += dt / ATTACK_DURATION;
                    if self.attack_t >= 1.0 {
                        self.player.x = self.attack_base_x;
                        self.player.y = self.attack_base_y;
                        self.attacking = false;
                    } else {
                        // Lunge forward then back.
                        let lunge = if self.attack_t < 0.5 {
                            smoothstep(self.attack_t * 2.0) * 0.25
                        } else {
                            (1.0 - smoothstep((self.attack_t - 0.5) * 2.0)) * 0.25
                        };
                        let fx = self.player.angle.cos();
                        let fy = self.player.angle.sin();
                        self.player.x = self.attack_base_x + fx * lunge;
                        self.player.y = self.attack_base_y + fy * lunge;
                        done = false;
                    }
                }

                if done {
                    let enemies_moved = self.compute_enemy_turns();
                    if self.state == GameState::GameOver {
                        return true;
                    }
                    if enemies_moved {
                        self.state = GameState::AnimatingEnemies;
                        self.enemy_anim_t = 0.0;
                    } else {
                        self.state = GameState::ResolvingTurn;
                        self.resolve_turn();
                        if self.state != GameState::GameOver {
                            self.state = GameState::WaitingForInput;
                        }
                    }
                    return true;
                }
            }

            GameState::AnimatingEnemies => {
                self.enemy_anim_t += dt;
                if self.enemy_anim_t >= ENEMY_ANIM_DURATION {
                    self.enemy_anim_t = 0.0;
                    self.apply_enemy_moves();
                    self.state = GameState::ResolvingTurn;
                    self.resolve_turn();
                    if self.state != GameState::GameOver {
                        self.state = GameState::WaitingForInput;
                    }
                    return true;
                }
            }

            _ => {}
        }

        // Count frames since death so the death screen has a minimum display time.
        if self.state == GameState::GameOver {
            self.death_frames += 1;
        }

        false
    }

    /// Attempt to walk one tile in grid direction (dx, dy).
    /// Handles entity interactions (enemies block, hallucinations vanish, pickups collect).
    fn try_move_tile(&mut self, dx: isize, dy: isize) -> bool {
        if !self.can_act() {
            return false;
        }
        let cx = self.player.x.floor() as isize;
        let cy = self.player.y.floor() as isize;
        let tx = (cx + dx) as usize;
        let ty = (cy + dy) as usize;

        // The target cell must be a passage.
        if !self
            .maze
            .is_passage_at_float(tx as f64 + 0.5, ty as f64 + 0.5)
        {
            return false;
        }

        // Check what's in the target cell.
        match self.maze.entity_at(tx, ty).cloned() {
            Some(Entity::Enemy { damage, .. }) => {
                // Blocked by real enemy — waste the turn, take damage.
                self.set_message("Something is blocking your way.");
                self.hp = self.hp.saturating_sub(damage);
                self.acted_this_turn.push((tx, ty));
                self.advance_turn();
                if self.hp == 0 {
                    self.state = GameState::GameOver;
                }
                return true; // action consumed
            }
            Some(Entity::Hallucination {
                persistent: true, ..
            }) => {
                // Persistent hallucination blocks movement.
                self.set_message("You are frightened to death just by thinking about doing this.");
                self.advance_turn();
                return true;
            }
            Some(Entity::Hallucination {
                persistent: false, ..
            }) => {
                // Non-persistent hallucination vanishes harmlessly.
                self.maze.take_entity(tx, ty);
                // Fall through to normal movement.
            }
            Some(Entity::Pickup(pt)) => {
                // Collect the pickup, then move.
                self.collect_pickup(pt, tx, ty);
                // Fall through to normal movement.
            }
            Some(Entity::HallucinatedPickup(pt)) => {
                // Collect the fake pickup.
                self.collect_hallucinated_pickup(pt, tx, ty);
                // Fall through to normal movement.
            }
            None => {
                // Empty cell — normal movement.
            }
        }

        // Normal tile movement.
        self.move_start = (self.player.x, self.player.y);
        self.move_target = (tx as f64 + 0.5, ty as f64 + 0.5);
        self.moving = true;
        self.move_t = 0.0;
        self.state = GameState::AnimatingPlayer;
        true
    }

    // ---- movement wrappers ----

    pub fn move_forward(&mut self) -> bool {
        let (dx, dy) = self.facing_delta();
        self.try_move_tile(dx, dy)
    }

    pub fn move_backward(&mut self) -> bool {
        let (dx, dy) = self.facing_delta();
        self.try_move_tile(-dx, -dy)
    }

    pub fn strafe_left(&mut self) -> bool {
        let (dx, dy) = self.facing_delta();
        self.try_move_tile(dy, -dx)
    }

    pub fn strafe_right(&mut self) -> bool {
        let (dx, dy) = self.facing_delta();
        self.try_move_tile(-dy, dx)
    }

    pub fn turn_left(&mut self) {
        if !self.can_act() {
            return;
        }
        self.turn_start = self.player.angle;
        self.turn_delta = -std::f64::consts::FRAC_PI_2;
        self.turn_t = 0.0;
        self.turning = true;
        // Turning is free — no state change, no turn consumed.
    }

    pub fn turn_right(&mut self) {
        if !self.can_act() {
            return;
        }
        self.turn_start = self.player.angle;
        self.turn_delta = std::f64::consts::FRAC_PI_2;
        self.turn_t = 0.0;
        self.turning = true;
        // Turning is free — no state change, no turn consumed.
    }

    // ---- attack -----------------------------------------------------------

    /// Roll bonus damage: 30% chance for +1, repeat on success.
    fn roll_bonus_damage(&self, rng: &mut impl Rng) -> u32 {
        let mut bonus = 0u32;
        while rng.random_bool(0.30) {
            bonus += 1;
        }
        bonus
    }

    /// Attack the cell directly ahead.
    pub fn attack(&mut self) -> bool {
        if !self.can_act() {
            return false;
        }

        let (fx, fy) = self.facing_cell();
        let fx = fx as usize;
        let fy = fy as usize;

        let entity = self.maze.entity_at(fx, fy).cloned();

        match entity {
            Some(Entity::Enemy { hp, damage, .. }) => {
                let mut rng = rand::rng();
                let bonus = self.roll_bonus_damage(&mut rng);
                let total_dmg = self.weapon_base_damage + bonus;
                let new_hp = hp.saturating_sub(total_dmg);

                if new_hp == 0 {
                    self.maze.take_entity(fx, fy);
                    self.kills += 1;
                    self.set_message(&format!("You slay the enemy! ({} dmg)", total_dmg));
                    self.flash_color = 0xFF_CC3333;
                    self.flash_alpha = 0.4;
                    self.begin_attack_animation();
                } else {
                    self.maze.entity_at_mut(fx, fy).map(|e| {
                        if let Entity::Enemy { hp: h, .. } = e {
                            *h = new_hp;
                        }
                    });
                    self.hp = self.hp.saturating_sub(damage);
                    self.acted_this_turn.push((fx, fy));
                    self.set_message(&format!(
                        "You hit the enemy for {} dmg. It strikes back!",
                        total_dmg
                    ));
                    if self.hp == 0 {
                        self.state = GameState::GameOver;
                    } else {
                        self.flash_color = 0xFF_CC3333;
                        self.flash_alpha = 0.4;
                        self.begin_attack_animation();
                    }
                }
                true
            }

            Some(Entity::Hallucination { persistent, hp }) => {
                self.sanity = self.sanity.saturating_sub(10);
                let new_hp = hp.saturating_sub(1);

                if !persistent || new_hp == 0 {
                    self.maze.take_entity(fx, fy);
                    self.set_message("The hallucination dissipates.");
                } else {
                    self.maze.entity_at_mut(fx, fy).map(|e| {
                        if let Entity::Hallucination { hp: h, .. } = e {
                            *h = new_hp;
                        }
                    });
                    self.set_message("You strike the apparition - it remains.");
                }
                self.flash_color = 0xFF_8833CC;
                self.flash_alpha = 0.35;
                self.begin_attack_animation();
                true
            }

            _ => {
                self.set_message("You swing at the air.");
                self.flash_color = 0xFF_FFFFFF;
                self.flash_alpha = 0.05;
                self.begin_attack_animation();
                true
            }
        }
    }

    fn begin_attack_animation(&mut self) {
        self.attack_base_x = self.player.x;
        self.attack_base_y = self.player.y;
        self.attacking = true;
        self.attack_t = 0.0;
        self.state = GameState::AnimatingPlayer;
    }

    // ---- inventory --------------------------------------------------------

    /// Use the currently selected inventory item (Z key).
    pub fn use_item(&mut self) {
        if !self.can_act() {
            return;
        }
        let item = match self.inventory[self.selected_slot] {
            Some(item) => item,
            None => {
                self.set_message("Nothing in that slot.");
                return;
            }
        };

        if item.is_hallucination {
            self.use_hallucinated_item();
            return;
        }

        match item.pickup {
            PickupType::Food => {
                self.weakness = self.weakness.saturating_sub(20);
                self.set_message("You eat the food. Weakness fades.");
            }
            PickupType::Pill => {
                self.weakness = self.weakness.saturating_sub(15);
                self.sanity = (self.sanity + 20).min(MAX_SANITY);
                self.set_message("The pill clears your mind and body.");
            }
            PickupType::Bandage => {
                self.weakness = self.weakness.saturating_sub(15);
                if self.hp < self.max_hp {
                    self.hp += 1;
                    self.set_message("You bandage your wounds. HP restored.");
                } else {
                    self.set_message("You bandage up. HP is already full.");
                }
            }
            PickupType::Weapon { .. } => {
                self.set_message("You can't use a weapon from inventory.");
                return;
            }
        }

        self.inventory[self.selected_slot] = None;
        self.advance_turn();
    }

    /// Use a hallucinated pickup — no effect, costs sanity.
    fn use_hallucinated_item(&mut self) {
        self.sanity = self.sanity.saturating_sub(5);
        self.set_message("It was never there...");
        self.inventory[self.selected_slot] = None;
        self.advance_turn();
    }

    /// Discard the currently selected inventory item (X key).
    pub fn discard_item(&mut self) {
        if !self.can_act() {
            return;
        }
        if self.inventory[self.selected_slot].is_some() {
            self.inventory[self.selected_slot] = None;
            self.set_message("Item discarded.");
            // Discarding does NOT consume a turn.
        }
    }

    /// Select an inventory slot (1-4 keys).
    pub fn select_slot(&mut self, slot: usize) {
        if slot < 4 {
            self.selected_slot = slot;
        }
    }

    /// Collect a real pickup into inventory.
    fn collect_pickup(&mut self, pt: PickupType, x: usize, y: usize) {
        self.maze.take_entity(x, y);

        match pt {
            PickupType::Weapon { base_damage } => {
                if base_damage > self.weapon_base_damage {
                    self.weapon_base_damage = base_damage;
                    self.set_message(&format!("Equipped weapon! Base damage: {}", base_damage));
                } else {
                    self.set_message("This weapon is no better than what you have.");
                }
            }
            _ => {
                let item = InventoryItem {
                    pickup: pt,
                    is_hallucination: false,
                };
                if let Some(slot) = self.inventory.iter_mut().find(|s| s.is_none()) {
                    *slot = Some(item);
                    self.set_message(match pt {
                        PickupType::Food => "Picked up food.",
                        PickupType::Pill => "Picked up pill.",
                        PickupType::Bandage => "Picked up bandage.",
                        _ => "Picked up item.",
                    });
                } else {
                    self.set_message("Inventory full.");
                }
            }
        }
    }

    /// Collect a hallucinated pickup.
    fn collect_hallucinated_pickup(&mut self, pt: PickupType, x: usize, y: usize) {
        self.maze.take_entity(x, y);
        let item = InventoryItem {
            pickup: pt,
            is_hallucination: true,
        };
        if let Some(slot) = self.inventory.iter_mut().find(|s| s.is_none()) {
            *slot = Some(item);
        }
        self.set_message("Picked up item.");
    }

    // ---- turn resolution --------------------------------------------------

    /// Advance the turn counter and state without animation.
    fn advance_turn(&mut self) {
        let enemies_moved = self.compute_enemy_turns();
        if self.state == GameState::GameOver {
            return;
        }
        if enemies_moved {
            self.state = GameState::AnimatingEnemies;
            self.enemy_anim_t = 0.0;
        } else {
            self.state = GameState::ResolvingTurn;
            self.resolve_turn();
            if self.state != GameState::GameOver {
                self.state = GameState::WaitingForInput;
            }
        }
    }

    /// Apply all per-turn effects (weakness, heartbeat, HP drain, message decay).
    fn resolve_turn(&mut self) {
        // Clear acted-this-turn tracking (enemy AI already consumed it).
        self.acted_this_turn.clear();

        // At sanity < 20%, hallucinations become persistent with extra HP.
        self.upgrade_hallucinations();
        if self.heartbeat_count % 3 == 0 {
            self.weakness = (self.weakness + 1).min(MAX_WEAKNESS);
        }
        self.heartbeat_count += 1;

        // Message decay.
        if self.message_turns > 0 {
            self.message_turns -= 1;
            if self.message_turns == 0 {
                self.message.clear();
            }
        }

        // HP drain at max weakness — stops at 1, never kills.
        if self.weakness >= MAX_WEAKNESS {
            if self.hp > 1 {
                self.hp -= 1;
            }
        }

        // Shifting maze: wall cells may flip at low sanity.
        self.shift_maze();
    }

    /// Skip the player's turn (C key).  Enemies still act.
    pub fn skip_turn(&mut self) {
        if !self.can_act() {
            return;
        }
        let enemies_moved = self.compute_enemy_turns();
        if self.state == GameState::GameOver {
            return;
        }
        if enemies_moved {
            self.state = GameState::AnimatingEnemies;
            self.enemy_anim_t = 0.0;
        } else {
            self.state = GameState::ResolvingTurn;
            self.resolve_turn();
            if self.state != GameState::GameOver {
                self.state = GameState::WaitingForInput;
            }
        }
    }

    /// Set a HUD message that persists for 3 turns.
    pub fn set_message(&mut self, msg: &str) {
        self.message = msg.to_string();
        self.message_turns = 3;
    }

    // ---- cardinal-direction helpers ----

    /// Which grid direction the player faces: (dx, dy) ∈ {±1, 0}.
    // ---- enemy AI ---------------------------------------------------------

    /// DDA line-of-sight check from grid cell (ex,ey) to player position (px,py).
    fn has_line_of_sight(&self, ex: usize, ey: usize, px: f64, py: f64) -> bool {
        let sx = ex as f64 + 0.5;
        let sy = ey as f64 + 0.5;
        let dx = px - sx;
        let dy = py - sy;
        let dist = (dx * dx + dy * dy).sqrt();
        if dist < 0.01 {
            return true;
        }
        // Walk the grid line; step size is half a cell for accuracy.
        let steps = (dist * 2.0).ceil() as usize;
        for i in 1..steps {
            let t = i as f64 / steps as f64;
            let cx = (sx + dx * t) as usize;
            let cy = (sy + dy * t) as usize;
            // Reached player cell — LOS confirmed.
            if cy == py as usize && cx == px as usize {
                return true;
            }
            if self.maze.is_wall(cy, cx) {
                return false;
            }
        }
        true
    }

    /// Try to move the enemy at (ex,ey) one tile toward the player.
    /// Queues the move in `enemy_moves` and removes the entity from the grid.
    /// `occupied` tracks cells that are already taken (by other enemy moves or static entities).
    fn try_move_enemy_toward(&mut self, ex: usize, ey: usize, occupied: &mut Vec<bool>) {
        let px = self.player.x.floor() as isize;
        let py = self.player.y.floor() as isize;

        // Four cardinal neighbours, sorted by Manhattan distance to player.
        let dirs: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
        let mut best: Option<(usize, usize, isize)> = None;

        for (dx, dy) in dirs {
            let nx = ex as isize + dx;
            let ny = ey as isize + dy;
            if nx < 0 || ny < 0 {
                continue;
            }
            let nx = nx as usize;
            let ny = ny as usize;
            if nx >= self.maze.width() || ny >= self.maze.height() {
                continue;
            }
            // Must be a passage and not occupied.
            if !self
                .maze
                .is_passage_at_float(nx as f64 + 0.5, ny as f64 + 0.5)
            {
                continue;
            }
            if occupied[ny * self.maze.width() + nx] {
                continue;
            }
            let dist = manhattan(nx as isize, ny as isize, px, py);
            let current = manhattan(ex as isize, ey as isize, px, py);
            if dist < current {
                match best {
                    None => best = Some((nx, ny, dist)),
                    Some((_, _, best_dist)) if dist < best_dist => best = Some((nx, ny, dist)),
                    _ => {}
                }
            }
        }

        if let Some((tx, ty, _)) = best {
            let entity = self.maze.take_entity(ex, ey).unwrap();
            occupied[ty * self.maze.width() + tx] = true;
            self.enemy_moves.push(EnemyMove {
                from_x: ex,
                from_y: ey,
                to_x: tx,
                to_y: ty,
                entity,
            });
        }
    }

    /// Try to move the enemy at (ex,ey) to a random adjacent passage cell (patrol).
    fn try_patrol_enemy(&mut self, ex: usize, ey: usize, occupied: &mut Vec<bool>) {
        let mut rng = rand::rng();
        let dirs: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
        // Shuffle directions.
        let mut indices = [0usize, 1, 2, 3];
        for i in (1..4).rev() {
            let j = rng.random_range(0..=i);
            indices.swap(i, j);
        }

        for &idx in &indices {
            let (dx, dy) = dirs[idx];
            let nx = ex as isize + dx;
            let ny = ey as isize + dy;
            if nx < 0 || ny < 0 {
                continue;
            }
            let nx = nx as usize;
            let ny = ny as usize;
            if nx >= self.maze.width() || ny >= self.maze.height() {
                continue;
            }
            if !self
                .maze
                .is_passage_at_float(nx as f64 + 0.5, ny as f64 + 0.5)
            {
                continue;
            }
            if occupied[ny * self.maze.width() + nx] {
                continue;
            }
            let entity = self.maze.take_entity(ex, ey).unwrap();
            occupied[ny * self.maze.width() + nx] = true;
            self.enemy_moves.push(EnemyMove {
                from_x: ex,
                from_y: ey,
                to_x: nx,
                to_y: ny,
                entity,
            });
            return;
        }
    }

    /// Compute actions for every enemy/hallucination on the level.
    /// Attacks are applied immediately; moves are queued in `enemy_moves`.
    /// Returns true if any enemy moved (needs animation).
    fn compute_enemy_turns(&mut self) -> bool {
        self.enemy_moves.clear();

        let w = self.maze.width();
        let h = self.maze.height();

        // Occupied mask: cells that are taken (by static entities or queued moves).
        let mut occupied = vec![false; w * h];
        for y in 0..h {
            for x in 0..w {
                if self.maze.entity_at(x, y).is_some() {
                    occupied[y * w + x] = true;
                }
            }
        }
        // Also mark the player's cell as occupied so enemies don't walk into it.
        let pcx_usize = self.player.x.floor() as usize;
        let pcy_usize = self.player.y.floor() as usize;
        if pcx_usize < w && pcy_usize < h {
            occupied[pcy_usize * w + pcx_usize] = true;
        }

        // Gather all enemy/hallucination positions (snapshot before mutation).
        let mut enemy_positions: Vec<(usize, usize)> = Vec::new();
        for y in 0..h {
            for x in 0..w {
                match self.maze.entity_at(x, y) {
                    Some(Entity::Enemy { .. }) | Some(Entity::Hallucination { .. }) => {
                        enemy_positions.push((x, y));
                    }
                    _ => {}
                }
            }
        }

        let px = self.player.x;
        let py = self.player.y;
        let pcx = px.floor() as isize;
        let pcy = py.floor() as isize;
        let is_patrol_turn = self.heartbeat_count % 3 == 0;

        // Drain acted-this-turn list for fast lookups.
        let acted: Vec<(usize, usize)> = self.acted_this_turn.drain(..).collect();

        for (ex, ey) in enemy_positions {
            // Entity may have been removed by a previous enemy's action.
            let entity = match self.maze.entity_at(ex, ey) {
                Some(e) => e.clone(),
                None => continue,
            };

            let is_hallucination = matches!(entity, Entity::Hallucination { .. });

            // ---- hallucination behaviour gating ----
            if is_hallucination {
                if self.depth <= 3 || self.sanity >= 40 {
                    // Depth 1-3: hallucinations always static.
                    // Sanity >= 40%: hallucinations are static.
                    continue;
                }
                // Depth 4+ and sanity 20-39%: patrol only.
                // Depth 7+ and sanity < 20%: chase (handled below via has_line_of_sight).
            }

            // ---- adjacent → attack ----
            if manhattan(ex as isize, ey as isize, pcx, pcy) == 1 {
                // Skip if this enemy already acted this turn (retaliated or blocked).
                if acted.contains(&(ex, ey)) {
                    // Still let it patrol/move if applicable.
                } else {
                    if is_hallucination {
                        self.sanity = self.sanity.saturating_sub(5);
                        self.set_message("A hallucination claws at your mind!");
                        self.flash_color = 0xFF_8833CC;
                        self.flash_alpha = 0.35;
                    } else {
                        let damage = match &entity {
                            Entity::Enemy { damage, .. } => *damage,
                            _ => 1,
                        };
                        self.hp = self.hp.saturating_sub(damage);
                        self.set_message(&format!("An enemy strikes you for {} damage!", damage));
                        self.flash_color = 0xFF_CC3333;
                        self.flash_alpha = 0.4;
                        if self.hp == 0 {
                            self.state = GameState::GameOver;
                            return false;
                        }
                    }
                    continue;
                }
            }

            // ---- line-of-sight → move toward player ----
            let has_los = self.has_line_of_sight(ex, ey, px, py);

            if has_los {
                // Real enemies always chase; hallucinations chase only at depth 7+ and sanity < 20%.
                if !is_hallucination {
                    self.try_move_enemy_toward(ex, ey, &mut occupied);
                    continue;
                } else if self.depth >= 7 && self.sanity < 20 {
                    self.try_move_enemy_toward(ex, ey, &mut occupied);
                    continue;
                }
            }

            // ---- patrol ----
            if is_patrol_turn {
                self.try_patrol_enemy(ex, ey, &mut occupied);
            }
        }

        !self.enemy_moves.is_empty()
    }

    /// After enemy animation completes, place entities in their target cells.
    fn apply_enemy_moves(&mut self) {
        for m in self.enemy_moves.drain(..) {
            let idx = m.to_y * self.maze.width() + m.to_x;
            self.maze.entities[idx] = Some(m.entity);
        }
    }

    /// Interpolation offset for an enemy during movement animation.
    /// Returns (dx, dy) in world units; (0, 0) when not animating.
    #[allow(dead_code)]
    pub fn enemy_offset(&self, cell_x: usize, cell_y: usize) -> (f64, f64) {
        if self.state != GameState::AnimatingEnemies {
            return (0.0, 0.0);
        }
        for m in &self.enemy_moves {
            if m.from_x == cell_x && m.from_y == cell_y {
                let t = smoothstep((self.enemy_anim_t / ENEMY_ANIM_DURATION).min(1.0));
                return (
                    (m.to_x as f64 - m.from_x as f64) * t,
                    (m.to_y as f64 - m.from_y as f64) * t,
                );
            }
        }
        (0.0, 0.0)
    }

    /// Entities that should be rendered during enemy animation.
    /// Returns (world_x, world_y, entity) for mid-air enemies.
    pub fn enemy_render_entities(&self) -> Vec<(f64, f64, Entity)> {
        self.enemy_moves
            .iter()
            .map(|m| {
                let t = smoothstep((self.enemy_anim_t / ENEMY_ANIM_DURATION).min(1.0));
                let wx = m.from_x as f64 + 0.5 + (m.to_x as f64 - m.from_x as f64) * t;
                let wy = m.from_y as f64 + 0.5 + (m.to_y as f64 - m.from_y as f64) * t;
                (wx, wy, m.entity.clone())
            })
            .collect()
    }

    fn facing_delta(&self) -> (isize, isize) {
        let q = (self.player.angle / std::f64::consts::FRAC_PI_2).round() as i32 & 3;
        match q {
            0 => (1, 0),  // east
            1 => (0, 1),  // south
            2 => (-1, 0), // west
            _ => (0, -1), // north
        }
    }

    /// The cell coordinate directly ahead of the player.
    pub fn facing_cell(&self) -> (isize, isize) {
        let (dx, dy) = self.facing_delta();
        let cx = self.player.x.floor() as isize;
        let cy = self.player.y.floor() as isize;
        (cx + dx, cy + dy)
    }

    // ---- misc -------------------------------------------------------------

    /// True when the player is standing on the exit staircase.
    pub fn on_exit(&self) -> bool {
        self.maze.is_exit(self.player.x, self.player.y)
    }

    /// Descend to the next dungeon depth.  Generates a new maze, places the
    /// player in a starting room facing east.  All stats, inventory, and
    /// weapon carry over.
    pub fn descend(&mut self) {
        self.depth += 1;
        let mut rng = rand::rng();
        let (maze, (start_x, start_y)) = Maze::generate(self.depth, &mut rng);
        self.maze = maze;
        self.player = Player::new(start_x, start_y, 0.0); // facing east
        self.wall_texture = crate::texture::generate_wall_texture(&mut rng);
        self.floor_texture = crate::texture::generate_floor_texture(&mut rng);
        self.exit_texture = crate::texture::generate_exit_texture(&mut rng);
        self.state = GameState::WaitingForInput;
        self.moving = false;
        self.turning = false;
        self.attacking = false;
        self.enemy_moves.clear();
        self.acted_this_turn.clear();
        self.frame_counter = 0;
        self.set_message(&format!("You descend to depth {}...", self.depth));
    }

    // ---- horror effects ---------------------------------------------------

    /// Phantom wall probability based on current sanity.
    fn phantom_chance(&self) -> f64 {
        match self.sanity {
            80..=100 => 0.0,
            60..=79 => 0.05,
            40..=59 => 0.10,
            20..=39 => 0.15,
            _ => 0.20,
        }
    }

    /// Simple deterministic hash for phantom effect placement.
    fn phantom_hash(&self, x: usize, y: usize) -> u64 {
        let h = (x as u64)
            .wrapping_mul(0x9e3779b9)
            .wrapping_add((y as u64).wrapping_mul(0x517cc1b727220a95))
            .wrapping_add(self.frame_counter);
        (h ^ (h >> 33)).wrapping_mul(0xc6a4a7935bd1e995)
    }

    /// True if this passage cell should render as a wall (phantom wall).
    pub fn is_phantom_wall(&self, x: usize, y: usize) -> bool {
        let chance = self.phantom_chance();
        if chance <= 0.0 {
            return false;
        }
        // Only applies to passages — walls are already walls.
        if self.maze.is_wall(y, x) {
            return false;
        }
        (self.phantom_hash(x, y) % 1000) < (chance * 1000.0) as u64
    }

    /// True if this wall cell should render as a passage (phantom passage).
    pub fn is_phantom_passage(&self, x: usize, y: usize) -> bool {
        let chance = self.phantom_chance();
        if chance <= 0.0 {
            return false;
        }
        // Only applies to walls — passages are already passages.
        if !self.maze.is_wall(y, x) {
            return false;
        }
        // Never make the cell the player is standing in a phantom passage.
        let px = self.player.x.floor() as usize;
        let py = self.player.y.floor() as usize;
        if x == px && y == py {
            return false;
        }
        (self.phantom_hash(x, y) % 1000) < (chance * 1000.0) as u64
    }

    /// Depth darkness factor: 0.0 at depth 1, up to 0.8 at depth 15+.
    pub fn depth_darkness_factor(&self) -> f64 {
        ((self.depth as f64 - 1.0).min(14.0) / 14.0) * 0.8
    }

    /// Combined darkness factor: weakness × depth, 0..2 range.
    pub fn darkness_factor(&self) -> f64 {
        self.weakness_factor() + self.depth_darkness_factor()
    }

    /// Sanity-based colour drift angle (radians) for hue-rotation effect.
    pub fn color_drift(&self) -> f64 {
        if self.sanity >= 80 {
            return 0.0;
        }
        let t = (80.0 - self.sanity as f64) / 80.0; // 0..1 as sanity drops
        let wave = (self.frame_counter as f64 * 0.02).sin() * 0.5 + 0.5;
        t * wave * 0.08 // max ~0.08 rad hue rotation
    }

    /// Wall-breathing X offset for texture sampling (subtle wave).
    pub fn wall_breathing(&self) -> f64 {
        if self.sanity >= 80 {
            return 0.0;
        }
        let t = (80.0 - self.sanity as f64) / 80.0;
        (self.frame_counter as f64 * 0.03).sin() * t * 3.0 // ±3 texels at worst
    }

    /// Upgrade all hallucinations to persistent with extra HP when sanity < 20%.
    fn upgrade_hallucinations(&mut self) {
        if self.sanity >= 20 {
            return;
        }
        for y in 0..self.maze.height() {
            for x in 0..self.maze.width() {
                if let Some(Entity::Hallucination { persistent, hp }) =
                    self.maze.entity_at_mut(x, y)
                {
                    if !*persistent {
                        *persistent = true;
                        *hp = 3; // takes multiple attacks to dissipate
                    }
                }
            }
        }
    }

    /// Shifting maze: flip 1-3 random wall cells outside player FOV.
    /// Called during turn resolution.
    fn shift_maze(&mut self) {
        // Depth 1–3: no shifting.
        if self.depth <= 3 {
            return;
        }
        // Chance based on sanity.
        let chance = match self.sanity {
            40..=59 => 0.05,
            20..=39 => 0.10,
            _ if self.sanity < 20 => 0.15,
            _ => return,
        };
        let mut rng = rand::rng();
        if !rng.random_bool(chance) {
            return;
        }

        let w = self.maze.width();
        let h = self.maze.height();
        let px = self.player.x.floor() as isize;
        let py = self.player.y.floor() as isize;
        let ex = self.maze.exit_x as isize;
        let ey = self.maze.exit_y as isize;

        // Candidates: wall cells at least 6 tiles from player (Chebyshev).
        let mut candidates: Vec<(usize, usize)> = Vec::new();
        for y in 1..h - 1 {
            for x in 1..w - 1 {
                // Only wall cells, not the exit.
                if !self.maze.is_wall(y, x) {
                    continue;
                }
                if x == self.maze.exit_x && y == self.maze.exit_y {
                    continue;
                }
                // At least 6 tiles away from player.
                let dx = (x as isize - px).abs();
                let dy = (y as isize - py).abs();
                if dx.max(dy) < 6 {
                    continue;
                }
                candidates.push((x, y));
            }
        }

        if candidates.is_empty() {
            return;
        }

        let flips = rng.random_range(1..=3).min(candidates.len());
        shuffle_slice(&mut candidates, &mut rng);

        for i in 0..flips {
            let (x, y) = candidates[i];
            // Flip wall → passage (or passage → wall, but we only collected walls).
            let idx = y * w + x;
            self.maze.cells[idx] = Cell::Passage;

            // Validate: can the player still reach the exit?
            if !self.path_exists((px as usize, py as usize), (ex as usize, ey as usize)) {
                // Revert.
                self.maze.cells[idx] = Cell::Wall;
            }
        }
    }

    /// BFS: is there a path of passage cells from `from` to `to`?
    fn path_exists(&self, from: (usize, usize), to: (usize, usize)) -> bool {
        let w = self.maze.width();
        let h = self.maze.height();
        let mut visited = vec![false; w * h];
        let mut queue = std::collections::VecDeque::new();
        queue.push_back(from);
        visited[from.1 * w + from.0] = true;

        let dirs: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];

        while let Some((cx, cy)) = queue.pop_front() {
            if cx == to.0 && cy == to.1 {
                return true;
            }
            for (dx, dy) in dirs {
                let nx = cx as isize + dx;
                let ny = cy as isize + dy;
                if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize {
                    continue;
                }
                let nx = nx as usize;
                let ny = ny as usize;
                if visited[ny * w + nx] {
                    continue;
                }
                if self.maze.is_wall(ny, nx) {
                    continue;
                }
                visited[ny * w + nx] = true;
                queue.push_back((nx, ny));
            }
        }
        false
    }

    /// Whole heartbeats elapsed (displayed in HUD).
    pub fn heartbeats(&self) -> usize {
        self.heartbeat_count as usize
    }

    /// Vertical camera bob (pixels) during tile-walk animation.
    pub fn camera_bob(&self) -> f64 {
        if self.moving {
            (self.move_t * 2.0 * std::f64::consts::PI).sin() * 3.0
        } else {
            0.0
        }
    }

    /// Weakness as a 0..2 factor for the renderer's darkness formula.
    pub fn weakness_factor(&self) -> f64 {
        (self.weakness as f64 / MAX_WEAKNESS as f64) * 2.0
    }

    /// Compute the final score.
    pub fn score(&self) -> u64 {
        (self.kills * 100) + (self.depth.pow(2) * 50) + (self.weapon_base_damage as u64 * 500)
    }
}