[英]What could be causing my program to go over a function twice even though it should be exiting after running over it once?
我正在尝试制作一个石头、纸、剪刀的游戏,但我无法弄清楚为什么我的程序在 function 上重复了两次,而它应该在 go 上重复一次,然后由于一段while
又从头开始环形。
这是导致问题的 function(过滤掉了不必要的信息):
def playRps(): # Compares the choices and determines who won the game
game = "".join([playerAction, computerAction])
outcomes = {
"rr": tied,
"pp": tied,
"ss": tied,
"rp": playerLoss,
"ps": playerLoss,
"sr": playerLoss,
"rs": playerWin,
"pr": playerWin,
"sp": playerWin,
}
if playerAction == "q":
return False
else:
action = outcomes.get(game)
if action:
action()
else:
print("Invalid input!")
您可以在此处找到整个functions.py
文件。
这是调用函数并运行程序的main.py
文件(过滤掉不必要的信息):
while True:
if functions.playerScore != 0 or functions.computerScore != 0:
functions.scores()
playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))
if playGame == "y":
while True:
functions.playerChoice()
functions.computerChoice()
functions.playRps()
if not functions.playRps():
break
elif playGame == "n":
print("Terminating program...")
quit()
else:
print("Unknown input. Please enter a valid answer.")
continue
您可以在此处找到整个main.py
文件。
好吧,当您不输入q
时,该程序按预期在functions.py
中显示为 go 到actions = outcome.get(game)
。 然后,它转到main.py
文件并在if not functions.playRps():
处验证结果。
出于某种原因,它然后继续到 go回到functions.py
并最终回到actions = outcome.get(game)
,这增加了第二点。 然后它返回到main.py
,然后在if not functions.playRps():
之后立即break
。
当我没有输入q
作为玩家响应时,它不应该重复playRps()
两次,也不应该在main.py
中break
。 由于while
循环,它应该 go回到main.py 中的main.py
playerChoice()
function,因此玩家可以做出选择。
除非玩家在调用 playerChoice playerChoice()
function 时输入q
,否则main.py
中的while
循环根本不应该被破坏。
我对你们的问题是:
playRps()
function 两次,为什么在调用 playerChoice playerChoice()
function 时播放器从未输入q
时调用函数的main.py
中的while
循环被破坏? 第二次调用 function 因为您在if statement
中再次调用 function :
functions.playRps() # call 1
if not functions.playRps(): # call 2
break
您应该为该 function 的结果设置一个变量,以便您可以在if statement
中对其进行评估而无需再次调用它:
result = functions.playRps()
if not result:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.