el_diablo/src/position.rs

75 lines
1.6 KiB
Rust

use std::cmp::max;
/// describes an character (PC or NPC) in the dungeon that has a position.
pub trait HasPosition {
/// returns a mutable position
fn get_position(&mut self) -> &mut Position;
/// returns an immutable position
fn get_immutable_position(&self) -> &Position;
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct Position {
level: usize,
x: usize,
y: usize,
}
impl Position {
pub fn new(level: usize, x: usize, y: usize) -> Self {
Self { level, x, y }
}
pub fn change(&mut self, dx: i16, dy: i16) -> (usize, usize) {
self.x = max((self.x as i16) + dx, 0) as usize;
self.y = max((self.y as i16) + dy, 0) as usize;
(self.x, self.y)
}
pub fn set(&mut self, level: usize, x: usize, y: usize) {
self.level = level;
self.x = x;
self.y = y;
}
pub fn get_level(&self) -> usize {
self.level
}
pub fn get_x(&self) -> usize {
self.x
}
pub fn get_y(&self) -> usize {
self.y
}
}
#[test]
fn test_position_change() {
let mut p = Position::new(0, 10, 10);
let res = p.change(-1, 1);
assert_eq!(res, (9, 11));
assert_eq!(p.get_x(), 9);
assert_eq!(p.get_y(), 11);
let res = p.change(-9, 1);
assert_eq!(res, (0, 12));
assert_eq!(p.get_x(), 0);
assert_eq!(p.get_y(), 12);
let res = p.change(-1, -13);
assert_eq!(res, (0, 0));
assert_eq!(p.get_x(), 0);
assert_eq!(p.get_y(), 0);
}
#[test]
fn test_position_set() {
let mut p = Position::new(0, 10, 10);
p.set(1, 2, 3);
assert_eq!(p.get_level(), 1);
assert_eq!(p.get_x(), 2);
assert_eq!(p.get_y(), 3);
}