Introduction
This program is a fun and interactive game where the computer selects a random number, and the user attempts to guess it.
It’s an excellent way to learn Go programming, practice using libraries, and understand conditional statements.
Objective
The objective of this project is to develop a simple yet engaging number guessing game to improve problem-solving skills
and familiarity with Go programming concepts such as random number generation, loops, and user input handling.
Code
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
func main() {
// Initialize the random seed
rand.Seed(time.Now().UnixNano())
// Generate a random number between 1 and 100
target := rand.Intn(100) + 1
fmt.Println("Welcome to the Number Guessing Game!")
fmt.Println("I have selected a number between 1 and 100. Can you guess it?")
// Scanner for user input
reader := bufio.NewReader(os.Stdin)
for attempts := 1; ; attempts++ {
fmt.Printf("Attempt %d: Enter your guess: ", attempts)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input. Please try again.")
continue
}
// Convert input to integer
guess, err := strconv.Atoi(input[:len(input)-1])
if err != nil {
fmt.Println("Invalid input. Please enter a number.")
continue
}
// Check the user's guess
if guess < target { fmt.Println("Too low!") } else if guess > target {
fmt.Println("Too high!")
} else {
fmt.Printf("Congratulations! You've guessed the number in %d attempts.\n", attempts)
break
}
}
}
Explanation
The program is structured as follows:
- Random Number Generation: The
math/rand
package is used to generate a random number
between 1 and 100. - User Input: The
bufio
andos
packages are used to read input from the user,
which is then converted to an integer using thestrconv
package. - Game Loop: A loop is used to repeatedly prompt the user for guesses until the correct number is guessed.
- Conditional Statements: If-else conditions compare the user’s guess with the target number and provide
feedback (“Too low”, “Too high”, or “Correct”).
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
guessing_game.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run guessing_game.go
- Follow the on-screen instructions to play the game.