我正在用python制作一个简单的摇滚,纸张,剪刀游戏 - 并且计数器变量出现错误,我或我的计算机科学似乎都无法放置。
import random
options = ["R", "P", "S"]
userwin = 0
computerwin = 0
counter = 0
def RPS():
counter = counter + 1
computerchoice = random.choice(options)
print ("It's round number", counter, "!")
humanchoice = input ("Do you choose rock [R], paper [P] or scissors[S]?")
if computerchoice == "R":
if humanchoice == "R":
print ("Rock grinds rock - it's a draw!")
if humanchoice == "P":
print ("Paper wraps rock - you win!")
userwin = userwin + 1
if humanchoice == "S":
print ("Rock blunts scissors - you lost!")
computerwin = computerwin + 1
if computerchoice == "S":
if humanchoice == "S":
print ("Scissors strikes scissors - it's a draw!")
if humanchoice == "R":
print ("Rock blunts scissors - you win!")
userwin = userwin + 1
if humanchoice == "P":
print ("Scissors cuts paper - you lost!")
computerwin = computerwin + 1
if computerchoice == "P":
if humanchoice == "P":
print ("Paper folds paper - it's a draw!")
if humanchoice == "S":
print ("Scissors cuts paper - you win!")
userwin = userwin + 1
if humanchoice == "S":
print ("Paper wraps scissors - you lost!")
computerwin = computerwin + 1
while userwin < 10 or computerwin < 10:
RPS()
出现的错误是
counter = counter + 1
UnboundLocalError: local variable 'counter' referenced before assignment
我之前没有遇到过这个错误 - 我不确定如何修复它。有任何想法吗?谢谢!
答案 0 :(得分:1)
您无法在函数中分配全局变量,您需要这样做:
def RPS():
global counter
counter = counter + 1
computerchoice = random.choice(options)
您必须为在函数外定义的每个变量执行此操作。