Skip to content

Commit

Permalink
finish map crate
Browse files Browse the repository at this point in the history
  • Loading branch information
LuckyTurtleDev committed May 12, 2023
1 parent 8eb4421 commit f17c015
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
30 changes: 26 additions & 4 deletions map/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use self_rust_tokenize::SelfRustTokenize;
use std::path::Path;
use std::{iter, path::Path};
use thiserror::Error;
use tiled::{LayerType, Loader};

pub mod tiles;
use tiles::{InvalidTileID, MapBaseTile, ObjectTile, PlayerTile};
use tiles::{InvalidTileID, MapBaseTile, MapTiles, ObjectTile, PlayerTile};

#[derive(Clone, Debug, SelfRustTokenize)]
pub struct Player {
Expand All @@ -19,7 +19,7 @@ pub struct Map {
pub base_layer: Vec<Vec<MapBaseTile>>,
pub object_layer: Vec<Vec<Option<ObjectTile>>>,
pub global_goal: Option<(u8, u8)>,
pub player_1: Option<Player>,
pub player_1: Player,
pub player_2: Option<Player>,
pub player_3: Option<Player>,
pub player_4: Option<Player>
Expand All @@ -40,7 +40,9 @@ pub enum MapError {
#[error("Map is to hight. Max size is 255x255 tiles")]
ToHight,
#[error("{0}")]
InvalidTileId(#[from] InvalidTileID)
InvalidTileId(#[from] InvalidTileID),
#[error("Map needs at least one player")]
NoPlayer,
}

impl Map {
Expand Down Expand Up @@ -136,6 +138,7 @@ impl Map {
_ => return Err(MapError::ToManyLayers)
}
}
let player_1 = player_1.ok_or(MapError::NoPlayer)?;
Ok(Map {
width,
height,
Expand Down Expand Up @@ -168,4 +171,23 @@ impl Map {
.filter_map(move |(y, item)| item.map(|item| (x as u8, y as u8, item)))
})
}

/// return an iterator over all player goals tiles and its x and y postion
pub fn iter_player_goals(&self) -> impl Iterator<Item = (u8, u8, PlayerTile)> + '_ {
iter::once(self.global_goal)
.flat_map(|goal| goal.map(|(x, y)| (x, y, PlayerTile::GlobalGoal)))
}

/// return an iterator over all static Tiles and its x and y postion.
/// starting from the lowest layer
pub fn iter_all(&self) -> impl Iterator<Item = (u8, u8, MapTiles)> + '_ {
let base = self
.iter_base_layer()
.map(|(x, y, tile)| (x, y, MapTiles::MapBaseTile(tile.to_owned())));
let objects = self
.iter_object_layer()
.map(|(x, y, tile)| (x, y, MapTiles::MapObjectTile(tile.to_owned())));
let goals = self.iter_player_goals().map(|(x, y, tile)| (x, y, MapTiles::PlayerTile(tile)));
base.chain(objects).chain(goals)
}
}
6 changes: 6 additions & 0 deletions map/src/tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ use num_enum::TryFromPrimitive;
use self_rust_tokenize::SelfRustTokenize;
use thiserror::Error;

pub enum MapTiles {
MapBaseTile(MapBaseTile),
MapObjectTile(ObjectTile),
PlayerTile(PlayerTile)
}

#[derive(Debug, Copy, Clone, Error)]
pub enum InvalidTileID {
#[error("invalid tiel id {0}")]
Expand Down

0 comments on commit f17c015

Please sign in to comment.