Skip to main content

TileMap

Struct TileMap 

Source
pub struct TileMap<T>
where T: Tile + Default,
{ 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: Formatting

Implementations§

Source§

impl<T> TileMap<T>
where T: Tile + Default,

Source

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

Source

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

Source

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>>§

Source

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!
Source

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!
Source

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());
Source

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()));
Source

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()));
Source

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);
Source

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);
Source

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);
Source

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);
Source

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)));
Source

pub fn first_vacant(&self) -> Option<Cell>

Returns first vacant Cell

§Note

This returns first Cell in Grid order

§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_vacant(), Some(Cell::new(0, 0)));
Source

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);
Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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 · Source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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 &K stored key value from a borrowed &Q lookup 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 · Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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> Clone for TileMap<T>
where T: Tile + Default + Clone,

Source§

fn clone(&self) -> TileMap<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for TileMap<T>
where T: Tile + Default + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Deref for TileMap<T>
where T: Tile + Default,

Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>

For more info, visit grid-math crate docs

Source§

type Target = GridMap<T>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<T> DerefMut for TileMap<T>
where T: Tile + Default,

Implements Deref trait for TileMap<T>, to return ref to the inner GridMap<T>

For more info, visit grid-math crate docs

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<T> Display for TileMap<T>
where T: Tile + Default,

Source§

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>
where T: Tile + Default,

Source§

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>
where T: Tile + Default,

Source§

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>
where T: Tile + Default,

Source§

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));

Auto Trait Implementations§

§

impl<T> Freeze for TileMap<T>

§

impl<T> RefUnwindSafe for TileMap<T>
where T: RefUnwindSafe,

§

impl<T> Send for TileMap<T>
where T: Send,

§

impl<T> Sync for TileMap<T>
where T: Sync,

§

impl<T> Unpin for TileMap<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for TileMap<T>

§

impl<T> UnwindSafe for TileMap<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V