i=1
玩另一个或退出游戏
def done():
quitvalue=str(input("Play Again?(y/n):"))
if quitvalue=='n' and i==0:
SystemExit
elif quitvalue=="y":
i=1
#Loop to Restart Game
def rps(play1,play2):
#Check Winner of Game
if play1==play2:
print("It's a tie!")
done()
elif play1=='r':
if play2=='s':
print(play1name+" Wins!")
done()
else:
print(play2name+" Wins!")
done()
elif play1=='p':
if play2=='r':
print(play1name+" Wins!")
done()
else:
print(play2name+" Wins!")
done()
elif play1=='s':
if play2=='p':
print(play1name+" Wins!")
done()
else:
print(play2name+" Wins!")
done()
#Player Input
while i==1:
play1name=str(input("Player 1 Name?:"))
play2name=str(input("Player 2 Name?:"))
play1= str(input(play1name+" Choose Rock(r),Paper(p), Scissors(s):"))
play2= str(input(play2name+" Choose Rock(r),Paper(p), Scissors(s):"))
i=0
rps(play1,play2)
这里的问题是done()
函数中的i
是指由 deafult 在函数中本地声明的变量i
,而不是在程序开始时声明的全局变量i
。 若要解决此问题,请在引用i
之前在done()
函数中添加global i
:
def done():
global i
quitvalue=str(input("Play Again?(y/n):"))
if quitvalue=='n' and i==0:
SystemExit
elif quitvalue=="y":
i=1
你的意思是在你的done()
函数中raise SystemExit
退出吗?
如果是这样,则无需跟踪名称不明确的变量i
并处理范围问题。有关一些有用的解释,请参阅此处。
您还应该将玩家名称输入移出游戏循环,input()
将返回一个字符串。
我已经整理了代码并删除了一些不必要的重复部分。
def done():
"""Prompt user to continue or exit"""
quit_value = input("Play Again?(y/n): ").lower()
if quit_value == 'n':
raise SystemExit
def rps(play1, play2):
"""Play a single round of Rock, Paper, Scissors"""
# Check Winner of Game
if play1 == play2:
print("It's a tie!")
elif play1 == 'r':
if play2 == 's':
print(play1name + " Wins!")
else:
print(play2name + " Wins!")
elif play1 == 'p':
if play2 == 'r':
print(play1name + " Wins!")
else:
print(play2name + " Wins!")
elif play1 == 's':
if play2 == 'p':
print(play1name + " Wins!")
else:
print(play2name + " Wins!")
# get player names
play1name = input("Player 1 Name?: ")
play2name = input("Player 2 Name?: ")
# Player Input
while True: # done() exits the program, so loop forever
play1 = input(play1name + " Choose Rock(r),Paper(p), Scissors(s): ")
play2 = input(play2name + " Choose Rock(r),Paper(p), Scissors(s): ")
# resolve the plays
rps(play1, play2)
# check for a rematch
done()
您可能还需要在rps()
函数中检查有效的移动。