diff --git a/src/game.rs b/src/game.rs index cbb4487..087c1cb 100644 --- a/src/game.rs +++ b/src/game.rs @@ -81,7 +81,11 @@ impl Version { } #[derive(Debug)] -pub struct SpriteNotFound; +pub enum NotFound { + Room, + Sprite, + Tile, +} #[derive(Clone, Debug, PartialEq)] pub struct Game { @@ -244,7 +248,7 @@ impl Game { /// todo refactor this into "get T by ID", taking a Vec and an ID name? #[inline] - pub fn get_sprite_by_id(&self, id: String) -> Result<&Sprite, SpriteNotFound> { + pub fn get_sprite_by_id(&self, id: String) -> Result<&Sprite, NotFound> { let index = self.sprites.iter().position( |sprite| sprite.id == id ); @@ -252,14 +256,65 @@ impl Game { if index.is_some() { Ok(&self.sprites[index.unwrap()]) } else { - Err(SpriteNotFound) + Err(NotFound::Sprite) } } - pub fn get_avatar(&self) -> Result<&Sprite, SpriteNotFound> { + pub fn get_tile_by_id(&self, id: String) -> Result<&Tile, NotFound> { + let index = self.tiles.iter().position( + |tile| tile.id == id + ); + + if index.is_some() { + Ok(&self.tiles[index.unwrap()]) + } else { + Err(NotFound::Tile) + } + } + + pub fn get_room_by_id(&self, id: String) -> Result<&Room, NotFound> { + let index = self.rooms.iter().position( + |room| room.id == id + ); + + if index.is_some() { + Ok(&self.rooms[index.unwrap()]) + } else { + Err(NotFound::Room) + } + } + + pub fn get_avatar(&self) -> Result<&Sprite, NotFound> { self.get_sprite_by_id("A".to_string()) } + // todo result + pub fn get_tiles_by_ids(&self, ids: Vec) -> Vec<&Tile> { + let mut tiles: Vec<&Tile> = Vec::new(); + + for id in ids { + let tile = self.get_tile_by_id(id); + if tile.is_ok() { + tiles.push(tile.unwrap()); + } + } + + tiles + } + + pub fn get_tiles_for_room(&self, id: String) -> Result, NotFound> { + let room = self.get_room_by_id(id); + if room.is_err() { + return Err(NotFound::Room); + } + let mut tile_ids = room.unwrap().tiles.clone(); + tile_ids.sort(); + tile_ids.dedup(); + // remove Ok once this function returns a result + Ok(self.get_tiles_by_ids(tile_ids)) + } + + // return? array of changes made? status? pub fn merge(game: Game) { // ignore title, version, room format, room type, font, text direction @@ -440,7 +495,7 @@ impl Game { pub fn new_variable_id(&self) -> String { new_unique_id(self.variable_ids()) } - + /// adds a palette safely and returns the new palette ID #[inline] pub fn add_palette(&mut self, mut palette: Palette) -> String {