golang猜拳游戏并比较谁赢得多
时间: 2023-07-26 22:10:33 浏览: 37
以下是一个简单的猜拳游戏,并比较谁赢得多的示例代码:
```go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var playerScore, computerScore int
rand.Seed(time.Now().UnixNano())
for i := 0; i < 10; i++ {
fmt.Println("Round", i+1)
playerChoice := getPlayerChoice()
computerChoice := getComputerChoice()
result := compareChoices(playerChoice, computerChoice)
if result == "win" {
playerScore++
fmt.Printf("You win! (%s vs %s)\n", playerChoice, computerChoice)
} else if result == "lose" {
computerScore++
fmt.Printf("You lose! (%s vs %s)\n", playerChoice, computerChoice)
} else {
fmt.Printf("Tie game! (%s vs %s)\n", playerChoice, computerChoice)
}
}
fmt.Println("Final score:")
fmt.Printf("You: %d\nComputer: %d\n", playerScore, computerScore)
if playerScore > computerScore {
fmt.Println("You win!")
} else if playerScore < computerScore {
fmt.Println("You lose!")
} else {
fmt.Println("Tie game!")
}
}
func getPlayerChoice() string {
var choice string
for {
fmt.Print("Enter your choice (rock/paper/scissors): ")
fmt.Scanln(&choice)
if choice == "rock" || choice == "paper" || choice == "scissors" {
return choice
}
fmt.Println("Invalid choice. Please try again.")
}
}
func getComputerChoice() string {
choices := []string{"rock", "paper", "scissors"}
return choices[rand.Intn(len(choices))]
}
func compareChoices(playerChoice, computerChoice string) string {
if playerChoice == computerChoice {
return "tie"
} else if playerChoice == "rock" && computerChoice == "scissors" ||
playerChoice == "paper" && computerChoice == "rock" ||
playerChoice == "scissors" && computerChoice == "paper" {
return "win"
} else {
return "lose"
}
}
```
在此示例中,我们使用 `rand` 包生成计算机的选择,并使用 `time` 包设置随机种子以获得更好的随机性。我们循环进行10轮比赛,并且记录每个玩家的得分。最后我们比较两个玩家的得分,以确定谁赢得了比赛。
要玩这个游戏,请运行程序并按照提示输入您的选择。程序将显示每个回合的结果以及最终得分和比赛结果。