我正在尝试创建一个保持得分的石头剪刀游戏,但是当我运行此程序时,每次都会重置分数。我需要改变什么才能保持得分?
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
print ""
p = raw_input("Type 'r' for rock, 'p' for paper or 's' for scissors: ")
choices = ['r', 'p', 's']
c = random.choice(choices)
print ""
print "Your move:", p
print "Computer's move:", c
print ""
if p == c:
print "Tie"
elif p == 'r' and c == 's':
playerScore += 1
print "You win"
elif p == 'p' and c == 'r':
playerScore += 1
print "You win"
elif p == 's' and c == 'p':
playerScore += 1
print "You win"
elif c == 'r' and p == 's':
computerScore += 1
print "You lose"
elif c == 'p' and p == 'r':
computerScore += 1
print "You lose"
elif c == 's' and p == 'p':
computerScore += 1
print "You lose"
else:
print "Try again"
print ""
print "Your score:", str(playerScore)+ ", Computer score:", str(computerScore)
while True:
rockPaperScissors()
答案 0 :(得分:2)
你在循环中调用该函数。该函数的第一件事是为分数创建一个局部变量。当功能结束时,该分数被丢弃。它不会通过多次调用持续存在。您应该返回新分数并将新值分配给计数器:
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
...
return playerScore, computerScore
player = 0
computer = 0
while True:
p, c = rockPaperScissors()
player += p
computer += c
print "Your score:", str(player)+ ", Computer score:", computer
答案 1 :(得分:0)
每次运行该功能时,您都会重置分数。在函数之外定义computerScore和playerScore,即使多次运行该函数,它也会保留这些值。使用global将全局变量“导入”到函数范围。
playerScore = 0
computerScore = 0
def rockPaperScissors ():
global playerScore
global computerScore
OTHER CODE