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
|
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
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,
// ---- 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,
}
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,
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,
}
}
// ---- 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 {
// 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 {
self.state = GameState::ResolvingTurn;
self.resolve_turn();
self.state = GameState::WaitingForInput;
return true;
}
false
}
GameState::AnimatingEnemies => {
self.enemy_anim_t += dt;
if self.enemy_anim_t >= ENEMY_ANIM_DURATION {
self.enemy_anim_t = 0.0;
self.state = GameState::ResolvingTurn;
self.resolve_turn();
self.state = GameState::WaitingForInput;
return true;
}
false
}
_ => 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.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));
} 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.set_message(&format!(
"You hit the enemy for {} dmg. It strikes back!",
total_dmg
));
if self.hp == 0 {
self.state = GameState::GameOver;
}
}
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) {
self.state = GameState::ResolvingTurn;
self.resolve_turn();
self.state = GameState::WaitingForInput;
}
/// Apply all per-turn effects (weakness, heartbeat, HP drain, message decay).
fn resolve_turn(&mut self) {
// Weakness grows every 3 turns, not every turn.
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;
}
}
}
/// Skip the player's turn (C key). Enemies still act.
pub fn skip_turn(&mut self) {
if !self.can_act() {
return;
}
self.state = GameState::AnimatingEnemies;
self.enemy_anim_t = 0.0;
// TODO Phase 7: enemy movement happens here
}
/// 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}.
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 -------------------------------------------------------------
pub fn check_win(&self) -> bool {
self.maze.is_exit(self.player.x, self.player.y)
}
/// 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
}
}
|