Skip to content

Commit 719e6f6

Browse files
committed
(base): finished game
0 parents  commit 719e6f6

File tree

4 files changed

+194
-0
lines changed

4 files changed

+194
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target

Cargo.lock

Lines changed: 140 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "guessing_game"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
rand = "0.8.5"

src/main.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Standard input/output
2+
use std::io;
3+
// Standard compare ordering
4+
use std::cmp::Ordering;
5+
// Random Random number generator
6+
use rand::Rng;
7+
8+
fn main() {
9+
println!("Guess the number !");
10+
11+
// Range expression: start..=end
12+
let secret_number = rand::thread_rng().gen_range(1..=100);
13+
14+
// Infinite loop
15+
loop {
16+
println!("Please input your guess: ");
17+
18+
// Mutable guess to new String = ""
19+
let mut guess = String::new();
20+
21+
22+
// User input and real line and write it to &guess and expect.
23+
io::stdin()
24+
.read_line(&mut guess)
25+
.expect("Failed to read line");
26+
27+
// Cast guess<string> to guess<u32> with a match.
28+
let guess: u32 = match guess.trim().parse() {
29+
Ok(num) => num,
30+
Err(_) => continue,
31+
};
32+
33+
println!("You guessed: {}", guess);
34+
35+
// Match compare guess & secret_number
36+
match guess.cmp(&secret_number) {
37+
Ordering::Less => println!("Too small!"),
38+
Ordering::Greater => println!("Too big!"),
39+
Ordering::Equal => {
40+
println!("You WIN !");
41+
// If player win, then exit the infinite loop.
42+
break;
43+
}
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)