Skip to content

Commit

Permalink
Support indexing a GridMap by Point
Browse files Browse the repository at this point in the history
Overload the Index operator for GridMap to support indexing by Point.
  • Loading branch information
seilis committed Jan 15, 2025
1 parent c3013dc commit ac379bb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/rpgtools/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
//!
//! This crate contains various tools for working with role-playing-game (RPG) data.
pub mod error;
pub mod map;
pub mod map;
14 changes: 13 additions & 1 deletion src/rpgtools/map/gridmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
use std::cmp;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::ops::Index;
use std::ops::IndexMut;

// Extern crates
use rand::prelude::*;
Expand Down Expand Up @@ -105,7 +107,7 @@ impl GridMap {
.find_by(point, &|cell: &GridCell| -> bool { cell.is_room() })
.unwrap();

self.place_entrance(point);
self.place_entrance(point)?;
Ok(())
}

Expand Down Expand Up @@ -626,6 +628,16 @@ impl GridMap {
}
}

impl Index<Point> for GridMap {
type Output = GridCell;

fn index(&self, index: Point) -> &Self::Output {
let (x, y): (usize, usize) = index.try_into().unwrap();
&self.cells[x][y]
}
}


#[cfg(test)]
mod tests {

Expand Down
4 changes: 2 additions & 2 deletions src/rpgtools/map/gridmap/point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use std::ops::{Add, Neg, Sub};
/// Note that this type is just an index and therefore implements both Clone and Copy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Point {
x: i64,
y: i64,
pub x: i64,
pub y: i64,
}

impl Point {
Expand Down

0 comments on commit ac379bb

Please sign in to comment.