Go语言实现猜数字小游戏

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

目录

前言

一、设计思路

二、代码编写

2.1 产生随机数

2.2 用户输入数据

2.3  核心代码

三、 全部代码

四、效果图

总结


前言

最近在学习go语言刚刚学完go语言的基础语法。编写了一个猜数字的小游戏来练习循环、分支语句、变量定义、输入输出等基础的go语言语法。为使今后的学习过程中更加对基础知识点掌握的更加牢固。


一、设计思路

     1. 首先程序随机生成一个100以内的整数然后等待用户的输入。
     2. 如果用户输入的是一个整数则转到下一步否则显示错误提示信息并重新输入。
     3. 如果用户输入的整数比随机数大程序提示“Your guess is bigger than the secret number. Please try again”。
     4. 如果用户输入的整数比随机数小程序提示“Your guess is smaller than the secret number. Please try again”。
     5. 如果用户输入的整数与随机数相同程序提示“Correct, you Legend!”
     6. 如果用户猜的次数大于10次并且没有猜对程序提示“The number of times has reached the upper limit. Game failed”。

二、代码编写

2.1 产生随机数

使用时间戳产生随机种子得到一个随机生成的100以内的整数。

/**
	产生随机数
	*/
	maxNum := 100
	rand.Seed(time.Now().UnixNano())
	secretNumber := rand.Intn(maxNum)
	// fmt.Println("The secret number is ", secretNumber)
	fmt.Println("Please input your guess")

2.2 用户输入数据

\n是因为上一次输入会产生缓冲的空格trim是去掉左右空格。atoi是将字符串转为整数以便于进行比较。

fmt.Scanf("%s \n", &input)
input = strings.Trim(input, "\r\n")

guess, err := strconv.Atoi(input)

2.3  核心代码

比较数字的大小。

if guess > secretNumber {
			fmt.Println("Your guess is bigger than the secret number. Please try again count=", count)
		} else if guess < secretNumber {
			fmt.Println("Your guess is smaller than the secret number. Please try again count=", count)
		} else {
			fmt.Println("Correct, you Legend!")
			break
		}

三、 全部代码

package main

import (
	"fmt"
	"math/rand"
	"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")

	/**
	输入猜的数进行比较
	*/

	var input string
	var count = 0
	for {

		fmt.Scanf("%s \n", &input)
		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)

		count = count + 1
		if guess > secretNumber {
			fmt.Println("Your guess is bigger than the secret number. Please try again count=", count)
		} else if guess < secretNumber {
			fmt.Println("Your guess is smaller than the secret number. Please try again count=", count)
		} else {
			fmt.Println("Correct, you Legend!")
			break
		}

		if count == 10 {
			fmt.Println("The number of times has reached the upper limit. Game failed")
			break
		}
	}
}

四、效果图

 当用户猜的次数超过10次时会提示游戏失败跳出循环。如下图

 当输入非法字符时会有相应的提示信息。如下图所示

当用户在10次内猜对时提示信息如下图所示

 

总结

这就是本次练习的猜数字小游戏的全部代码及其演示过程。对于刚学习go语言的我来说对于基础知识点的掌握还是非常有帮助的。分享给大家一起学习有什么需要完善的地方还请在评论区讨论交流。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go