From 7c8c420d4435f8afcc52c5aba0ddcfd1c84f8ee6 Mon Sep 17 00:00:00 2001 From: Christopher Date: Tue, 28 Feb 2023 20:15:46 +1300 Subject: [PATCH] work on nav command under new model --- 84_Super_Star_Trek/rust/src/main.rs | 44 +++++++++++++++---- 84_Super_Star_Trek/rust/src/text_constants.rs | 2 + 2 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 84_Super_Star_Trek/rust/src/text_constants.rs diff --git a/84_Super_Star_Trek/rust/src/main.rs b/84_Super_Star_Trek/rust/src/main.rs index cc6948ac..3fcf9632 100644 --- a/84_Super_Star_Trek/rust/src/main.rs +++ b/84_Super_Star_Trek/rust/src/main.rs @@ -1,21 +1,25 @@ -use std::{io::{stdin, stdout, Write}, process::exit}; +use std::{io::{stdin, stdout, Write}, process::exit, str::FromStr}; use model::Galaxy; +use crate::text_constants::BAD_NAV; + mod model; mod commands; +mod text_constants; fn main() { ctrlc::set_handler(move || { exit(0) }) .expect("Error setting Ctrl-C handler"); - let galaxy = Galaxy::generate_new(); + let mut galaxy = Galaxy::generate_new(); // init ops, starting state and notes commands::short_range_scan(&galaxy); loop { match prompt("Command?").as_str() { "SRS" => commands::short_range_scan(&galaxy), + "NAV" => gather_dir_and_speed_then_move(&mut galaxy), _ => print_command_help() } @@ -25,11 +29,31 @@ fn main() { } } -fn prompt(prompt: &str) -> String { +fn gather_dir_and_speed_then_move(galaxy: &mut Galaxy) { + let dir = prompt_value::("Course (1-9)?", 1, 9); + if dir.is_none() { + println!("{}", BAD_NAV); + return; + } + + let speed = prompt_value::("Course (1-9)?", 0.0, 8.0); + if speed.is_none() { + println!("{}", BAD_NAV); + return; + } + + let distance = (speed.unwrap() * 8.0) as i32; + // could be done with a step function - while distance > 0, move by digit. + // if passing a boundary, test for the next quadrant in that direction + // if present, change quadrant and move to border + // else stop. +} + +fn prompt(prompt_text: &str) -> String { let stdin = stdin(); let mut stdout = stdout(); - print!("{prompt} "); + print!("{prompt_text} "); let _ = stdout.flush(); let mut buffer = String::new(); @@ -39,11 +63,15 @@ fn prompt(prompt: &str) -> String { "".into() } +fn prompt_value(prompt_text: &str, min: T, max: T) -> Option { + let passed = prompt(prompt_text); + match passed.parse::() { + Ok(n) if (n >= min && n <= max) => Some(n), + _ => None + } +} + fn print_command_help() { println!("valid commands are just SRS and NAV at the mo") } -// match text.parse::() { -// Ok(n) if (n >= 1 && n <= 8) => Some(Message::DirectionForNav(n)), -// _ => None -// } \ No newline at end of file diff --git a/84_Super_Star_Trek/rust/src/text_constants.rs b/84_Super_Star_Trek/rust/src/text_constants.rs new file mode 100644 index 00000000..36339abe --- /dev/null +++ b/84_Super_Star_Trek/rust/src/text_constants.rs @@ -0,0 +1,2 @@ + +pub const BAD_NAV: &str = " Lt. Sulu reports, 'Incorrect course data, sir!'"; \ No newline at end of file