core_pb/grid/
computed_grid.rs

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
use crate::grid::standard_grid::{StandardGrid, GRID_OPEN};
use crate::grid::{Grid, GRID_SIZE};
use nalgebra::Point2;
use ordered_float::OrderedFloat;
use pacbot_rs::location::Direction;
use pacbot_rs::location::Direction::*;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};

/// Validates a [`Grid`].
///
/// A valid [`Grid`] must satisfy the following conditions:
/// - The edges of the grid must all be walls.
/// - There must be no 2x2 walkable squares.
/// - There must be at least one walkable space.
/// - No wall should have a walkable cell either both above and below or both to the left and right
fn validate_grid(grid: &Grid) -> Result<(), String> {
    if *grid == GRID_OPEN {
        return Ok(());
    }

    // the edges of the grid should all be walls
    if (0..GRID_SIZE).any(|row| !grid[row][0]) {
        return Err("Left edge of grid is not all walls".to_string());
    }
    if (0..GRID_SIZE).any(|row| !grid[row][GRID_SIZE - 1]) {
        return Err("Right edge of grid is not all walls".to_string());
    }
    if (0..GRID_SIZE).any(|col| !grid[0][col]) {
        return Err("Top edge of grid is not all walls".to_string());
    }
    if (0..GRID_SIZE).any(|col| !grid[GRID_SIZE - 1][col]) {
        return Err("Bottom edge of grid is not all walls".to_string());
    }

    // there should be no 2x2 walkable squares
    for row in 0..GRID_SIZE - 1 {
        for col in 0..GRID_SIZE - 1 {
            if !grid[row][col]
                && !grid[row][col + 1]
                && !grid[row + 1][col]
                && !grid[row + 1][col + 1]
            {
                return Err(format!("2x2 walkable square at ({}, {})", row, col));
            }
        }
    }

    // there should be at least one walkable space
    if grid.iter().all(|row| row.iter().all(|wall| *wall)) {
        return Err("No walkable spaces".to_string());
    }

    // no wall should have a walkable cell either both above and below or both to the left and right
    for row in 1..GRID_SIZE - 1 {
        for col in 1..GRID_SIZE - 1 {
            if grid[row][col] {
                if !grid[row - 1][col] && !grid[row + 1][col] {
                    return Err(format!(
                        "Wall at ({}, {}) has walkable cells both above and below",
                        row, col
                    ));
                }
                if !grid[row][col - 1] && !grid[row][col + 1] {
                    return Err(format!(
                        "Wall at ({}, {}) has walkable cells both to the left and right",
                        row, col
                    ));
                }
            }
        }
    }

    Ok(())
}

/// A rectangle representing a wall.
///
/// The rectangle is defined by the top left corner and the bottom right corner.
/// Note that [`Wall`] does not follow the same grid conventions as [`Grid`].
/// The coordinates are intended to be +0.5, and may be negative.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Wall {
    /// The top left corner of the [`Wall`].
    pub top_left: Point2<i8>,
    /// The bottom right corner of the [`Wall`].
    pub bottom_right: Point2<i8>,
}

/// A [`Grid`] with precomputed data for faster pathfinding.
///
/// This struct is created by [`ComputedGrid::try_from`].
///
/// # Examples
///
/// ```
/// use core_pb::grid::standard_grid::StandardGrid;
///
/// let grid = StandardGrid::Blank.compute_grid();
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComputedGrid {
    grid: Grid,
    standard_grid: Option<StandardGrid>,

    walkable_nodes: Vec<Point2<i8>>,
    coords_to_node: HashMap<Point2<i8>, usize>,

    /// walkable, right, left, up, down
    valid_actions: Vec<[bool; 5]>,
    /// note that all walkable nodes might not be reachable from each other
    distance_matrix: Vec<Vec<Option<u8>>>,

    /// walls represent rectangles with top left corner at the specified point
    walls: Vec<Wall>,
}

impl Default for ComputedGrid {
    fn default() -> Self {
        StandardGrid::Pacman.compute_grid()
    }
}

impl From<StandardGrid> for ComputedGrid {
    fn from(value: StandardGrid) -> Self {
        let mut s = Self::try_from(value.get_grid()).expect("Failed to compute a StandardGrid");
        s.standard_grid = Some(value);
        s
    }
}

impl TryFrom<Grid> for ComputedGrid {
    type Error = String;

    fn try_from(grid: Grid) -> Result<Self, Self::Error> {
        if grid == GRID_OPEN {
            return Ok(Self::compute_open_grid());
        }
        validate_grid(&grid)?;

        let mut walkable_nodes = vec![];
        let mut coords_to_node: HashMap<Point2<i8>, usize> = HashMap::new();

        let mut valid_actions = vec![];
        let mut distance_matrix = vec![];

        // note that all edges must be walls
        // iterate through all grid positions
        for row in 1..GRID_SIZE - 1 {
            for col in 1..GRID_SIZE - 1 {
                let pos = Point2::new(row as i8, col as i8);
                if !grid[row][col] {
                    // remember walkable nodes
                    let node_index = walkable_nodes.len();
                    walkable_nodes.push(pos);
                    coords_to_node.insert(pos, node_index);
                    // quick lookup for whether a node is walkable in a given direction
                    valid_actions.push([
                        true,
                        !grid[row - 1][col],
                        !grid[row][col - 1],
                        !grid[row + 1][col],
                        !grid[row][col + 1],
                    ]);
                }
            }
        }

        // initialize distance matrix
        for _ in 0..walkable_nodes.len() {
            distance_matrix.push(vec![None; walkable_nodes.len()]);
        }

        // initialize ComputedGrid
        let mut s = ComputedGrid {
            grid,
            standard_grid: None,
            walkable_nodes,
            coords_to_node,
            valid_actions,
            distance_matrix,
            walls: Vec::new(),
        };

        // compute distance matrix with BFS
        for (i, &start) in s.walkable_nodes.iter().enumerate() {
            let mut visited = vec![false; s.walkable_nodes.len()];
            let mut queue = vec![(start, 0)];
            while let Some((pos, dist)) = queue.pop() {
                // only walkable nodes are added to the queue
                let node_index = *s.coords_to_node.get(&pos).unwrap();
                if visited[node_index] {
                    continue;
                }
                visited[node_index] = true;
                s.distance_matrix[i][node_index] = Some(dist);
                for neighbor in s.neighbors(&pos) {
                    queue.push((neighbor, dist + 1));
                }
            }
        }

        fn is_wall(g: &ComputedGrid, p: &Point2<i8>) -> bool {
            let parts = [
                Point2::new(p.x, p.y),
                Point2::new(p.x + 1, p.y),
                Point2::new(p.x, p.y + 1),
                Point2::new(p.x + 1, p.y + 1),
            ];
            parts.iter().all(|part| {
                if part.x < 0 || part.y < 0 {
                    true
                } else {
                    g.wall_at(part)
                }
            })
        }

        fn is_part_of_wall(g: &ComputedGrid, p: &Point2<i8>) -> bool {
            for wall in &g.walls {
                if p.x >= wall.top_left.x
                    && p.y >= wall.top_left.y
                    && p.x < wall.bottom_right.x
                    && p.y < wall.bottom_right.y
                {
                    return true;
                }
            }
            false
        }

        let mut row = -1;
        let mut col = -1;
        loop {
            // make sure this point isn't already a part of a wall
            let is_already_wall = is_part_of_wall(&s, &Point2::new(row, col));
            // compute walls - first, add each cell individually
            if !is_already_wall && is_wall(&s, &Point2::new(row, col)) {
                let mut wall = Wall {
                    top_left: Point2::new(row, col),
                    bottom_right: Point2::new(row + 1, col + 1),
                };

                if wall.top_left.y > GRID_SIZE as i8 {
                    wall.top_left.y = GRID_SIZE as i8;
                }

                col += 1;

                // extend the wall to the right
                while is_wall(&s, &Point2::new(row, col))
                    && !is_part_of_wall(&s, &Point2::new(row, col))
                {
                    if col >= GRID_SIZE as i8 {
                        break;
                    }

                    wall.bottom_right.y += 1;
                    col += 1;
                }

                // Extend the wall down
                let mut next_row = row + 1;
                while next_row < GRID_SIZE as i8 {
                    let mut can_extend = true;
                    for next_col in wall.top_left.y..wall.bottom_right.y {
                        if !is_wall(&s, &Point2::new(next_row, next_col))
                            || is_part_of_wall(&s, &Point2::new(next_row, next_col))
                        {
                            can_extend = false;
                            break;
                        }
                    }
                    if can_extend {
                        wall.bottom_right.x += 1;
                        next_row += 1;
                    } else {
                        break;
                    }
                }

                s.walls.push(wall);
            } else {
                col += 1;
            }

            if col >= GRID_SIZE as i8 {
                col = -1;
                row += 1;

                if row == GRID_SIZE as i8 {
                    break;
                }
            }
        }

        Ok(s)
    }
}

impl ComputedGrid {
    /// Returns the underlying [`Grid`].
    ///
    /// # Examples
    ///
    /// ```
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Blank.compute_grid();
    ///
    /// assert_eq!(grid.grid()[0][0], true);
    /// ```
    pub fn grid(&self) -> &Grid {
        &self.grid
    }

    /// Returns the underlying [`StandardGrid`], if one was used to construct it.
    pub fn standard_grid(&self) -> &Option<StandardGrid> {
        &self.standard_grid
    }

    /// Returns the positions of all walkable nodes in the grid.
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Blank.compute_grid();
    /// assert_eq!(grid.walkable_nodes()[0], Point2::new(1, 1));
    /// ```
    pub fn walkable_nodes(&self) -> &Vec<Point2<i8>> {
        &self.walkable_nodes
    }

    /// Returns the index of the given position in the walkable_nodes vector, or `None` if the
    /// position is not walkable.
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Blank.compute_grid();
    /// assert_eq!(grid.coords_to_node(&Point2::new(1, 1)), Some(0));
    /// assert_eq!(grid.coords_to_node(&Point2::new(0, 0)), None);
    /// ```
    pub fn coords_to_node(&self, p: &Point2<i8>) -> Option<usize> {
        self.coords_to_node.get(p).copied()
    }

    /// Returns the valid actions for the given position.
    ///
    /// The five values represent:
    /// - whether the node is walkable
    /// - whether the node to the right is walkable
    /// - whether the node to the left is walkable
    /// - whether the node above is walkable
    /// - whether the node below is walkable
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Blank.compute_grid();
    /// assert_eq!(grid.valid_actions(Point2::new(1, 1)), Some([true, false, false, false, false]));
    /// ```
    pub fn valid_actions(&self, p: Point2<i8>) -> Option<[bool; 5]> {
        let node_index = self.coords_to_node.get(&p)?;
        Some(self.valid_actions[*node_index])
    }

    /// Returns whether there is a wall at a given position
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Blank.compute_grid();
    /// assert_eq!(grid.wall_at(&Point2::new(0, 0)), true);
    /// assert_eq!(grid.wall_at(&Point2::new(1, 1)), false);
    /// assert_eq!(grid.wall_at(&Point2::new(32, 32)), true);
    /// ```
    pub fn wall_at(&self, p: &Point2<i8>) -> bool {
        if p.x >= GRID_SIZE as i8 || p.y >= GRID_SIZE as i8 || p.x < 0 || p.y < 0 {
            true
        } else {
            self.grid[p.x as usize][p.y as usize]
        }
    }

    /// Returns the distance between two points, or `None` if the points are not both walkable.
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Pacman.compute_grid();
    /// assert_eq!(grid.dist(&Point2::new(1, 1), &Point2::new(1, 1)), Some(0));
    /// assert_eq!(grid.dist(&Point2::new(1, 1), &Point2::new(1, 2)), Some(1));
    /// ```
    pub fn dist(&self, p1: &Point2<i8>, p2: &Point2<i8>) -> Option<u8> {
        let p1 = self.coords_to_node.get(p1)?;
        let p2 = self.coords_to_node.get(p2)?;
        self.distance_matrix[*p1][*p2]
    }

    /// Returns all the walkable neighbors of the given position.
    ///
    /// # Examples
    ///
    /// ```
    /// use nalgebra::Point2;
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Pacman.compute_grid();
    /// assert!(grid.neighbors(&Point2::new(1, 1)).contains(&Point2::new(1, 2)));
    /// assert!(grid.neighbors(&Point2::new(1, 1)).contains(&Point2::new(2, 1)));
    /// ```
    pub fn neighbors(&self, p: &Point2<i8>) -> Vec<Point2<i8>> {
        let mut neighbors = vec![];
        let mut potential_neighbors = vec![Point2::new(p.x + 1, p.y), Point2::new(p.x, p.y + 1)];
        if p.x > 0 {
            potential_neighbors.push(Point2::new(p.x - 1, p.y));
        }
        if p.y > 0 {
            potential_neighbors.push(Point2::new(p.x, p.y - 1));
        }
        for &neighbor in &potential_neighbors {
            if !self.wall_at(&neighbor) {
                neighbors.push(neighbor);
            }
        }
        neighbors
    }

    /// Returns the [`Wall`]s in the grid.
    ///
    /// # Examples
    ///
    /// ```
    /// use core_pb::grid::standard_grid::StandardGrid;
    ///
    /// let grid = StandardGrid::Pacman.compute_grid();
    /// let walls = grid.walls();
    /// ```
    pub fn walls(&self) -> &Vec<Wall> {
        &self.walls
    }

    /// Return the walkable node from the nodes surrounding this point
    pub fn node_nearest(&self, x: f32, y: f32) -> Option<Point2<i8>> {
        [
            Point2::new(x.floor() as i8, y.floor() as i8),
            Point2::new(x.ceil() as i8, y.floor() as i8),
            Point2::new(x.floor() as i8, y.ceil() as i8),
            Point2::new(x.ceil() as i8, y.ceil() as i8),
        ]
        .into_iter()
        .filter(|&node| !self.wall_at(&node))
        .min_by_key(|&node| {
            let dx = node.x as f32 - x;
            let dy = node.y as f32 - y;
            OrderedFloat::from(dx * dx + dy * dy)
        })
    }

    /// Returns the shortest path, if one exists, from start to finish
    /// The path includes path the start and the finish
    pub fn bfs_path(&self, start: Point2<i8>, finish: Point2<i8>) -> Option<Vec<Point2<i8>>> {
        let mut prev: HashMap<Point2<i8>, Option<Point2<i8>>> = HashMap::new();
        let mut queue: VecDeque<Point2<i8>> = VecDeque::new();
        prev.insert(start, None);
        queue.push_back(start);
        while let Some(current) = queue.pop_front() {
            if current == finish {
                let mut path = vec![finish];
                let mut next = finish;
                while let Some(Some(before_next)) = prev.get(&next) {
                    path.insert(0, *before_next);
                    next = *before_next;
                }
                return Some(path);
            }
            let neighbors = self.neighbors(&current);
            for n in &neighbors {
                if !prev.contains_key(n) {
                    prev.insert(*n, Some(current));
                    queue.push_back(*n);
                }
            }
        }
        None
    }

    fn compute_open_grid() -> Self {
        let mut walkable_nodes = vec![];
        let mut valid_actions = vec![];
        let mut coords_to_node = HashMap::new();
        let mut distance_matrix = vec![];

        let grid = GRID_OPEN;

        for row in 1..GRID_SIZE - 1 {
            for col in 1..GRID_SIZE - 1 {
                let pos = Point2::new(row as i8, col as i8);
                if !grid[row][col] {
                    // remember walkable nodes
                    let node_index = walkable_nodes.len();
                    walkable_nodes.push(pos);
                    coords_to_node.insert(pos, node_index);
                    // quick lookup for whether a node is walkable in a given direction
                    valid_actions.push([
                        true,
                        !grid[row - 1][col],
                        !grid[row][col - 1],
                        !grid[row + 1][col],
                        !grid[row][col + 1],
                    ]);
                }
            }
        }

        // initialize distance matrix
        for _ in 0..walkable_nodes.len() {
            distance_matrix.push(vec![None; walkable_nodes.len()]);
        }

        for (a, first) in walkable_nodes.iter().enumerate() {
            for (b, second) in walkable_nodes.iter().enumerate() {
                if !grid[first.x as usize][first.y as usize]
                    && !grid[second.x as usize][second.y as usize]
                {
                    distance_matrix[a][b] =
                        Some(((first.x - second.x).abs() + (first.y - second.y).abs()) as u8)
                }
            }
        }

        // initialize ComputedGrid
        ComputedGrid {
            grid,
            standard_grid: Some(StandardGrid::Open),
            walkable_nodes,
            coords_to_node,
            valid_actions,
            distance_matrix,
            walls: vec![
                Wall {
                    top_left: Point2::new(-1, -1),
                    bottom_right: Point2::new(32, 0),
                },
                Wall {
                    top_left: Point2::new(-1, 0),
                    bottom_right: Point2::new(0, 32),
                },
                Wall {
                    top_left: Point2::new(0, 31),
                    bottom_right: Point2::new(32, 32),
                },
                Wall {
                    top_left: Point2::new(31, 0),
                    bottom_right: Point2::new(32, 31),
                },
            ],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grid::standard_grid::*;

    #[test]
    fn valid_preset_grids() {
        assert!(validate_grid(&GRID_PACMAN).is_ok());
        assert!(validate_grid(&GRID_BLANK).is_ok());
    }

    #[test]
    fn validation_require_empty_space() {
        let mut grid = GRID_BLANK;
        grid[1][1] = true;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(format!("{}", v.unwrap_err()), "No walkable spaces");
    }

    #[test]
    fn validation_invalid_bottom_wall() {
        let mut grid = GRID_BLANK;
        grid[GRID_SIZE - 1][1] = false;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(
            format!("{}", v.unwrap_err()),
            "Bottom edge of grid is not all walls"
        );
    }

    #[test]
    fn validation_invalid_top_wall() {
        let mut grid = GRID_BLANK;
        grid[0][1] = false;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(
            format!("{}", v.unwrap_err()),
            "Top edge of grid is not all walls"
        );
    }

    #[test]
    fn validation_invalid_left_wall() {
        let mut grid = GRID_BLANK;
        grid[1][0] = false;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(
            format!("{}", v.unwrap_err()),
            "Left edge of grid is not all walls"
        );
    }

    #[test]
    fn validation_invalid_right_wall() {
        let mut grid = GRID_BLANK;
        grid[1][GRID_SIZE - 1] = false;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(
            format!("{}", v.unwrap_err()),
            "Right edge of grid is not all walls"
        );
    }

    #[test]
    fn validation_invalid_2x2() {
        let mut grid = GRID_BLANK;
        grid[1][1] = false;
        grid[1][2] = false;
        grid[2][1] = false;
        grid[2][2] = false;

        let v = validate_grid(&grid);
        assert!(v.is_err());
        assert_eq!(
            format!("{}", v.unwrap_err()),
            "2x2 walkable square at (1, 1)"
        );
    }

    #[test]
    fn compute_preset_grids() {
        StandardGrid::Pacman.compute_grid();
        StandardGrid::Blank.compute_grid();
    }

    #[test]
    fn compute_walkable_nodes() {
        let mut grid = GRID_BLANK;
        grid[1][1] = false;
        grid[1][2] = false;
        grid[6][1] = false;

        let computed_grid = ComputedGrid::try_from(grid).unwrap();
        assert_eq!(computed_grid.walkable_nodes.len(), 3);
        assert!(computed_grid.walkable_nodes.contains(&Point2::new(1, 1)));
        assert!(computed_grid.walkable_nodes.contains(&Point2::new(1, 2)));
        assert!(computed_grid.walkable_nodes.contains(&Point2::new(6, 1)));
    }

    #[test]
    fn compute_coords_to_node() {
        let mut grid = GRID_BLANK;
        grid[1][1] = false;
        grid[1][2] = false;
        grid[6][1] = false;

        let computed_grid = ComputedGrid::try_from(grid).unwrap();
        assert_eq!(computed_grid.coords_to_node.len(), 3);
        let idx = *computed_grid
            .coords_to_node
            .get(&Point2::new(1, 1))
            .unwrap();
        assert_eq!(computed_grid.walkable_nodes[idx], Point2::new(1, 1));
    }

    #[test]
    fn compute_valid_actions() {
        let mut grid = GRID_BLANK;
        grid[1][1] = false;
        grid[1][2] = false;
        grid[6][1] = false;

        let computed_grid = ComputedGrid::try_from(grid).unwrap();
        assert_eq!(computed_grid.valid_actions.len(), 3);
        let one_one_idx = *computed_grid
            .coords_to_node
            .get(&Point2::new(1, 1))
            .unwrap();
        assert_eq!(
            computed_grid.valid_actions[one_one_idx],
            [true, false, false, false, true]
        );

        let one_two_idx = *computed_grid
            .coords_to_node
            .get(&Point2::new(1, 2))
            .unwrap();
        assert_eq!(
            computed_grid.valid_actions[one_two_idx],
            [true, false, true, false, false]
        );

        let six_one_idx = *computed_grid
            .coords_to_node
            .get(&Point2::new(6, 1))
            .unwrap();
        assert_eq!(
            computed_grid.valid_actions[six_one_idx],
            [true, false, false, false, false]
        );
    }

    #[test]
    fn compute_distance_matrix() {
        let mut grid = GRID_BLANK;
        grid[1][1] = false;
        grid[1][2] = false;
        grid[6][1] = false;

        let points = [Point2::new(1, 1), Point2::new(1, 2), Point2::new(6, 1)];

        let computed_grid = ComputedGrid::try_from(grid).unwrap();
        assert_eq!(computed_grid.distance_matrix.len(), 3);
        assert_eq!(computed_grid.distance_matrix[0].len(), 3);
        assert_eq!(computed_grid.distance_matrix[1].len(), 3);
        assert_eq!(computed_grid.distance_matrix[2].len(), 3);
        assert_eq!(computed_grid.dist(&points[0], &points[0]), Some(0));
        assert_eq!(computed_grid.dist(&points[0], &points[1]), Some(1));
        assert_eq!(computed_grid.dist(&points[0], &points[2]), None);
        assert_eq!(computed_grid.dist(&points[1], &points[0]), Some(1));
        assert_eq!(computed_grid.dist(&points[1], &points[1]), Some(0));
        assert_eq!(computed_grid.dist(&points[1], &points[2]), None);
        assert_eq!(computed_grid.dist(&points[2], &points[0]), None);
        assert_eq!(computed_grid.dist(&points[2], &points[1]), None);
        assert_eq!(computed_grid.dist(&points[2], &points[2]), Some(0));
    }

    #[test]
    fn grid_at() {
        let grid = StandardGrid::Blank.compute_grid();
        assert_eq!(grid.wall_at(&Point2::new(0, 0)), true);
    }

    #[test]
    fn grid_at_oob() {
        let grid = StandardGrid::Blank.compute_grid();
        assert_eq!(grid.wall_at(&Point2::new(0, GRID_SIZE as i8)), true);
        assert_eq!(grid.wall_at(&Point2::new(GRID_SIZE as i8, 0)), true);
    }
}

/// Find the direction from the start point to the end point
pub fn facing_direction(start: &Point2<i8>, end: &Point2<i8>) -> Direction {
    if start.y > end.y {
        Right
    } else if start.y < end.y {
        Left
    } else if start.x < end.x {
        Up
    } else if start.x > end.x {
        Down
    } else {
        // start == end
        Stay
    }
}