golang猜字谜游戏
时间: 2023-08-26 11:05:08 浏览: 129
以下是一个简单的猜字谜游戏的示例代码,使用Go语言实现:
```go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// 设置随机数种子
rand.Seed(time.Now().Unix())
// 定义谜底和谜面的数组
answers := []string{"apple", "banana", "orange", "grape", "watermelon"}
hints := []string{"It's a fruit and starts with 'a'.", "It's a fruit and curved.", "It's a fruit and round.", "It's a fruit and small.", "It's a fruit and big."}
// 随机选择一个谜底
answerIndex := rand.Intn(len(answers))
answer := answers[answerIndex]
hint := hints[answerIndex]
// 初始化猜测次数
guesses := 0
// 开始游戏
fmt.Println("Welcome to the Guessing Game!")
fmt.Println("I am thinking of a word. Can you guess what it is?")
for {
// 获取用户的猜测
var guess string
fmt.Print("Your guess: ")
fmt.Scanln(&guess)
// 比较猜测和谜底
if guess == answer {
guesses++
fmt.Printf("Congratulations! You guessed the word '%s' in %d guesses!\n", answer, guesses)
break
} else {
guesses++
fmt.Println("Sorry, that's not the word I'm thinking of.")
fmt.Println("Hint: ", hint)
}
}
}
```
该程序随机选择一个谜底,并提示用户猜测该谜底的单词。如果用户猜对了,程序会输出恭喜信息和猜测次数;否则程序会输出提示信息并继续等待用户猜测。
阅读全文