首页 > 解决方案 > 我已经设置了一个 RNG 和一个继续按钮,但它不会在继续后更新结果

问题描述

#Setting up RNG
loop = "y"
while loop == "y" or loop == "yes":
    from random import randint
    dice = (randint(1,10))
    dice2 = (randint(1,10))
    roll = (dice + dice2)
    win = 3
    loss = 2
    cash = 20
    if roll == 3 or roll == 7 or roll == 11 or roll == 17:
        cash += (win)
    else:
        cash -= (loss)
    #Starting game
    print("""Welcome to, Gambling for School!

    You have $20 and must earn as much money as possible

    If you roll a 3, 7, 11, or 17, you will win $3 but any other number 
takes $2

    You have a 20% of winning
""")
    x = input("Press ENTER to start.")
    #Results
    if roll == 11 or roll == 8 or roll == 18:
        print("You rolled an " + str(roll) + "!")
    else:
        print("You rolled a " + str(roll) + "!")
    print("")
    print("Cash - $" + str(cash))
    loop = input("Continue? (Y/N) ").lower()

必须更改缩进以将其显示为代码

当它运行时,我按回车键开始游戏,它正确地加减,但是当我选择继续时,它就像我从来没有输过或赢过任何钱一样。如果我的大脑死了,现在是凌晨 1 点,但我想不出任何办法来解决它

标签: pythonpython-3.xrandom

解决方案


您在每场比赛前cash重新初始化变量。20要修复游戏,只需将该代码移出循环即可。

和的初始化 winloss可以移出循环,因为它们不会改变。

from random import randint语句也一样,将所有导入语句放在文件顶部被认为是一种好习惯。

from random import randint

#Setting up RNG
loop = "y"
win = 3
loss = 2
cash = 20
while loop == "y" or loop == "yes":
    dice = (randint(1,10))
    dice2 = (randint(1,10))
    roll = (dice + dice2)

    if roll == 3 or roll == 7 or roll == 11 or roll == 17:
        cash += win
    else:
        cash -= loss
    #Starting game
    print("""Welcome to, Gambling for School!

You have $20 and must earn as much money as possible

If you roll a 3, 7, 11, or 17, you will win $3 but any other number 
takes $2

You have a 20% of winning
""")
    x = input("Press ENTER to start.")
    #Results
    if roll == 11 or roll == 8 or roll == 18:
        print("You rolled an " + str(roll) + "!")
    else:
        print("You rolled a " + str(roll) + "!")
    print("")
    print("Cash - $" + str(cash))
    loop = input("Continue? (Y/N) ").lower()

推荐阅读