How to implement a number guessing game using Go langua…

Here is an example code of implementing a number guessing game using the Go language.

package main

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

func main() {
	// 生成随机数
	rand.Seed(time.Now().UnixNano())
	target := rand.Intn(100)

	// 提示玩家猜数字
	fmt.Println("猜数字游戏开始!")
	fmt.Println("请输入一个0到100之间的整数:")

	// 循环判断猜测结果
	for {
		var guess int
		fmt.Scan(&guess)

		if guess < target {
			fmt.Println("太小了,请继续猜测:")
		} else if guess > target {
			fmt.Println("太大了,请继续猜测:")
		} else {
			fmt.Println("猜对了!")
			break
		}
	}
}

The above code first initializes the random number seed using rand.Seed(time.Now().UnixNano()), and then generates a random integer between 0 and 99 as the target number using rand.Intn(100).

Next, continuously prompt the player to input their guess using fmt.Scan(&guess), compare the input with the target number, and output the corresponding hint. If the guess is correct, output “Correct!” and end the loop.

Please note that this is just a simple example and does not include comprehensive input validation and other processing. In real applications, it may be necessary to validate input, provide more guidance, and handle exceptions.

bannerAds