Go语言实现的石头剪刀布游戏
时间:2024-03-06
浏览:103
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《Go语言实现的石头剪刀布游戏》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
我们的项目是使用 go 制作一款实用的剪刀石头布游戏。我认为这是一个很好的地方,可以就我可能犯的一些明显错误寻求一些指导。
我遇到了几个问题。
- 无论用户输入什么,程序都会说我总是输入“rock”。
- 无论我输入什么,程序总是告诉我这是一个“平局”
所以对我来说很明显我的 if/else 语句有问题,但我不确定它在哪里以及到底是什么。我也知道我的 playerplay 函数很丑陋,但由于某种原因,当我最初在那里放置显示菜单时,它会继续循环回到我的菜单,而不继续执行程序的其余部分。
package main
import (
"fmt"
"math/rand"
"time"
)
func ComputerPlay() int {
return rand.Intn(2) + 1
}
func PlayerPlay(play int) int {
fmt.Scanln(&play)
return play
}
func PrintPlay(playerName string, play int) {
fmt.Printf("%s picked ", playerName)
if play == 0 {
fmt.Printf("rock\n")
} else if play == 1 {
fmt.Printf("paper\n")
} else if play == 2 {
fmt.Printf("scissors\n")
}
fmt.Printf("Computer has chose ")
switch ComputerPlay() {
case 0:
fmt.Println("rock\n")
case 1:
fmt.Println("paper\n")
case 2:
fmt.Println("scissors\n")
}
}
func ShowResult(computerPlay int, humanPlay int){
var play int
computerPlay = ComputerPlay()
humanPlay = PlayerPlay(play)
if humanPlay == 0 && humanPlay == 0 {
fmt.Printf("It's a tie\n")
} else if humanPlay == 0 && computerPlay == 1 {
fmt.Printf(" Rock loses to paper\n")
} else if humanPlay == 0 && computerPlay == 2 {
fmt.Printf("Rock beats scissors\n")
} else if humanPlay == 1 && computerPlay == 0 {
fmt.Printf(" Paper beats rock\n")
} else if humanPlay == 1 && computerPlay == 1 {
fmt.Printf("It's a tie!\n")
} else if humanPlay == 1 && computerPlay == 2 {
fmt.Printf("Paper loses to scissors\n")
} else if humanPlay == 2 && computerPlay == 0 {
fmt.Printf("Scissors loses to rock\n")
} else if humanPlay == 2 && computerPlay == 1 {
fmt.Printf(" Scissors beats paper\n")
} else if humanPlay == 2 && computerPlay == 2 {
fmt.Printf(" It's a tie!\n")
}
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Printf("Welcome to Rock, Paper, Scissors\n\n")
fmt.Printf("What is your name?\n")
var playerName string
fmt.Scanln(&playerName)
fmt.Printf("Choose\n")
fmt.Printf("0. Rock\n")
fmt.Printf("1. paper\n")
fmt.Printf("2. scissors\n")
fmt.Printf("Your choice -> ")
var play int
PlayerPlay(play)
PrintPlay(playerName, play)
var computerPlay int
ComputerPlay()
ShowResult(computerPlay, play)
}解决方案
问题在于您在 playerplay 函数中使用按值传递参数而不是按引用传递参数。
golang 中的函数始终按值传递(“原始”或指针)。按值传递的参数是不可变的。它将在内存中分配新的空间,与
var play不同。在
playerplay()函数中,fmt.scanln(&play)尝试读取并复制新分配的空间的值并成功执行此操作,但出现错误参考(不在您的var play上)。因此,
var play变量将保持其默认值不变(对于 int 为 0)。你最终总是会做出选择。
您需要做的是将 playerplay() 函数更改为接受引用类型,并用 var play 的引用填充它,以便 fmt.scanln() 可以改变 var play 。
例如。
func playerplay(play *int) {
fmt.scanln(play)
}
像这样使用它们,
var play int PlayerPlay(&play)
注意 & 符号用于获取值的引用(指针)。
到这里,我们也就讲完了《Go语言实现的石头剪刀布游戏》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
