I am making a little rock paper scissors game in rust as a little mini-project while I learn the language. I have made the code below, but it seems that no matter what I do, it always prints "Invalid Response."
My current code:
fn start_next() {
thread::sleep(time::Duration::from_secs(3));
rps();
}
fn rps() {
let rk = String::from("rock");
let pp = String::from("paper");
let sc = String::from("scissors");
let end = String::from("end");
let mut guess = String::new();
println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");
io::stdin().read_line(&mut guess).expect("Unable to read line");
let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];
// debug
println!("\nAI chose {}", aichoice);
println!("You chose {}", guess);
if guess.eq_ignore_ascii_case(&rk) {
match aichoice {
"rock" => {
println!("Your moves canceled out.");
}
"paper" => {
println!("Paper defated your rock.");
}
"scissors" => {
println!("You defeated scissors");
}
_ => {}
}
start_next();
return;
}
if guess.eq_ignore_ascii_case(&pp) {
match aichoice {
"rock" => {
println!("You defeated rock.");
}
"paper" => {
println!("Your moves canceled out.");
}
"scissors" => {
println!("Scissors defeated your paper.");
}
_ => {}
}
start_next();
return;
}
if guess.eq_ignore_ascii_case(&sc) {
match aichoice {
"rock" => {
println!("Rock defeated your scissors.");
}
"paper" => {
println!("You defeated paper.");
}
"scissors" => {
println!("Your moves canceled out.");
}
_ => {}
}
start_next();
return;
}
if guess.eq_ignore_ascii_case(&end) {
return;
}
println!("Invalid response");
start_next();
}
(yes, ik this if chaining kind of sucks, but I am trying this because it wouldn't work with string.to_lowercase() and match)
I had previously, like I mentioned, tried to use a match case statement to do it, but it had the same results.
My previous code was something like this:
let mut guess = String::new();
println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");
io::stdin().read_line(&mut guess).expect("Unable to read line");
let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];
let guess2: &str = &*guess.to_lowercase();
match guess2 {
case "rock" => {
...
}
case "paper" => {
...
}
case "scissors" => {
...
}
case "end" => {
return;
}
case _ => {
println!("Invalid Response");
}
}
thread::sleep(time::Duration::from_secs(3));
rps();
My guess is I either made some random mistake both times or have something wrong with my Rust installation.
I also tested with my previous code and to_lowercase()
was working, just something with comparing strings that I don't understand.