下面是我为自己制作的骰子游戏构建的代码。一旦退出游戏,我需要它来显示获胜次数和失败次数。一切运行顺利,但仅计算当前的最后结果。有什么想法吗?
import random
def roll_dice():
winner = 0
loser = 0
roll = (random.randint(1,6))
roll2 = (random.randint(1,6))
print(roll," "roll2)
if roll == roll2:
print("Winner!")
winner += 1
else:
print("Loser!")
loser += 1
play_again = input("Would you like to play again?")
if play_again == "yes":
roll_dice()
else:
print("You won " , winner , "times")
print("You lost ", loser , "times")
quit
def main():
game_start = input("Would you like to roll the dice?")
if game_start == 'yes':
roll_dice()
else:
print("too bad")
if __name__ == '__main__':
main()
答案 0 :(得分:3)
之所以发生这种情况,是因为您是变量的优胜者,而失败者是局部变量,并且每次调用roll_dice()时都将其初始化为零。您可以将赢家和输家作为全局变量,也可以将它们作为参数传递给函数。参见下面的全局变量
import random
winner = 0
loser = 0
def roll_dice():
global winner, loser
roll = (random.randint(1,6))
roll2 = (random.randint(1,6))
print(roll," ",roll2)
if roll == roll2:
print("Winner!")
winner += 1
else:
print("Loser!")
loser += 1
play_again = input("Would you like to play again?")
if play_again == "yes":
roll_dice()
else:
print("You won " , winner , "times")
print("You lost ", loser , "times")
quit
def main():
game_start = input("Would you like to roll the dice?")
if game_start == 'yes':
roll_dice()
else:
print("too bad")
if __name__ == '__main__':
main()
我还要指出,您不应在此处使用递归,因为它会导致堆栈溢出错误。循环将是一个更好的选择。
答案 1 :(得分:0)
这是因为winner
和loser
是局部变量,范围为对roll_dice
的调用。
每次调用都会实例化一个新变量loser
和winner
,并且该实例随函数的返回而消失。
更多Short description of the scoping rules?
一种解决问题的方法是在全局范围内制作winner
和loser
变量。
更干净的解决方案是重组代码,以使roll_dice
返回winner
和loser
的计数作为元组。
答案 2 :(得分:0)
每次调用function
(因为您将其作为递归进行调用)时,winner
和loser
的变量将变为zero
。我认为您需要在function
中更改def roll_dice()
。如@ ashutoshy.and01所述,最好使用looping
。
此外,如果只有两个骰子上的数字相等,就可以使玩家成为赢家,否则,即使玩家的骰子数大于计算机的骰子数,输家也会成为赢家。
def roll_dice():
winner = 0
loser = 0
play_again = "yes"
while play_again == "yes":
roll = (random.randint(1,6))
roll2 = (random.randint(1,6))
print(str(roll)," ",end=str(roll2))
if roll >= roll2:
print(" Winner!")
winner += 1
else:
print(" Loser!")
loser += 1
play_again = input("Would you like to play again?")
print("You won " , winner , "times")
print("You lost ", loser , "times")
quit