diff --git a/84_Super_Star_Trek/rust/src/commands.rs b/84_Super_Star_Trek/rust/src/commands.rs index cf427310..60ffcb21 100644 --- a/84_Super_Star_Trek/rust/src/commands.rs +++ b/84_Super_Star_Trek/rust/src/commands.rs @@ -322,8 +322,9 @@ fn show_starbase_data(galaxy: &Galaxy) { }, Some(s) => { view::starbase_report(); - let pos = s.sector; - // calulcate direction and distance then print + let origin = galaxy.enterprise.sector; + let target = s.sector; + view::direction_distance(origin.direction(target), origin.dist(target)) } } } diff --git a/84_Super_Star_Trek/rust/src/input.rs b/84_Super_Star_Trek/rust/src/input.rs index 5bd35fb3..68ab7006 100644 --- a/84_Super_Star_Trek/rust/src/input.rs +++ b/84_Super_Star_Trek/rust/src/input.rs @@ -42,12 +42,15 @@ pub fn prompt_value(prompt_text: &str, min: T, max: T) } pub fn param_or_prompt_value(params: &Vec, param_pos: usize, prompt_text: &str, min: T, max: T) -> Option { + let mut res: Option = None; if params.len() > param_pos { match params[param_pos].parse::() { - Ok(n) => Some(n), - _ => None + Ok(n) if (n >= min && n <= max) => res = Some(n), + _ => () } - } else { - return prompt_value::(prompt_text, min, max); } + if res.is_some() { + return res; + } + return prompt_value::(prompt_text, min, max); } \ No newline at end of file diff --git a/84_Super_Star_Trek/rust/src/model.rs b/84_Super_Star_Trek/rust/src/model.rs index 9b2f1118..dd2b8dd8 100644 --- a/84_Super_Star_Trek/rust/src/model.rs +++ b/84_Super_Star_Trek/rust/src/model.rs @@ -154,6 +154,33 @@ impl Pos { self.0.abs_diff(other.0) + self.1.abs_diff(other.1) } + pub fn dist(&self, other: Pos) -> f32 { + let dx = other.0 as f32 - self.0 as f32; + let dy = other.1 as f32 - self.1 as f32; + (f32::powi(dx, 2) + f32::powi(dy, 2)).sqrt() + } + + pub fn direction(&self, other: Pos) -> f32 { + // this is a replication of the original BASIC code + let dx = other.0 as f32 - self.0 as f32; + let dy = other.1 as f32 - self.1 as f32; + let dx_dominant = dx.abs() > dy.abs(); + + let frac = if dx_dominant { dy / dx } else { -dx / dy }; + let nearest_cardinal = + if dx_dominant { + if dx > 0. { 7. } else { 3. } + } else { + if dy > 0. { 1. } else { 5. } + }; + + let mut dir = nearest_cardinal + frac; + if dir < 1. { + dir += 8. + } + dir + } + pub fn as_galactic_sector(&self, containing_quadrant: Pos) -> Self { Pos(containing_quadrant.0 * 8 + self.0, containing_quadrant.1 * 8 + self.1) } diff --git a/84_Super_Star_Trek/rust/src/view.rs b/84_Super_Star_Trek/rust/src/view.rs index 75ad1924..19cc7a57 100644 --- a/84_Super_Star_Trek/rust/src/view.rs +++ b/84_Super_Star_Trek/rust/src/view.rs @@ -587,4 +587,11 @@ pub fn no_local_starbase() { pub fn starbase_report() { println!("From Enterprise to Starbase:'") +} + +pub fn direction_distance(dir: f32, dist: f32) { + println!( +"Direction = {dir} +Distance = {dist}" + ) } \ No newline at end of file