add new tile/room functions; redo Not Found errors

This commit is contained in:
Max Bradbury 2020-06-24 14:33:15 +01:00
parent f517f5c8fd
commit 04c0ebca69
1 changed files with 60 additions and 5 deletions

View File

@ -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<T> 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<String>) -> 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<Vec<&Tile>, 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