go语言编写程序石头
时间: 2024-06-28 16:00:45 浏览: 7
在Go语言中编写一个简单的"石头、剪刀、布"游戏(Rock, Paper, Scissors),你可以按照以下步骤进行:
1. 定义游戏规则:
- 石头打败剪刀 (rock beats scissors)
- 剪刀打败布 (scissors beats paper)
- 布打败石头 (paper beats rock)
2. 创建玩家和电脑的输入选择:
- 定义一个枚举类型(enum)或结构体(struct)来表示三种选择(石头、剪刀、布)。
```go
type Choice struct {
Name string
}
const (
Rock Choice = "rock"
Paper Choice = "paper"
Scissors Choice = "scissors"
)
```
3. 定义函数让玩家输入并验证选择:
- 创建一个函数接收用户输入,并返回对应的Choice类型。
```go
func getPlayerChoice() Choice {
var choice Choice
fmt.Println("Please choose: rock, paper, or scissors")
_, err := fmt.Scan(&choice.Name)
if err != nil || choice.Name != Rock && choice.Name != Paper && choice.Name != Scissors {
fmt.Println("Invalid choice, please try again.")
return getPlayerChoice()
}
return choice
}
```
4. 定义电脑随机选择:
- 使用Go的随机数包`math/rand`生成一个0到2之间的整数,对应于石头、剪刀、布。
```go
import (
"fmt"
"math/rand"
"time"
)
func getComputerChoice() Choice {
rand.Seed(time.Now().UnixNano())
return Choice{
Name: fmt.Sprintf("%v", randomNumToChoice[rand.Intn(len(randomNumToChoice))]),
}
}
```
5. 游戏循环和判断胜负:
- 在一个while循环中,不断让用户和电脑进行选择,然后比较结果并输出胜负。
```go
func main() {
randomNumToChoice := []string{Rock, Paper, Scissors}
for {
playerChoice := getPlayerChoice()
computerChoice := getComputerChoice()
fmt.Printf("Player chose %s, Computer chose %s\n", playerChoice.Name, computerChoice.Name)
if playerChoice.Name == computerChoice.Name {
fmt.Println("It's a tie!")
} else if (playerChoice.Name == Rock && computerChoice.Name == Scissors) ||
(playerChoice.Name == Paper && computerChoice.Name == Rock) ||
(playerChoice.Name == Scissors && computerChoice.Name == Paper) {
fmt.Println("You win!")
} else {
fmt.Println("You lose!")
}
// 添加更多选项或停止条件,如询问是否继续游戏等
}
}
```