el_diablo/src/position.rs

75 lines
1.6 KiB
Rust
Raw Normal View History

2023-12-07 10:12:44 +01:00
use std::cmp::max;
2023-12-25 13:47:15 +01:00
/// 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)]
2023-11-08 06:52:20 +01:00
pub struct Position {
2023-11-27 19:21:10 +01:00
level: usize,
x: usize,
y: usize,
2023-11-08 06:52:20 +01:00
}
impl Position {
2023-11-27 19:21:10 +01:00
pub fn new(level: usize, x: usize, y: usize) -> Self {
2024-10-20 14:59:20 +02:00
Self { level, x, y }
2023-11-08 06:52:20 +01:00
}
2023-12-07 10:12:44 +01:00
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)
2023-11-27 19:21:10 +01:00
}
pub fn set(&mut self, level: usize, x: usize, y: usize) {
self.level = level;
self.x = x;
self.y = y;
}
2023-12-03 09:25:03 +01:00
pub fn get_level(&self) -> usize {
self.level
}
2023-11-27 19:21:10 +01:00
pub fn get_x(&self) -> usize {
self.x
}
2024-10-20 14:59:20 +02:00
pub fn get_y(&self) -> usize {
self.y
}
2023-12-07 10:12:44 +01:00
}
#[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);
2024-10-20 14:59:20 +02:00
}