每个循环后的随机数都是相同的

2024-10-02 02:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序应该为每一个骰子显示一对骰子,这是按计划进行的。我想它重复多次,但每次重复它不再是随机的,只是重复从第2行和第3行分配的数字。如果我掷2和3,它每次都重复2和3。 如何使它每次循环时都分配一个新的随机数?你知道吗

import random
dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6)

。。。[编辑:]

visualdice_1 =( """
            +-------+
            |       |
            |   *   |
            |       |
            +-------+""")

visualdice_2 =( """
            +-------+
            | *     |
            |       |
            |     * |
            +-------+""")

然后与

def showdice():
#Dice1 Visual Execution
    if dice1 == 1:
        print(visualdice_1)
    if dice1 == 2:
        print(visualdice_2)

def start():
    confirmation = input("Would you like to roll the dice? (Y/N): ")
    if confirmation == "Y" or confirmation == "y":
        print ("You've rolled:",dice1,"and", dice2), showdice()
        return start()
    else:
        print("Goodbye")
start()

Tags: 程序ifdef数字random骰子startprint
2条回答

只需重新运行:

dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6) 

在打印功能之前。你知道吗

您在描述中发现了自己的问题:“第2行和第3行的指定号码”。在循环上方指定数字。你知道吗

相反,将随机数生成器放入循环中,并编辑showdice()函数,将骰子值作为参数:

def showdice(dice):
#Dice1 Visual Execution
    if dice == 1:
        print(visualdice_1)
    if dice == 2:
        print(visualdice_2)
    # I suppose this continues until "if dice == 6"...
    ...

def start():
    dice1 = random.randrange(1,6)
    dice2 = random.randrange(1,6)
    confirmation = input("Would you like to roll the dice? (Y/N): ")
    if confirmation == "Y" or confirmation == "y":
        print ("You've rolled:",dice1,"and", dice2)
        showdice(dice1)
        showdice(dice2)
        return start()
    else:
        print("Goodbye")
start()

否则,它将始终使用与您在脚本顶部实例化的相同的随机掷骰子。你知道吗

相关问题 更多 >

    热门问题