File tree Expand file tree Collapse file tree 4 files changed +194
-0
lines changed
Expand file tree Collapse file tree 4 files changed +194
-0
lines changed Original file line number Diff line number Diff line change 1+ /target
Original file line number Diff line number Diff line change 1+ [package ]
2+ name = " guessing_game"
3+ version = " 0.1.0"
4+ edition = " 2021"
5+
6+ [dependencies ]
7+ rand = " 0.8.5"
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments