【问题标题】:Freezing dice rolled?冷冻骰子滚动?
【发布时间】:2016-03-14 10:41:54
【问题描述】:

我正在按照 Yahtzee 掷骰子游戏的思路创建游戏。我必须给用户掷出 5 个骰子,并问他们一个 5 位数的数字,他们想重新掷出哪个骰子。例如:

Your roll is:  5 1 5 5 1
Which dice should I roll again?: 234
Your new roll is: 5 7 2 4 1

中间的三个数字会发生变化,因为它们是掷出的骰子。 我不知道如何有效地做到这一点。我可以创建 240 个 if 语句,但这似乎不是解决此问题的正确方法。

这是我目前的代码:

import random

def yahtzee():
    dice1 = random.randrange(1,6)
    dice2 = random.randrange(1,6)
    dice3 = random.randrange(1,6)
    dice4 = random.randrange(1,6)
    dice5 = random.randrange(1,6)
    print('Your roll is: ' + ' ' + str(dice1) + ' ' + str(dice2) + ' ' + str(dice3) + ' ' + str(dice4) + ' ' + str(dice5))
    reroll = input('Which dice should I roll again?: ')

这给了我结果:

yahtzee()
Your roll is:  4 3 2 1 5
Which dice should I roll again?: 

不知道如何重新掷骰子。任何帮助,将不胜感激!谢谢!

【问题讨论】:

    标签: python python-3.x if-statement random dice


    【解决方案1】:

    一般来说,管理存储在列表中的结果要容易得多:

    def yahtzee():
        dice = [random.randrange(1, 6) for _ in range(5)]
        print('Your roll is: ', *dice)
        reroll = input('Which dice should I roll again?: ')
        for i in reroll:
            dice[int(i) - 1] = random.randrange(1, 6)
        print('Your roll is: ', *dice)
    

    示例输出:

    Your roll is:  5 3 2 5 3
    Which dice should I roll again?: 12
    Your roll is:  1 2 2 5 3
    

    【讨论】:

    • 太棒了,非常感谢,发现我的代码效率很低,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-03-16
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多