需要帮助修复随机数

问题描述 投票:-1回答:2

我正在学习Python,正在研究随机掷骰子。当我运行它时,它会重复显示在询问您是否要再次播放后首次显示的相同数字。我需要帮助找到我在这里出错的地方。

我已经尝试过移动代码并且还使用不同种类的代码。我只是难过。

import sys
import random
import time


greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
die = random.randint(0, 6)

print(greeting)
time.sleep(2)

answer = input("Want to play?")

while answer == "yes" or answer == "y":
    print(roll)
    time.sleep(2)
    print(die)
    answer = input("Want to play again?")
print("Thanks for playing!")

这就是我得到的:

Welcome to my Dice Game!
Want to play?yes
Lets roll this die!
5
Want to play again?yes
Lets roll this die!
5
Want to play again?y
Lets roll this die!
5
python random while-loop dice
2个回答
2
投票

你需要每次在循环中重新计算骰子的值,如:

import sys
import random
import time


greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"


print(greeting)
time.sleep(2)

answer = input("Want to play?")

while answer == "yes" or answer == "y":
    print(roll)
    time.sleep(2)
    die = random.randint(0, 6) # recompute it here instead
    print(die)
    answer = input("Want to play again?")
print("Thanks for playing!")

1
投票

当你运行命令die = random.randint(0, 6)时,你告诉Python的是“使用random.randint()函数来选择1到6之间的随机整数,然后将名为die的变量设置为等于所选择的整数”。完成后,其余代码不会更新die的值。这意味着循环中的print(die)将继续打印最初给出的任何值。换句话说,命令die = random.randint(0, 6)并不意味着“重新运行命令random.randint(0, 6)并在每次引用die时获取另一个随机数”。相反,die只是一个具有特定恒定值的变量。

由于random.randint()是实际数字生成的原因,继续更新die的一种方法是简单地将循环外的命令移动到循环内部:

while answer == "yes" or answer == "y":
    print(roll)
    die = random.randint(0, 6) # Generate a new random number, then assign it to 'die'
    time.sleep(2)
    print(die)
    answer = input("Want to play again?")

事实上,如果你没有真正使用除打印之外的数字做任何事情,你可能会完全忘记使用变量,只需在你的random.randint()命令中粘贴print命令:

while answer == "yes" or answer == "y":
    print(roll)
    time.sleep(2)
    print(random.randint(0, 6))
    answer = input("Want to play again?")
© www.soinside.com 2019 - 2024. All rights reserved.