98 lines
2.6 KiB
Rust
98 lines
2.6 KiB
Rust
// Copyright (c) 2022 Emma Tebibyte
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
/* Bingame is free software: you can redistribute it and/or modify it
|
|
* under the terms of the GNU Affero General Public License as published by the
|
|
* Free Software Foundation, either version 3 of the License, or (at your
|
|
* option) any later version.
|
|
*
|
|
* Bingame is distributed in the hope that it will be useful, but WITHOUT
|
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
* details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
* along with this program. If not, see https://www.gnu.org/licenses/.
|
|
*/
|
|
|
|
use rand::Rng;
|
|
use std::cmp::Ordering;
|
|
|
|
fn parse_input() -> Option<u32> {
|
|
loop {
|
|
let mut input = String::new();
|
|
std::io::stdin()
|
|
.read_line(&mut input)
|
|
.unwrap();
|
|
|
|
match input.trim().parse::<u32>() {
|
|
Ok(output) => return Some(output),
|
|
Err(_) => {
|
|
match input.trim() {
|
|
"quit" | ":q" | "q" | "stop" | "exit" => {
|
|
println!("Stopping...");
|
|
return None;
|
|
},
|
|
_ => eprintln!("{} is not a number!", input),
|
|
};
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
println!("Welcome to bingame! Type \"quit\" anytime to stop playing.
|
|
Provide an upward limit for generated numbers:");
|
|
|
|
let limit = match parse_input() {
|
|
Some(limit) => limit,
|
|
None => std::process::exit(0),
|
|
};
|
|
game(limit)
|
|
}
|
|
|
|
fn numgen(limit: u32) -> Result<(u32, u32), bool> {
|
|
// generate random number
|
|
let nombre: u32 = rand::thread_rng().gen_range(0..limit);
|
|
|
|
// convert number from decimal to binary notation
|
|
let mut binvec = vec![];
|
|
let mut countdown = nombre;
|
|
while countdown > 0 {
|
|
binvec.push(countdown % 2);
|
|
countdown /= 2;
|
|
}
|
|
|
|
let mut binnery = String::new();
|
|
for i in binvec { binnery = i.to_string() + &binnery; }
|
|
|
|
let binnery = binnery.parse::<u32>();
|
|
|
|
let binary = match binnery {
|
|
Ok(binary) => binary,
|
|
Err(_) => std::process::abort(),
|
|
};
|
|
return Ok((nombre, binary));
|
|
}
|
|
|
|
fn game(limit: u32) {
|
|
loop {
|
|
let ans = numgen(limit).unwrap();
|
|
println!("Type {} in binary", ans.0);
|
|
|
|
let guess = match parse_input() {
|
|
Some(guess) => guess,
|
|
None => std::process::exit(0),
|
|
};
|
|
|
|
match guess.cmp(&ans.1) {
|
|
Ordering::Equal => {
|
|
println!("That's correct! {} in binary is {}!", ans.0, ans.1);
|
|
},
|
|
Ordering::Greater | Ordering::Less => {
|
|
println!("Nope! {} in binary is {}!", ans.0, ans.1);
|
|
},
|
|
};
|
|
}
|
|
}
|