diff options
author | Justin Worthe <justin.worthe@gmail.com> | 2017-05-20 18:01:43 +0200 |
---|---|---|
committer | Justin Worthe <justin.worthe@gmail.com> | 2017-05-20 18:01:43 +0200 |
commit | 7dd0fe43fe7e72e5f56a8a61bbaec3a78399e6c8 (patch) | |
tree | 4b1cfd0375609019c0e1a07f34bf8e5574ffce84 /src/math.rs | |
parent | 10c8ceb168e86a58e38086691ddd519bac63ff03 (diff) |
Moved ship placement knowledge out to be one per ship
Diffstat (limited to 'src/math.rs')
-rw-r--r-- | src/math.rs | 70 |
1 files changed, 57 insertions, 13 deletions
diff --git a/src/math.rs b/src/math.rs index 3d8a976..2ef1013 100644 --- a/src/math.rs +++ b/src/math.rs @@ -63,19 +63,63 @@ impl Point { } - pub fn move_point(&self, direction: Direction, distance: u16, map_size: u16) -> Option<Point> { - let x = self.x; - let y = self.y; - - match direction { - South if y < distance => None, - West if x < distance => None, - North if y + distance >= map_size => None, - East if x + distance >= map_size => None, - South => Some(Point::new(x, y-distance)), - West => Some(Point::new(x-distance, y)), - North => Some(Point::new(x, y+distance)), - East => Some(Point::new(x+distance, y)) + pub fn move_point(&self, direction: Direction, distance: i32, map_size: u16) -> Option<Point> { + let x = self.x as i32 + match direction { + West => -distance, + East => distance, + _ => 0 + }; + let y = self.y as i32 + match direction { + South => -distance, + North => distance, + _ => 0 + }; + let max = map_size as i32; + + if x >= max || y >= max || x < 0 || y < 0 { + None + } + else { + Some(Point::new(x as u16, y as u16)) } } + + pub fn move_point_no_bounds_check(&self, direction: Direction, distance: i32) -> Point { + let x = self.x as i32 + match direction { + West => -distance, + East => distance, + _ => 0 + }; + let y = self.y as i32 + match direction { + South => -distance, + North => distance, + _ => 0 + }; + + Point::new(x as u16, y as u16) + } + + pub fn check_for_ship_collision(&self, ship_start: Point, direction: Direction, length: u16) -> bool { + let reverse = match direction { + West | South => true, + East | North => false + }; + + let same_cross = match direction { + East | West => self.y == ship_start.y, + North | South => self.x == ship_start.x + }; + + let (parr_self, parr_ship) = match direction { + East | West => (self.x, ship_start.x), + North | South => (self.y, ship_start.y) + }; + + let corrected_parr_ship = match reverse { + true => parr_ship - length + 1, + false => parr_ship + }; + + same_cross && parr_self >= corrected_parr_ship && parr_self < corrected_parr_ship + length + } } |