A LITTLE CORNER OF MY WORLD

Read a few words, keep a little time

Every moment worth recording has a light of its own.

Back to all posts
Learn code

02 - Guess game in Go

Time to build a little guess game, we going to learn how to control flow, use loop and declare variables.

On this page
  1. Variable declaration
  2. Declare a random number
  3. Ask and capture the answer
  4. Compare the input with the random number
  5. The loop
  6. Final program

We are going to build a “Guess game” for the next step. It’s a classic game when you learn how to code. You can see an example of what is it here.

Before coding anything, just think of all the steps the program will need:

  • Create a random number, something between 0-100 to start.
  • The program will ask the user for a number, so we need to capture the answer
  • Create a loop for the program, the game quits when you find the right number.
  • Compare the answer with the random number, the program tells if the number is greater or lower

Variable declaration

In Go, you have two ways to declare a variable

var chaosNumber = 10; // normal way
chaosNumber := 10; // or shorter. Some people feel that the := operator is an ugly symbol

Avoid mixing = and :=. The := operator is used to declare a variable, while = assigns a value to a variable.

Declare a random number

There are two libraries in Go for this, math/rand and crypto/rand. I think the math/rand is the simplest for this program, so we are going to use that.

go doc math/rand
go doc rand.intln

So at this step, your program main.go would look like this:

package main
import ( "fmt"; "math/rand"; )

func main() {
randomNumber := rand.Intn(100) // generate a number between 0 and 100 (max)
fmt.Printf("Number is %d\n", randomNumber)
}

If you run the program two times, you should have two different numbers unless you are very lucky

go run main.go
go run main.go

Ask and capture the answer

To capture the answer, you need fmt.Scanln. Don’t hesitate to check with go doc

fmt.Println("Please enter a number between 1 and 100")
var input
fmt.Scanln(&input)
fmt.Printf("You entered %d", input)

In Go, when you start using random values (like the user input), you should check that the “Type” is correct or check for errors. Here we want an “Integer” (positive number) and nothing else, so instead, do this:

fmt.Println("Please enter a number between 1 and 100")
var input int
_, err := fmt.Scanln(&input) // use "_" when you don't need to use the variable
if err != nil { // if err is not "nil"
    fmt.Println("Error reading input: ", err)
    os.Exit(-1) // exit(-1) is bad, yeah really bad
}
if input > 100 || input < 0 {
    fmt.Println("Superior to 100 or a negative number")
    os.Exit(-1)
}

Compare the input with the random number

This part is “easy”, you just need some condition if {}

if input == chaosNumber { // == mean "equal"
    fmt.Printf("===You found the number %d===\n", chaosNumber)
    os.Exit(0) // Exit without error
}

if input > chaosNumber { // superior
    fmt.Printf("%d is too high\n", input)
}

if input < chaosNumber { // u know
    fmt.Printf("%d is too low\n", input)
}

The loop

For the loop, you can use a for {}:

for {
// You program logic here
}

Final program

Solution in 39 lines:

package main

import (
	"fmt"
	"math/rand"
	"os"
)

func main() {
	chaosNumber := rand.Intn(100)

	fmt.Println("===Hello th the GuessGame===")
	//fmt.Printf("Number is %d\n", chaosNumber)

	for {
		fmt.Println("Please enter a number between 1 and 100")
		var input int
		_, err := fmt.Scanln(&input)
		if err != nil { // if err is not "nil"
			fmt.Println("Error reading input: ", err)
			os.Exit(-1)
		}
		if input > 100 || input < 0 {
			fmt.Println("Superior to 100 or not Integer")
			os.Exit(-1)
		}

		if input == chaosNumber {
			fmt.Printf("===You found the number %d===\n", chaosNumber)
			os.Exit(0)
		}
		if input > chaosNumber {
			fmt.Printf("%d is too high\n", input)
		}
		if input < chaosNumber {
			fmt.Printf("%d is too low\n", input)
		}
	}
}

You can try to improve this program, count how many attempts you make before finding the right number, rewrite the code using functions, etc.

✿

Thank you for reading. I hope these words were useful.

Szorfein
Szorfein / Author

A little code, a little everyday life. Say hello in the guestbook. Guestbook