Refactor common types.
This commit is contained in:
parent
f284b692cc
commit
48419b4674
14 changed files with 376 additions and 250 deletions
67
src/common/position.rs
Normal file
67
src/common/position.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
use crate::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub type PositionType = i32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||
pub struct Position {
|
||||
pub x: PositionType,
|
||||
pub y: PositionType,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Dimension {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
}
|
||||
|
||||
impl Position {
|
||||
pub fn new(x: PositionType, y: PositionType) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
|
||||
pub fn in_direction(&self, dir: &Direction, len: PositionType) -> Position {
|
||||
match dir {
|
||||
Direction::Up => Position::new(self.x, self.y - len),
|
||||
Direction::Right => Position::new(self.x + len, self.y),
|
||||
Direction::Down => Position::new(self.x, self.y + len),
|
||||
Direction::Left => Position::new(self.x - len, self.y),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn in_range(&self, min: &Position, max: &Position) -> Option<&Position> {
|
||||
if self.x < min.x {
|
||||
return None;
|
||||
}
|
||||
if self.x >= max.x {
|
||||
return None;
|
||||
}
|
||||
if self.y < min.y {
|
||||
return None;
|
||||
}
|
||||
if self.y >= max.y {
|
||||
return None;
|
||||
}
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for Position {
|
||||
type Output = Position;
|
||||
|
||||
fn add(mut self, rhs: Self) -> Self::Output {
|
||||
self.x += rhs.x;
|
||||
self.y += rhs.y;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Sub for Position {
|
||||
type Output = Position;
|
||||
|
||||
fn sub(mut self, rhs: Self) -> Self::Output {
|
||||
self.x -= rhs.x;
|
||||
self.y -= rhs.y;
|
||||
self
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue