microgames 0.1.0

no_std microgame business logic: plug in events, input, and output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Minesweeper business logic.
//!
//! This module owns mine placement, first-click safety, reveal flood fill,
//! flagging, chording, win/loss state, and event callbacks.

use core::cmp::min;

use crate::RandomSource;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConfigError {
    EmptyBoard,
    TooManyMines,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Config {
    pub mine_count: usize,
    pub first_reveal_safe: bool,
}

impl Config {
    pub const fn new(mine_count: usize) -> Self {
        Self {
            mine_count,
            first_reveal_safe: true,
        }
    }

    pub const fn with_first_reveal_safe(mut self, first_reveal_safe: bool) -> Self {
        self.first_reveal_safe = first_reveal_safe;
        self
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::new(10)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GameState {
    Ready,
    Playing,
    Won,
    Lost,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ActionOutcome {
    pub changed: bool,
    pub revealed_cells: usize,
    pub state: GameState,
}

impl ActionOutcome {
    const fn unchanged(state: GameState) -> Self {
        Self {
            changed: false,
            revealed_cells: 0,
            state,
        }
    }

    const fn changed(state: GameState, revealed_cells: usize) -> Self {
        Self {
            changed: true,
            revealed_cells,
            state,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CellView {
    pub is_mine: bool,
    pub adjacent_mines: u8,
    pub is_revealed: bool,
    pub is_flagged: bool,
    pub exploded: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Cell {
    is_mine: bool,
    adjacent_mines: u8,
    is_revealed: bool,
    is_flagged: bool,
}

impl Cell {
    const fn new() -> Self {
        Self {
            is_mine: false,
            adjacent_mines: 0,
            is_revealed: false,
            is_flagged: false,
        }
    }
}

pub trait MinesweeperEvents {
    fn on_game_started(&mut self) {}
    fn on_cell_revealed(&mut self, _x: usize, _y: usize, _adjacent_mines: u8) {}
    fn on_flag_toggled(&mut self, _x: usize, _y: usize, _is_flagged: bool) {}
    fn on_mine_triggered(&mut self, _x: usize, _y: usize) {}
    fn on_game_won(&mut self) {}
    fn on_game_lost(&mut self) {}
}

pub struct NoopEvents;

impl MinesweeperEvents for NoopEvents {}

#[derive(Clone)]
pub struct Game<const W: usize, const H: usize>
where
    [(); W]:,
    [(); H]:,
{
    board: [[Cell; H]; W],
    config: Config,
    state: GameState,
    changed: bool,
    mines_placed: bool,
    revealed_safe_cells: usize,
    flags_used: usize,
    exploded_cell: Option<(usize, usize)>,
}

impl<const W: usize, const H: usize> Game<W, H>
where
    [(); W]:,
    [(); H]:,
{
    pub fn new(config: Config) -> Result<Self, ConfigError> {
        if W == 0 || H == 0 {
            return Err(ConfigError::EmptyBoard);
        }

        let cell_count = W * H;
        let reserved_safe_cells = config.first_reveal_safe as usize;
        if config.mine_count > cell_count.saturating_sub(reserved_safe_cells) {
            return Err(ConfigError::TooManyMines);
        }

        Ok(Self {
            board: [[Cell::new(); H]; W],
            config,
            state: GameState::Ready,
            changed: true,
            mines_placed: false,
            revealed_safe_cells: 0,
            flags_used: 0,
            exploded_cell: None,
        })
    }

    pub const fn width(&self) -> usize {
        W
    }

    pub const fn height(&self) -> usize {
        H
    }

    pub const fn total_cells(&self) -> usize {
        W * H
    }

    pub const fn mine_count(&self) -> usize {
        self.config.mine_count
    }

    pub const fn state(&self) -> GameState {
        self.state
    }

    pub fn has_changed(&self) -> bool {
        self.changed
    }

    pub fn consume_changed(&mut self) -> bool {
        let changed = self.changed;
        self.changed = false;
        changed
    }

    pub fn mines_placed(&self) -> bool {
        self.mines_placed
    }

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

    pub fn remaining_mines_hint(&self) -> usize {
        self.config.mine_count.saturating_sub(self.flags_used)
    }

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

    pub fn exploded_cell(&self) -> Option<(usize, usize)> {
        self.exploded_cell
    }

    pub fn reset(&mut self) {
        self.board = [[Cell::new(); H]; W];
        self.state = GameState::Ready;
        self.changed = true;
        self.mines_placed = false;
        self.revealed_safe_cells = 0;
        self.flags_used = 0;
        self.exploded_cell = None;
    }

    pub fn cell_view_at(&self, x: usize, y: usize) -> Option<CellView> {
        if x >= W || y >= H {
            return None;
        }

        let cell = self.board[x][y];
        Some(CellView {
            is_mine: cell.is_mine,
            adjacent_mines: cell.adjacent_mines,
            is_revealed: cell.is_revealed,
            is_flagged: cell.is_flagged,
            exploded: self.exploded_cell == Some((x, y)),
        })
    }

    pub fn toggle_flag<T: MinesweeperEvents>(
        &mut self,
        x: usize,
        y: usize,
        events: &mut T,
    ) -> ActionOutcome {
        if x >= W || y >= H || matches!(self.state, GameState::Won | GameState::Lost) {
            return ActionOutcome::unchanged(self.state);
        }

        let cell = &mut self.board[x][y];
        if cell.is_revealed {
            return ActionOutcome::unchanged(self.state);
        }

        cell.is_flagged = !cell.is_flagged;
        if cell.is_flagged {
            self.flags_used = self.flags_used.saturating_add(1);
        } else {
            self.flags_used = self.flags_used.saturating_sub(1);
        }

        self.changed = true;
        events.on_flag_toggled(x, y, cell.is_flagged);
        ActionOutcome::changed(self.state, 0)
    }

    pub fn reveal<R: RandomSource, T: MinesweeperEvents>(
        &mut self,
        x: usize,
        y: usize,
        rng: &mut R,
        events: &mut T,
    ) -> ActionOutcome {
        if x >= W || y >= H || matches!(self.state, GameState::Won | GameState::Lost) {
            return ActionOutcome::unchanged(self.state);
        }

        if self.board[x][y].is_flagged || self.board[x][y].is_revealed {
            return ActionOutcome::unchanged(self.state);
        }

        if !self.mines_placed {
            self.place_mines(x, y, rng, events);
        }

        if self.board[x][y].is_mine {
            self.explode_at(x, y, events);
            return ActionOutcome::changed(self.state, 0);
        }

        let revealed_cells = self.reveal_safe_region_from(x, y, events);
        self.finish_win_if_needed(events);

        if revealed_cells == 0 {
            ActionOutcome::unchanged(self.state)
        } else {
            ActionOutcome::changed(self.state, revealed_cells)
        }
    }

    pub fn chord<T: MinesweeperEvents>(
        &mut self,
        x: usize,
        y: usize,
        events: &mut T,
    ) -> ActionOutcome {
        if x >= W || y >= H || !self.mines_placed || !matches!(self.state, GameState::Playing) {
            return ActionOutcome::unchanged(self.state);
        }

        let cell = self.board[x][y];
        if !cell.is_revealed || cell.adjacent_mines == 0 {
            return ActionOutcome::unchanged(self.state);
        }

        if self.flagged_neighbors(x, y) != cell.adjacent_mines as usize {
            return ActionOutcome::unchanged(self.state);
        }

        let mut revealed_cells = 0;
        for neighbor_y in y.saturating_sub(1)..=min(y.saturating_add(1), H.saturating_sub(1)) {
            for neighbor_x in x.saturating_sub(1)..=min(x.saturating_add(1), W.saturating_sub(1)) {
                if neighbor_x == x && neighbor_y == y {
                    continue;
                }

                let neighbor = self.board[neighbor_x][neighbor_y];
                if neighbor.is_revealed || neighbor.is_flagged {
                    continue;
                }

                if neighbor.is_mine {
                    self.explode_at(neighbor_x, neighbor_y, events);
                    return ActionOutcome::changed(self.state, revealed_cells);
                }

                revealed_cells += self.reveal_safe_region_from(neighbor_x, neighbor_y, events);
            }
        }

        if revealed_cells == 0 {
            return ActionOutcome::unchanged(self.state);
        }

        self.finish_win_if_needed(events);
        ActionOutcome::changed(self.state, revealed_cells)
    }

    fn place_mines<R: RandomSource, T: MinesweeperEvents>(
        &mut self,
        safe_x: usize,
        safe_y: usize,
        rng: &mut R,
        events: &mut T,
    ) {
        let mut remaining_mines = self.config.mine_count;
        let mut remaining_slots = self.total_cells() - self.config.first_reveal_safe as usize;

        for y in 0..H {
            for x in 0..W {
                if self.config.first_reveal_safe && x == safe_x && y == safe_y {
                    continue;
                }

                if remaining_slots == 0 {
                    continue;
                }

                let roll = (rng.next_u32() as usize) % remaining_slots;
                if roll < remaining_mines {
                    self.board[x][y].is_mine = true;
                    remaining_mines -= 1;
                }
                remaining_slots -= 1;
            }
        }

        self.compute_adjacency();
        self.mines_placed = true;
        self.state = GameState::Playing;
        self.changed = true;
        events.on_game_started();
    }

    fn compute_adjacency(&mut self) {
        for y in 0..H {
            for x in 0..W {
                let mut adjacent_mines = 0_u8;
                for neighbor_y in
                    y.saturating_sub(1)..=min(y.saturating_add(1), H.saturating_sub(1))
                {
                    for neighbor_x in
                        x.saturating_sub(1)..=min(x.saturating_add(1), W.saturating_sub(1))
                    {
                        if neighbor_x == x && neighbor_y == y {
                            continue;
                        }

                        if self.board[neighbor_x][neighbor_y].is_mine {
                            adjacent_mines = adjacent_mines.saturating_add(1);
                        }
                    }
                }
                self.board[x][y].adjacent_mines = adjacent_mines;
            }
        }
    }

    fn reveal_safe_region_from<T: MinesweeperEvents>(
        &mut self,
        x: usize,
        y: usize,
        events: &mut T,
    ) -> usize {
        let mut revealed_cells = self.reveal_safe_cell(x, y, events);
        if revealed_cells == 0 || self.board[x][y].adjacent_mines != 0 {
            return revealed_cells;
        }

        let mut expanded = true;
        while expanded {
            expanded = false;
            for scan_y in 0..H {
                for scan_x in 0..W {
                    let scan = self.board[scan_x][scan_y];
                    if !scan.is_revealed || scan.is_mine || scan.adjacent_mines != 0 {
                        continue;
                    }

                    for neighbor_y in scan_y.saturating_sub(1)
                        ..=min(scan_y.saturating_add(1), H.saturating_sub(1))
                    {
                        for neighbor_x in scan_x.saturating_sub(1)
                            ..=min(scan_x.saturating_add(1), W.saturating_sub(1))
                        {
                            let newly_revealed =
                                self.reveal_safe_cell(neighbor_x, neighbor_y, events);
                            revealed_cells += newly_revealed;
                            if newly_revealed != 0 {
                                expanded = true;
                            }
                        }
                    }
                }
            }
        }

        revealed_cells
    }

    fn reveal_safe_cell<T: MinesweeperEvents>(
        &mut self,
        x: usize,
        y: usize,
        events: &mut T,
    ) -> usize {
        let cell = &mut self.board[x][y];
        if cell.is_revealed || cell.is_flagged || cell.is_mine {
            return 0;
        }

        cell.is_revealed = true;
        self.revealed_safe_cells = self.revealed_safe_cells.saturating_add(1);
        self.changed = true;
        events.on_cell_revealed(x, y, cell.adjacent_mines);
        1
    }

    fn flagged_neighbors(&self, x: usize, y: usize) -> usize {
        let mut flagged = 0_usize;
        for neighbor_y in y.saturating_sub(1)..=min(y.saturating_add(1), H.saturating_sub(1)) {
            for neighbor_x in x.saturating_sub(1)..=min(x.saturating_add(1), W.saturating_sub(1)) {
                if neighbor_x == x && neighbor_y == y {
                    continue;
                }

                if self.board[neighbor_x][neighbor_y].is_flagged {
                    flagged += 1;
                }
            }
        }
        flagged
    }

    fn explode_at<T: MinesweeperEvents>(&mut self, x: usize, y: usize, events: &mut T) {
        self.board[x][y].is_revealed = true;
        self.exploded_cell = Some((x, y));
        self.state = GameState::Lost;
        self.changed = true;
        events.on_mine_triggered(x, y);
        events.on_game_lost();
    }

    fn finish_win_if_needed<T: MinesweeperEvents>(&mut self, events: &mut T) {
        let safe_cells = self.total_cells().saturating_sub(self.config.mine_count);
        if matches!(self.state, GameState::Playing) && self.revealed_safe_cells >= safe_cells {
            self.state = GameState::Won;
            self.changed = true;
            events.on_game_won();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Config, Game, GameState, MinesweeperEvents};
    use crate::RandomSource;

    #[derive(Clone, Copy)]
    struct FixedRng(u32);

    impl RandomSource for FixedRng {
        fn next_u32(&mut self) -> u32 {
            self.0
        }
    }

    #[derive(Default)]
    struct TestEvents {
        started: usize,
        revealed: usize,
        won: usize,
        lost: usize,
        mines: usize,
    }

    impl MinesweeperEvents for TestEvents {
        fn on_game_started(&mut self) {
            self.started += 1;
        }

        fn on_cell_revealed(&mut self, _x: usize, _y: usize, _adjacent_mines: u8) {
            self.revealed += 1;
        }

        fn on_mine_triggered(&mut self, _x: usize, _y: usize) {
            self.mines += 1;
        }

        fn on_game_won(&mut self) {
            self.won += 1;
        }

        fn on_game_lost(&mut self) {
            self.lost += 1;
        }
    }

    #[test]
    fn first_reveal_is_safe() {
        let mut game = Game::<2, 2>::new(Config::new(3)).unwrap();
        let mut rng = FixedRng(0);
        let mut events = TestEvents::default();

        let outcome = game.reveal(0, 0, &mut rng, &mut events);

        assert_eq!(outcome.state, GameState::Won);
        assert_eq!(outcome.revealed_cells, 1);
        assert!(game.cell_view_at(0, 0).unwrap().is_revealed);
        assert!(!game.cell_view_at(0, 0).unwrap().is_mine);
        assert_eq!(events.started, 1);
        assert_eq!(events.won, 1);
    }

    #[test]
    fn zero_mines_reveal_clears_board() {
        let mut game = Game::<3, 3>::new(Config::new(0)).unwrap();
        let mut rng = FixedRng(0);
        let mut events = TestEvents::default();

        let outcome = game.reveal(1, 1, &mut rng, &mut events);

        assert_eq!(outcome.state, GameState::Won);
        assert_eq!(outcome.revealed_cells, 9);
        assert_eq!(game.revealed_safe_cells(), 9);
        assert_eq!(events.revealed, 9);
    }

    #[test]
    fn can_lose_without_first_click_protection() {
        let config = Config::new(1).with_first_reveal_safe(false);
        let mut game = Game::<1, 1>::new(config).unwrap();
        let mut rng = FixedRng(0);
        let mut events = TestEvents::default();

        let outcome = game.reveal(0, 0, &mut rng, &mut events);

        assert_eq!(outcome.state, GameState::Lost);
        assert_eq!(events.lost, 1);
        assert_eq!(events.mines, 1);
    }

    #[test]
    fn toggling_flags_updates_hint() {
        let mut game = Game::<4, 4>::new(Config::new(3)).unwrap();
        let mut events = TestEvents::default();

        let flagged = game.toggle_flag(1, 1, &mut events);
        assert!(flagged.changed);
        assert_eq!(game.flags_used(), 1);
        assert_eq!(game.remaining_mines_hint(), 2);

        let unflagged = game.toggle_flag(1, 1, &mut events);
        assert!(unflagged.changed);
        assert_eq!(game.flags_used(), 0);
        assert_eq!(game.remaining_mines_hint(), 3);
    }
}