el_diablo/src/monster.rs

60 lines
1.5 KiB
Rust
Raw Normal View History

2023-11-27 19:21:10 +01:00
use crate::position::Position;
pub struct Monster {
life: usize,
position: Position,
}
impl Monster {
2023-12-17 19:48:58 +01:00
#[cfg(test)]
2023-11-27 19:21:10 +01:00
pub fn new(life: usize) -> Self {
Monster {
life,
position: Position::new(0, 0, 0),
}
}
2023-12-07 10:12:44 +01:00
pub fn new_with_position(life: usize, position: Position) -> Self {
Monster {
life,
position,
}
}
2023-12-17 19:48:58 +01:00
#[cfg(test)]
2023-11-27 19:21:10 +01:00
pub fn get_life(&self) -> usize { self.life }
pub fn is_dead(&self) -> bool { self.life <= 0 }
2023-12-03 13:44:29 +01:00
pub fn decrease_life(&mut self, by: usize) {
self.life = self.life.saturating_sub(by);
2023-11-27 19:21:10 +01:00
}
2023-12-17 19:48:58 +01:00
#[cfg(test)]
2023-11-27 19:21:10 +01:00
pub fn get_position(&mut self) -> &mut Position {
&mut self.position
}
2023-12-03 10:41:43 +01:00
pub fn get_immutable_position(&self) -> &Position {
&self.position
}
2023-11-27 19:21:10 +01:00
}
#[test]
fn monsters_can_move() {
let mut m = Monster::new(2);
assert_eq!(m.get_position(), &Position::new(0, 0, 0));
m.get_position().change(1, 2);
assert_eq!(m.get_position(), &Position::new(0, 1, 2));
m.get_position().change(2, 1);
assert_eq!(m.get_position(), &Position::new(0, 3, 3));
m.get_position().set(1, 2, 3);
m.get_position().change(2, 1);
assert_eq!(m.get_position(), &Position::new(1, 4, 4));
}
#[test]
fn monsters_can_die() {
let mut m = Monster::new(2);
assert_eq!(m.get_life(), 2);
assert_eq!(m.is_dead(), false);
m.decrease_life(1);
assert_eq!(m.get_life(), 1);
m.decrease_life(2);
assert_eq!(m.get_life(), 0);
assert_eq!(m.is_dead(), true);
}