Python 简单的石头剪刀布游戏,有问题吗?
我正在为我的编程课写一个石头剪纸程序,在程序结束的时候要拿到满分有些问题。我是Python的超级初学者,所以这里没有什么特别的东西。出于某种原因,当我运行程序时,不管游戏循环多少次,唯一显示的分数是1。我做错了什么Python 简单的石头剪刀布游戏,有问题吗?,python,Python,我正在为我的编程课写一个石头剪纸程序,在程序结束的时候要拿到满分有些问题。我是Python的超级初学者,所以这里没有什么特别的东西。出于某种原因,当我运行程序时,不管游戏循环多少次,唯一显示的分数是1。我做错了什么 from myro import * from random import * def announceGame(): """ Announces the game to the user """ speak("Welcome to Rock, Paper, Sc
from myro import *
from random import *
def announceGame():
""" Announces the game to the user """
speak("Welcome to Rock, Paper, Scissors. I look forward to playing you.")
def computerMove():
""" Determines a random choice for the computer """
randomNumber = random()
if randomNumber == 1:
compMove = "R"
elif randomNumber == 2:
compMove = "P"
else:
compMove = "S"
return compMove
def userMove():
""" Asks the user to input their choice."""
userChoice = raw_input("Please enter R, P, or S: ")
return userChoice
def playGame(userChoice, compMove):
""" Compares the user's choice to the computer's choice, and decides who wins."""
global userWin
global compWin
global tie
userWin = 0
compWin = 0
tie = 0
if (userChoice == "R" and compMove == "S"):
userWin = userWin + 1
print "You win."
elif (userChoice == "R" and compMove == "P"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "R"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "P"):
userWin = userWin + 1
print "You win"
elif (userChoice == "P" and compMove == "S"):
compWin = compWin + 1
print "I win"
elif (userChoice == "P" and compMove == "R"):
userWin = userWin + 1
print "You win"
else:
tie = tie + 1
print "It's a tie"
return compWin, userWin, tie
def printResults(compWin, userWin, tie):
""" Prints the results at the end of the game. """
print " Rock Paper Scissors Results "
print "------------------------------------"
print "Computer Wins: " + str(compWin)
print "User Wins: " + str(userWin)
print "Ties: " + str(tie)
def main():
announceGame()
for game in range(1,6):
u = userMove()
c = computerMove()
game = playGame(u,c)
printResults(compWin, userWin, tie)
main()
在
playGame
中,您可以将userWin
、compWin
和tie
设置为零。因此,每次调用该函数时,它们都会在添加新值之前设置为零。您应该在循环中调用的函数之外初始化这些变量。(例如,您可以在announceGame
中初始化它们)我确实将这段代码移到了announceGame()函数中,但是它仍然会出现0或者告诉我在赋值之前已经引用了局部变量?如果您想从该函数引用全局变量,您仍然需要在playGame
中包含global
语句。如果你想保留它们的值,就不应该将它们设置为零。在你学习Python的过程中,试着重新构造你的代码,去掉那些global
语句。