block_breaker/
position.rs

1use crate::vector::Vector;
2use std::ops::{Add, AddAssign, Sub, SubAssign};
3
4/// A generic position
5pub struct Position {
6    x: f64,
7    y: f64,
8}
9
10impl Position {
11    /// Create a new position
12    pub fn new(x: u16, y: u16) -> Position {
13        Position {
14            x: f64::from(x),
15            y: f64::from(y),
16        }
17    }
18
19    /// Get the x coordinate
20    pub fn x(&self) -> u16 {
21        self.x as u16
22    }
23
24    /// Get the y coordinate
25    pub fn y(&self) -> u16 {
26        self.y as u16
27    }
28}
29
30impl Add for Position {
31    type Output = Self;
32
33    fn add(self, other: Self) -> Self {
34        Self {
35            x: self.x + other.x,
36            y: self.y + other.y,
37        }
38    }
39}
40
41impl<'a, 'b> Add<&'b Position> for &'a Position {
42    type Output = Position;
43
44    fn add(self, other: &'b Position) -> Position {
45        Position {
46            x: self.x + other.x,
47            y: self.y + other.y,
48        }
49    }
50}
51
52impl<'a, 'b> Add<&'b Vector> for &'a Position {
53    type Output = Position;
54
55    fn add(self, other: &'b Vector) -> Position {
56        Position {
57            x: self.x + other.x(),
58            y: self.y + other.y(),
59        }
60    }
61}
62
63impl AddAssign<Position> for Position {
64    fn add_assign(&mut self, other: Self) {
65        *self = Self {
66            x: self.x + other.x,
67            y: self.y + other.y,
68        }
69    }
70}
71
72impl<'a> AddAssign<&'a Position> for Position {
73    fn add_assign(&mut self, other: &Self) {
74        *self = Self {
75            x: self.x + other.x,
76            y: self.y + other.y,
77        }
78    }
79}
80
81impl Sub for Position {
82    type Output = Self;
83
84    fn sub(self, other: Self) -> Self {
85        Self {
86            x: self.x - other.x,
87            y: self.y - other.y,
88        }
89    }
90}
91
92impl SubAssign for Position {
93    fn sub_assign(&mut self, other: Self) {
94        *self = Self {
95            x: self.x - other.x,
96            y: self.y - other.y,
97        }
98    }
99}