el_diablo/src/level.rs
2023-11-23 09:29:13 +01:00

117 lines
3.4 KiB
Rust

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)]
pub enum StructureElement {
Wall,
Floor,
StairDown,
StairUp,
Start,
End,
Unknown,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Artifact {
Chest { gold: usize },
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Level {
pub(crate) structure: [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) discovered: [[bool; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) artifacts: [[Option<Artifact>; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) start_x: usize,
pub(crate) start_y: usize,
pub(crate) end_x: usize,
pub(crate) end_y: usize,
}
impl Level {
pub fn new() -> Level {
let s = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
Level {
structure: s,
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
artifacts: [[None; LEVEL_HEIGHT]; LEVEL_WIDTH],
start_x: 1,
start_y: 1,
end_x: 1,
end_y: 1,
}
}
pub fn remove_artifact(&mut self, x: i16, y: i16) {
if x < 0 || y < 0 {
return;
}
let x = x as usize;
let y = y as usize;
if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT {
return;
}
self.artifacts[x][y] = None;
}
pub fn get_element(&self, x: i16, y: i16) -> (Option<StructureElement>, Option<Artifact>) {
if x < 0 || y < 0 {
return (None, None);
}
let x = x as usize;
let y = y as usize;
if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT {
return (None, None);
}
if !self.discovered[x][y] {
return (Some(StructureElement::Unknown), None);
}
return (Some(self.structure[x][y]), self.artifacts[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();
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;
}
}
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;
}
}
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;
}
}
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;
}
}
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(0, 0).0.unwrap(), StructureElement::Wall);
assert_eq!(l.get_element(4, 4).0.unwrap(), StructureElement::StairDown);
assert_eq!(l.get_element(49, 24).0.unwrap(), StructureElement::Wall);
assert_eq!(l.get_element(50, 25).0, None);
}