pub struct TileMap<T>{
pub formatting: Formatting,
/* private fields */
}Expand description
TileMap<T>, represents a tilemap over the type T, where T is Tile + Default
TileMap<T> is based on the GridMap<V> from the grid-math crate,
and implements the Deref and the DerefMut traits to deref to the inner GridMap<T>
§Examples
use cli_tilemap::{Tile, TileMap, Formatting};
use crossterm::style::{Stylize, StyledContent};
use grid_math::Cell;
use std::io::stdout;
#[derive(Default, Debug)]
enum Entity {
Enemy,
Hero,
#[default]
Air,
}
impl Tile for Entity {
fn tile(&self) -> StyledContent<&'static str> {
match self {
Self::Air => "[-]".dark_grey().bold(),
Self::Hero => "[&]".green().bold(),
Self::Enemy => "[@]".red().bold(),
}
}
}
// new 5x5 tilemap:
let mut map: TileMap<Entity> = TileMap::new(5, 5);
// insert entities:
map.insert(Cell::new(3, 3), Entity::Enemy);
map.insert(Cell::new(1, 0), Entity::Hero);
// draw map to the raw stdout:
map.draw(&mut stdout()).expect("should be able to draw to the stdout!");
// change row and tile spacing:
map.formatting.row_spacing = 2;
map.formatting.tile_spacing = 4;
// format as a string and print:
let map_string = map.to_string();
println!("{map_string}");Fields§
§formatting: FormattingImplementations§
Source§impl<T> TileMap<T>
impl<T> TileMap<T>
Sourcepub fn new(width: u8, depth: u8) -> Self
pub fn new(width: u8, depth: u8) -> Self
Creates new TileMap<T> with the empty inner GridMap<T> of specified size,
and with the defult Formatting
For more info, visit grid-math crate docs
Sourcepub fn formatted(width: u8, depth: u8, formatting: Formatting) -> Self
pub fn formatted(width: u8, depth: u8, formatting: Formatting) -> Self
Creates new TileMap<T> with the empty inner GridMap<T> of specified size,
and with the given Formatting
For more info, visit grid-math crate docs
Sourcepub fn draw<W: Write>(&self, stdout: &mut W) -> Result<()>
pub fn draw<W: Write>(&self, stdout: &mut W) -> Result<()>
Draws the TileMap<T> to the given stdout, using the inner Formatting rules
§Examples
use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
use std::io::stdout;
#[derive(Default)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let mut map: TileMap<Empty> = TileMap::new(5, 5);
map.draw(&mut stdout()).expect("should be able to draw to the stdout!");Methods from Deref<Target = GridMap<T>>§
Sourcepub fn insert(&mut self, cell: Cell, value: V) -> Option<V>
pub fn insert(&mut self, cell: Cell, value: V) -> Option<V>
Shadows insert method from the HashMap, and reimplements it
so it checks first if the key (Cell) is within the Grid, and then inserts it into the HashMap.
This method currently has bad error handling, but this may change in the future
§Panics
Panics, if the key (Cell) is not within the inner Grid
§Examples:
use grid_math::{Grid, GridMap};
let grid = Grid::new(5, 5);
let mut map: GridMap<char> = GridMap::from(grid);
map.insert(map.grid().start(), '#');
map.insert(map.grid().end(), '@');
assert_eq!(map.len(), 2);use grid_math::{Cell, Grid, GridMap};
let grid = Grid::new(5, 5);
let cell = Cell::new(6, 6);
let mut map: GridMap<char> = GridMap::from(grid);
map.insert(cell, '#'); // panic!Sourcepub fn vacant_insert(&mut self, cell: Cell, value: V) -> bool
pub fn vacant_insert(&mut self, cell: Cell, value: V) -> bool
Inserts new object only if the Cell is not occupied.
Returns true if inserted, and false if not
§Panics
Panics, if the key (Cell) is not within the inner Grid
§Examples:
use grid_math::{Grid, GridMap};
let grid = Grid::new(5, 5);
let mut map: GridMap<char> = GridMap::from(grid);
assert!(map.vacant_insert(map.grid().start(), '#'));
assert!(!map.vacant_insert(map.grid().start(), '@'));
assert_eq!(map.get(&map.grid().start()), Some(&'#'));use grid_math::{Cell, Grid, GridMap};
let grid = Grid::new(5, 5);
let cell = Cell::new(6, 6);
let mut map: GridMap<char> = GridMap::from(grid);
map.vacant_insert(cell, '#'); // panic!Sourcepub fn grid(&self) -> Grid
pub fn grid(&self) -> Grid
Returns the inner Grid
§Examples:
use grid_math::{Grid, GridMap};
let grid = Grid::new(5, 5);
let map: GridMap<char> = GridMap::from(grid);
assert_eq!(grid, map.grid());Sourcepub fn occupied(&self, cell: Cell) -> bool
pub fn occupied(&self, cell: Cell) -> bool
Checks if the Cell is occupied. This is an alias for contains_key method
§Panics
Panics, if the given Cell is not within the inner Grid
§Examples:
use grid_math::{Cell, Grid, GridMap};
let grid = Grid::new(5, 5);
let cell = Cell::new(2, 3);
let mut map: GridMap<char> = GridMap::from(grid);
map.insert(cell, '#');
assert!(map.occupied(cell));
assert!(!map.occupied(map.grid().start()));Sourcepub fn vacant(&self, cell: Cell) -> bool
pub fn vacant(&self, cell: Cell) -> bool
Checks if the Cell is free
§Panics
Panics, if the given Cell is not within the inner Grid
§Examples:
use grid_math::{Cell, Grid, GridMap};
let grid = Grid::new(5, 5);
let cell = Cell::new(2, 3);
let mut map: GridMap<char> = GridMap::from(grid);
map.insert(cell, '#');
assert!(!map.vacant(cell));
assert!(map.vacant(map.grid().start()));Sourcepub fn occupied_count(&self) -> u16
pub fn occupied_count(&self) -> u16
Returns count of occupied Cells
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.occupied_count(), 2);Sourcepub fn vacant_count(&self) -> u16
pub fn vacant_count(&self) -> u16
Returns count of vacant Cells
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.vacant_count(), 23);Sourcepub fn all_occupied(&self) -> Filter<Cells, impl FnMut(&Cell)> ⓘ
pub fn all_occupied(&self) -> Filter<Cells, impl FnMut(&Cell)> ⓘ
Returns an iterator over every occupied Cell
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.all_occupied().count(), 2);Sourcepub fn all_vacant(&self) -> Filter<Cells, impl FnMut(&Cell)> ⓘ
pub fn all_vacant(&self) -> Filter<Cells, impl FnMut(&Cell)> ⓘ
Returns an iterator over every vacant Cell
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.all_vacant().count(), 23);Sourcepub fn first_occupied(&self) -> Option<Cell>
pub fn first_occupied(&self) -> Option<Cell>
Returns first occupied Cell
§Note
This returns first Cell in Grid order, so (2, 3) will go after (4, 1)
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.first_occupied(), Some(Cell::new(4, 1)));Sourcepub fn first_vacant(&self) -> Option<Cell>
pub fn first_vacant(&self) -> Option<Cell>
Sourcepub fn random_occupied(&self) -> Option<Cell>
pub fn random_occupied(&self) -> Option<Cell>
Returns random occupied Cell
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_ne!(map.get(&map.random_occupied().unwrap()), None);
assert_ne!(map.get(&map.random_occupied().unwrap()), None);
assert_ne!(map.get(&map.random_occupied().unwrap()), None);Sourcepub fn random_vacant(&self) -> Option<Cell>
pub fn random_vacant(&self) -> Option<Cell>
Returns random vacant Cell
§Examples:
use grid_math::{Cell, Grid, GridMap};
let mut map: GridMap<char> = GridMap::new(5, 5);
map.insert(Cell::new(2, 3), '#');
map.insert(Cell::new(4, 1), '@');
assert_eq!(map.get(&map.random_vacant().unwrap()), None);
assert_eq!(map.get(&map.random_vacant().unwrap()), None);
assert_eq!(map.get(&map.random_vacant().unwrap()), None);Methods from Deref<Target = HashMap<Cell, V>>§
1.0.0 · Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
This number is a lower bound; the HashMap<K, V> might be able to hold
more, but is guaranteed to be able to hold at least this many.
§Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);1.0.0 · Sourcepub fn keys(&self) -> Keys<'_, K, V> ⓘ
pub fn keys(&self) -> Keys<'_, K, V> ⓘ
An iterator visiting all keys in arbitrary order.
The iterator element type is &'a K.
§Examples
use std::collections::HashMap;
let map: HashMap<&str, i32> = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
let mut values: Vec<_> = map.keys().copied().collect();
values.sort();
assert_eq!(values, vec!["a", "b", "c"]);§Performance
In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn values(&self) -> Values<'_, K, V> ⓘ
pub fn values(&self) -> Values<'_, K, V> ⓘ
An iterator visiting all values in arbitrary order.
The iterator element type is &'a V.
§Examples
use std::collections::HashMap;
let map: HashMap<&str, i32> = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
let mut values: Vec<_> = map.values().copied().collect();
values.sort();
assert_eq!(values, vec![1, 2, 3]);§Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, K, V> ⓘ
pub fn iter(&self) -> Iter<'_, K, V> ⓘ
An iterator visiting all key-value pairs in arbitrary order.
The iterator element type is (&'a K, &'a V).
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
let mut count = 0;
for (_key, _val) in map.iter() {
count += 1;
}
assert_eq!(count, 3);§Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);1.0.0 · Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the map contains no elements.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());1.9.0 · Sourcepub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the map’s BuildHasher.
§Examples
use std::collections::HashMap;
use std::hash::RandomState;
let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();1.0.0 · Sourcepub fn get<Q>(&self, k: &Q) -> Option<&V>
pub fn get<Q>(&self, k: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash and Eq on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);1.40.0 · Sourcepub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
Returns the key-value pair corresponding to the supplied key. This is potentially useful:
- for key types where non-identical keys can be considered equal;
- for getting the
&Kstored key value from a borrowed&Qlookup key; or - for getting a reference to a key with the same lifetime as the collection.
The supplied key may be any borrowed form of the map’s key type, but
Hash and Eq on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Debug)]
struct S {
id: u32,
name: &'static str, // ignored by equality and hashing operations
}
impl PartialEq for S {
fn eq(&self, other: &S) -> bool {
self.id == other.id
}
}
impl Eq for S {}
impl Hash for S {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);
let mut map = HashMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);1.0.0 · Sourcepub fn contains_key<Q>(&self, k: &Q) -> bool
pub fn contains_key<Q>(&self, k: &Q) -> bool
Returns true if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but
Hash and Eq on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);Trait Implementations§
Source§impl<T> Deref for TileMap<T>
Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>
impl<T> Deref for TileMap<T>
Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>
For more info, visit grid-math crate docs
Source§impl<T> DerefMut for TileMap<T>
Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>
impl<T> DerefMut for TileMap<T>
Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>
For more info, visit grid-math crate docs
Source§impl<T> Display for TileMap<T>
impl<T> Display for TileMap<T>
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Implements fmt method for the TileMap<T> in the same way as the draw method works
§Examples
use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
#[derive(Default)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let mut map: TileMap<Empty> = TileMap::new(5, 5);
println!("{map}");Source§impl<T> From<(Grid, HashMap<Cell, T>)> for TileMap<T>
impl<T> From<(Grid, HashMap<Cell, T>)> for TileMap<T>
Source§fn from(data: (Grid, HashMap<Cell, T>)) -> Self
fn from(data: (Grid, HashMap<Cell, T>)) -> Self
Creates TileMap<T> from the existing HashMap<Cell, T> and the given Grid
§Panics
Panics if the given HashMap<Cell, T> contains Cells that are not within the given Grid
This panic is a part of grid-math crate current state, error handling may change in the future
§Examples
use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
use grid_math::{Cell, Grid};
use std::collections::HashMap;
#[derive(Debug, Default, PartialEq, Eq)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let grid = Grid::new(5, 5);
let mut hashmap: HashMap<Cell, Empty> = HashMap::new();
let target = Cell::new(1, 2);
hashmap.insert(target, Empty);
let map: TileMap<Empty> = TileMap::from((grid, hashmap));
assert_eq!(map.get(&target), Some(&Empty));use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
use grid_math::{Cell, Grid};
use std::collections::HashMap;
#[derive(Debug, Default, PartialEq, Eq)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let grid = Grid::new(5, 5);
let mut hashmap: HashMap<Cell, Empty> = HashMap::new();
let target = Cell::new(7, 1);
hashmap.insert(target, Empty);
let map: TileMap<Empty> = TileMap::from((grid, hashmap)); // panic!Source§impl<T> From<Grid> for TileMap<T>
impl<T> From<Grid> for TileMap<T>
Source§fn from(grid: Grid) -> Self
fn from(grid: Grid) -> Self
Creates new empty TileMap<T> from the specified Grid
§Examples
use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
use grid_math::{Cell, Grid};
#[derive(Default)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let cells = (Cell::new(2, 2), Cell::new(5, 5));
let grid = Grid::from(cells);
let map: TileMap<Empty> = TileMap::from(grid);
assert_eq!(map.grid(), grid);Source§impl<T> From<GridMap<T>> for TileMap<T>
impl<T> From<GridMap<T>> for TileMap<T>
Source§fn from(gridmap: GridMap<T>) -> Self
fn from(gridmap: GridMap<T>) -> Self
Creates TileMap<T> from the existing GridMap<T> where T: Tile + Default
§Examples
use cli_tilemap::{Tile, TileMap};
use crossterm::style::{Stylize, StyledContent};
use grid_math::{Cell, GridMap};
#[derive(Debug, Default, PartialEq, Eq)]
struct Empty;
impl Tile for Empty {
fn tile(&self) -> StyledContent<&'static str> {
"[-]".dark_grey().bold()
}
}
let mut gridmap: GridMap<Empty> = GridMap::new(5, 5);
let target = Cell::new(1, 2);
gridmap.insert(target, Empty);
let map: TileMap<Empty> = TileMap::from(gridmap);
assert_eq!(map.get(&target), Some(&Empty));