Created
September 23, 2021 13:53
-
-
Save aldy505/496765ed8ba66e1dac8d9b0ec60b31fb to your computer and use it in GitHub Desktop.
Rust's Guessing Game but written in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// The program will generate a random integer between 1 and 100. | |
// It will then prompt the player to enter a guess. | |
// After a guess is entered, the program will indicate whether the guess is too low or too high. | |
// If the guess is correct, the game will print a congratulatory message and exit. | |
import ( | |
"fmt" | |
"math/rand" | |
"os" | |
"time" | |
) | |
// Entrypoint | |
func main() { | |
// Seed the random number generator, so it will be different each time. | |
rand.Seed(time.Now().Unix()) | |
// Generate the random number. | |
randInteger := rand.Intn(50) | |
fmt.Println("Random number is: ", randInteger) | |
// Forever for loop, exits only if the number is guessed correctly. | |
for { | |
fmt.Print("Make your guess: ") | |
// Store input from stdin here | |
var inputInteger int | |
// _ means the variable would be ignored by the compiler and/or linter | |
_, err := fmt.Scan(&inputInteger) | |
if err != nil { | |
panic(err) | |
} | |
if inputInteger == randInteger { | |
break | |
} else if inputInteger > randInteger { | |
fmt.Println("Noo, the number is smaller than that.") | |
continue | |
} | |
// Not using else just because I want to demonstrate break and continue | |
fmt.Println("Not again, the number is bigger than that.") | |
} | |
fmt.Println("Congrats, chap, you've done it!") | |
// Not necessary to be honest. Just wanna show you that you have this option. | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment