![](/img/trans.png)
[英]How to restart a pygame game with user input and also keep record of score?
[英]How to restart my game with user input of 'y'? Created a user defined function for after-game
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)
这里的问题是, i
在done()
函数是指可变i
正被由deafult功能局部声明的,而不是全局变量i
宣布你的程序的开始。 要解决此问题,增加global i
在你done()
之前的功能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()
函数中的有效移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.