A complete beginner’s guide
Concept
The player will guess a number between 0 and 10. If their guess is correct, they win. Otherwise, the program will give the player a hint to either guess higher or lower depending on the correct number. The player will have three(3) shots at the game; if he guesses incorrectly three(3) times, the game would end.
Golang
Simply put, Go is an open-source programming language that makes it easy to build simple, reliable, and efficient software.
In this piece, you will learn how to make a simple guessing game in Golang.
Getting Started With Golang.
To start with, you will need to install Golang on your computer. If you don’t already have it installed, you can do this from the Golang website.
Once you are done with the installation, open the CMD on Windows, Terminal on Mac, and Linux. Then change directory “cd” to the folder you want to store your guessing game in.
Create the directory for your guessing game
mkdir Guess
Move into the new Guess directory
cd Guess
Initialize your project with a go.mod file. Ensure you replace the string ‘username‘ with your Github username.
go mod init github.com/username/Guess
Create a new file named guess.go
touch guess.go
You have now successfully installed ‘go’ and also set up your guessing game file.
Now, open the guess.go file with a text/code editor on your device. I use VS Code. Windows comes with Notepad pre-installed. Mac OS includes TextEdit. Linux users can use Vim. You can also download other text editors like sublime text or atom.
Creating the Guessing game
The instructions for this tutorial will be included in the code itself as comments. In Golang, you make comments with double forward slashes.
Note: A clean code without comments is included below if you just want to jump straight at the game.
// The first statement in a go source file must start with a package “name”. All the functions declared in this program become part of the declared package. Go programs start running in the main package. This tells the Go compiler to compile the package as an executable program.
//An Executable simply means a file that contains a program that is capable of being executed or run as a program on your computer.
package main
import (
“fmt” // import the fmt package which allows you to use text
//formatting, reading input & printing output functions
“math/rand” //import the rand package which allows you to
//generate random numbers
“time” // import the package which will provide time functionality to measure time
)
func main() {
fmt.Println(“Game: Guess a number between 0 and 10”)
// This informs the player about how to play the game.
fmt.Println(“You have three(3) tries “)
// generate a random number
source := rand.NewSource(time.Now().UnixNano())
//The default number generator is predictable, so it will produce the same sequence of numbers each time. To produce a varying range of numbers, give it a seed that changes (in this case: time would ensure it changes ). Note that this is not safe to use for random numbers you want to be secret; use crypto/rand for those.
randomizer := rand.New(source)
secretNumber := randomizer.Intn(10)
// generate numbers between 0 and 10 only. If you want to change the range change the value 10 to a higher or lower value
var guess int
// this is one form of declaration in go; you have to add the type of the variable been declared. “var guess” won't work
for try := 1; try <= 3; try++ {
// declaring the conditions for the for loop ; the shorthand form of declaring a variable was used here. Declare and Initialize ‘ := ‘ you declare and assign a value upon declaration. Go will automatically infer the type of the variable since you already assigned a value to it.
fmt.Printf(“TRIAL %d\n”, try)
// print out the number of times the player has made a guess
fmt.Println(“Please enter your number”)
// the program will prompt the player to make a guess and enter a number
fmt.Scan(&guess)
// this function makes it possible for the program to receive the input
if guess < secretNumber {
// if the guessed number is less than or greater than the correct number; give the player a hint
fmt.Printf(“Sorry, wrong guess ; number is too small\n “)
} else if guess > secretNumber {
fmt.Printf(“Sorry, wrong guess ; number is too large\n “)
} else {
fmt.Printf(“You win!\n”)
break
// Print out "you win" message when the player guesses the correct number
}
if try == 3 {
// if the number of tries is equal to 3, print game over and also the correct number
fmt.Printf(“Game over!!\n “)
fmt.Printf(“The correct number is %d\n”, secretNumber)
break
}
}
}
Once you are done editing, save the program. Also, you can change whatever you want in your program. For example, you could increase the guessing range of numbers from 10 to 100. You could change the program’s response to the player’s actions in the printLn() functions. You can do whatever you want, the game is yours now🤗.
Running Your Program
Open up the terminal of your VS code or command prompt (Windows/Linux) or the terminal (Mac), depending on the choice of text editor you made above. Ensure you are still in the guessing game directory you created above. If you are not, navigate to the guessing game directory using the command below;
cd
There are two methods that you can use to run your guessing game. Build or Run. Use either of the two.
1- Build
Type the following command
go build guess.go
You should see a new file in your guess directory(folder) named ‘‘guess’’
Then run
./guess
2- Run
Type the following command
go run guess.go
Regardless of the method, you went with above; Your game should be running now. Once your program is running, test it out! Play around with it a few times. Have fun !!
If you have any questions about this tutorial, feel free to drop it as a comment or send me a message on LinkedIn or Twitter and I will try my best to help you out.
Below is a version of the code without comments.
package main
import (
“fmt”
“math/rand”
“time”
)
func main() {
fmt.Println(“Game: Guess a number between 0 and 10”)
fmt.Println(“You have three(3) tries “)
source := rand.NewSource(time.Now().UnixNano())
randomizer := rand.New(source)
secretNumber := randomizer.Intn(10)
var guess int
for try := 1; try <= 3; try++ {
fmt.Printf(“TRIAL %d\n”, try)
fmt.Println(“Please enter your number”)
fmt.Scan(&guess)
if guess < secretNumber {
fmt.Printf(“Sorry, wrong guess ; number is too small\n “)
} else if guess > secretNumber {
fmt.Printf(“Sorry, wrong guess ; number is too large\n “)
} else {
fmt.Printf(“You win!\n”)
break
}
if try == 3 {
fmt.Printf(“Game over!!\n “)
fmt.Printf(“The correct number is %d\n”, secretNumber)
break
}
}
}
Bonus: If you are using VS code, you can open the IDE from your terminal by typing this simple command
code
Note: you must have installed this in your path. To do this, press CMD + SHIFT + P, type shell command, and select Install code command in path
Top comments (0)