first cut of dir / dist to local objects

also bug fix for param reading, where the param wasnt bound by min max
This commit is contained in:
Christopher
2023-03-05 08:11:24 +13:00
parent c4d4f820ac
commit 5542e2fe59
4 changed files with 44 additions and 6 deletions

View File

@@ -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))
}
}
}

View File

@@ -42,12 +42,15 @@ pub fn prompt_value<T: FromStr + PartialOrd>(prompt_text: &str, min: T, max: T)
}
pub fn param_or_prompt_value<T: FromStr + PartialOrd>(params: &Vec<String>, param_pos: usize, prompt_text: &str, min: T, max: T) -> Option<T> {
let mut res: Option<T> = None;
if params.len() > param_pos {
match params[param_pos].parse::<T>() {
Ok(n) => Some(n),
_ => None
Ok(n) if (n >= min && n <= max) => res = Some(n),
_ => ()
}
} else {
return prompt_value::<T>(prompt_text, min, max);
}
if res.is_some() {
return res;
}
return prompt_value::<T>(prompt_text, min, max);
}

View File

@@ -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)
}

View File

@@ -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}"
)
}