01_Go游戏-猜数字
package main import ( "fmt" "math/rand" "os" "time" ) func initRandNum(p *int) { rand.Seed(time.Now().UnixNano()) var num int for { num = rand.Intn(10000) if num >= 1000 { break } } *p = num } func initRandSlice(s []int, num int) { s[0] = num / 1000 s[1] = num % 1000 / 100 s[2] = num % 100 / 10 s[3] = num % 10 } func runGame(randSlice []int, userSlice []int) { var isRight bool = true for i := 0; i < len(userSlice); i++ { if userSlice[i] > randSlice[i] { fmt.Printf("第 %d 位猜大了\n", i) isRight = false } else if userSlice[i] < randSlice[i] { fmt.Printf("第 %d 位猜小了\n", i) isRight = false } else { fmt.Printf("第 %d 位猜对了\n", i) } } if isRight { fmt.Println("恭喜过关!") os.Exit(0) } } func main() { var randNum int randSlice := make([]int, 4) var userNum int userSlice := make([]int, 4) for { fmt.Println("************************************") fmt.Println(` 欢迎来到猜数字游戏 游戏要求: 1. 请输入一个四位数; 2. 不能输入非数字之外的字符 3. 输入0退出游戏 `) fmt.Println("************************************") initRandNum(&randNum) initRandSlice(randSlice, randNum) fmt.Printf("randSlice: %d\n", randSlice) fmt.Printf("请输入一个千位数字(0退出):") fmt.Scanln(&userNum) switch { case userNum >= 1000 && userNum <= 9999: initRandSlice(userSlice, userNum) runGame(randSlice, userSlice) case userNum == 0: os.Exit(1) default: fmt.Println("无效的输入") } } }