use std::cmp::{max,min}; use crate::position::Position; pub const LEVEL_WIDTH: usize = 50; pub const LEVEL_HEIGHT: usize = 25; #[derive(Copy, Clone, Debug, PartialEq)] enum StructureElement { Wall, Floor, StairDown, StairUp, Unknown, } #[derive(Copy, Clone, Debug, PartialEq)] pub struct Level { structure: [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH], discovered: [[bool; LEVEL_HEIGHT]; LEVEL_WIDTH], } impl Level { pub fn new() -> Level { let mut s = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH]; for x in 2..LEVEL_WIDTH - 2 { for y in 2..LEVEL_HEIGHT - 2 { s[x][y] = StructureElement::Floor; } } Level { structure: s, discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH], } } pub fn get_element(&self, x: i16, y: i16) -> Option { if x < 0 || y < 0 { return None; } let x = x as usize; let y = y as usize; if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT { return None; } if !self.discovered[x][y] { return Some(StructureElement::Unknown); } Some(self.structure[x][y]) } /// discover the area with in the level around the given position pub fn discover(&mut self, pos: &Position) { let x = pos.get_x(); let y = pos.get_y(); // uncover fields directly next to the player for x_r in max(x - 1, 0)..=min(x + 1, LEVEL_WIDTH - 1) { for y_r in max(y - 1, 0)..=min(y + 1, LEVEL_HEIGHT - 1) { self.discovered[x_r][y_r] = true; } } // uncover fields up to 2 fields right of the player for x_r in x..=min(x + 2, LEVEL_WIDTH - 1) { self.discovered[x_r][y] = true; if self.structure[x_r][y] == StructureElement::Wall { break; } } // uncover fields up to 2 fields below of the player for y_r in y..=min(y + 2, LEVEL_HEIGHT - 1) { self.discovered[x][y_r] = true; if self.structure[x][y_r] == StructureElement::Wall { break; } } // uncover fields up to 2 fields left of the player for x_r in (max(x, 2)..x + 2).rev() { self.discovered[x_r - 2][y] = true; if self.structure[x_r - 2][y] == StructureElement::Wall { break; } } // uncover fields up to 2 fields above of the player for y_r in (max(y, 2)..y + 2).rev() { self.discovered[x][y_r - 2] = true; if self.structure[x][y_r - 2] == StructureElement::Wall { break; } } } } #[test] fn test_get_element() { let l = Level::new(); assert_eq!(l.get_element(-1, -1), None); assert_eq!(l.get_element(0, 0).unwrap(), StructureElement::Unknown); assert_eq!(l.get_element(LEVEL_WIDTH as i16 - 1, LEVEL_HEIGHT as i16 - 1).unwrap(), StructureElement::Unknown); assert_eq!(l.get_element(LEVEL_WIDTH as i16, LEVEL_HEIGHT as i16), None); } #[test] fn test_discover_get_element() { let mut l = Level::new(); assert_eq!(l.get_element(10, 10).unwrap(), StructureElement::Unknown); let p = Position::new(0, 10, 10); l.discover(&p); assert_eq!(l.get_element(10, 10).unwrap(), StructureElement::Floor); assert_eq!(l.get_element(9, 10).unwrap(), StructureElement::Floor); assert_eq!(l.get_element(10, 9).unwrap(), StructureElement::Floor); assert_eq!(l.get_element(11, 10).unwrap(), StructureElement::Floor); assert_eq!(l.get_element(10, 11).unwrap(), StructureElement::Floor); }