From 872529bc9a13b1923047a7f9308abaa40eb63d3c Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Sat, 13 May 2017 21:01:14 +0200 Subject: Random placement --- src/math.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 45 insertions(+), 13 deletions(-) (limited to 'src/math.rs') diff --git a/src/math.rs b/src/math.rs index 665d4d0..8e81348 100644 --- a/src/math.rs +++ b/src/math.rs @@ -2,18 +2,18 @@ use std::fmt; use rand; use rand::distributions::{IndependentSample, Range}; -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Orientation { +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Direction { North, East, South, West, } -impl fmt::Display for Orientation { +use Direction::*; + +impl fmt::Display for Direction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use Orientation::*; - f.write_str( match self { &North => "North", @@ -25,7 +25,22 @@ impl fmt::Display for Orientation { } } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +impl Direction { + pub fn random() -> Direction { + let mut rng = rand::thread_rng(); + let between = Range::new(0, 4); + let dir = between.ind_sample(&mut rng); + match dir { + 0 => North, + 1 => East, + 2 => South, + 3 => West, + _ => panic!("Invalid number generated by random number generator") + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Point { pub x: u16, pub y: u16 @@ -38,12 +53,29 @@ impl Point { y: y } } -} -pub fn random_point(map_dimension: u16) -> Point { - let mut rng = rand::thread_rng(); - let between = Range::new(0, map_dimension); - let x = between.ind_sample(&mut rng); - let y = between.ind_sample(&mut rng); - Point::new(x, y) + pub fn random(map_size: u16) -> Point { + let mut rng = rand::thread_rng(); + let between = Range::new(0, map_size); + let x = between.ind_sample(&mut rng); + let y = between.ind_sample(&mut rng); + Point::new(x, y) + } + + + pub fn move_point(&self, direction: Direction, distance: u16, map_size: u16) -> Option { + 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)) + } + } } -- cgit v1.2.3