gpt4 book ai didi

python - 变量未记录值的变化

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:10 26 4
gpt4 key购买 nike

我想用 Python 制作一个简单的剪刀石头布游戏。游戏进行的很顺利,但是最后的分数总是显示为0。

我想展示一小部分代码,但我不知道问题出在哪里,所以对于代码的长度,我深表歉意。

我还是个小白,如果问题太傻或者代码格式不好请见谅。

#Rock-Paper-Scissor Game
import random


print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")

userTally = 0
compTally = 0

def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])

if userInput == "R": #User Inputs R for Rock

if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1

elif userInput == "P": #User Inputs P for Paper

if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1

elif userInput == "S": #User Inputs S for Scissor

if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)

def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:

gameProcess(0, 0)
tryNum = tryNum + 1

tryCount()


print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()

最佳答案

您将 0, 0 传递给 gameProcess,您将其视为函数内的分数,然后将它们修改后返回,但您实际上并没有在调用 的唯一地方使用返回值strong>gameProcess(在tryCount),所以全局userTally,compTally变量保持不变。

这是您应该如何更改 tryCount:

def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:

userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1

关于python - 变量未记录值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com