0
我正在爲我的編程課寫這個Rock Paper Scissors程序,並且在程序結束時出現了一些問題,讓它們顯示出滿分。我是Python的超級初學者,所以在這裏沒什麼特別的。出於某種原因,當我運行該程序時,無論遊戲循環多少次,唯一顯示的分數爲1。我在這裏做錯了什麼?簡單的岩石紙剪刀遊戲,迴歸分數的問題?
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()
我沒有將這段代碼移動到announceGame()函數,但它仍然與0或告訴我的本地變量已被引用前賦值? – user1473879
如果你想引用來自該函數的全局變量,你仍然需要在'playGame'中包含'global'語句。如果你想保持它們的值,你不應該將它們設置爲零。 – BrenBarn
啊,非常感謝:)現在工作得很好 – user1473879