Guessing Numbers in Go Language Practical Introductory Cases

Articles and codes have been archived in [Github warehouse: https://github.com/timerring/backend-tutorial ] or the public account [AIShareLab] can also be obtained by replying to go .

guess the number

In the first example, we will use Golang to build a guessing number game.

In this game, the program first generates a random integer between 1 and 100, and then prompts the player to guess. Each time the player enters a number, the program tells the player whether the guess is higher or lower than the secret random number, and asks the player to guess again. If the guess is correct, tell the player victory and exit the program.

package main

import (
	"fmt"
	"math/rand"
)

func main() {
    
    
	maxNum := 100
	secretNumber := rand.Intn(maxNum)
	fmt.Println("The secret number is ", secretNumber)
}

It can be found through experimentation that the random numbers generated each time are the same.

By looking at the documentation, it can be seen that the generation of random numbers uses a random seed.

Otherwise the same sequence of random numbers will be generated each time. Usually the startup timestamp is used to initialize the random number seed. Here use time.now.unixto initialize the random seed.

package main

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

func main() {
    
    
	maxNum := 100
	rand.Seed(time.Now().UnixNano())
	secretNumber := rand.Intn(maxNum)
	fmt.Println("The secret number is ", secretNumber)
}

Then implement user input and output, and parse it into numbers.

When each program is executed, several files will be opened, stdin stdout stderretc., and stdinthe files can be os.Stdinobtained. Then it is inconvenient to directly operate this file, we will use bufio.NewReader to convert a file into a readervariable.

readerThere are operations on the variable for manipulating streams, and its ReadStringmethods can be used to read a row. If it fails, it will print an error and be able to exit. ReadStringThe returned result contains a trailing newline character, which is removed and converted to a number. If the conversion fails, we also print an error and exit.

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
    
    
	maxNum := 100
	rand.Seed(time.Now().UnixNano())
	secretNumber := rand.Intn(maxNum)
	// fmt.Println("The secret number is ", secretNumber)

	fmt.Println("Please input your guess")
	reader := bufio.NewReader(os.Stdin)
	for {
    
    
		// `reader` 变量上有用来操作流的操作,可以用它的 `ReadString` 方法读取一行。
		input, err := reader.ReadString('\n')
		if err != nil {
    
    
			fmt.Println("An error occured while reading input. Please try again", err)
			continue
		}
		// `ReadString` 返回的结果包含结尾的换行符,把它去掉。
		input = strings.Trim(input, "\r\n")
		// 再转换成数字
		guess, err := strconv.Atoi(input)
		if err != nil {
    
    
			fmt.Println("Invalid input. Please enter an integer value")
			continue
		}
		fmt.Println("You guess is", guess)
		if guess > secretNumber {
    
    
			fmt.Println("Your guess is bigger than the secret number. Please try again")
		} else if guess < secretNumber {
    
    
			fmt.Println("Your guess is smaller than the secret number. Please try again")
		} else {
    
    
			fmt.Println("Correct, you Legend!")
			break
		}
	}
}

Reference: Byte Internal Course Go Language Principles and Practice

Guess you like

Origin blog.csdn.net/m0_52316372/article/details/132081133