python - 卡住骰子滚动?

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

我正在按照 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?: 

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

最佳答案

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

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

关于python - 卡住骰子滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34174060/

相关文章:

mysql - Python - Mac OSX 10.10 中的 MySQL 连接器错误

javascript - JAVASCRIPT 中 IF 条件上的 AND

c++ - 当条件激活时停止 arduino 循环

python检查字符串是否以有效范围内的数字结尾

python - 有没有办法通过将 python 列表快速转换为 numpy 矩阵来搜索列表?

python - 如何使用 getpass() 在输入时隐藏用户密码

urls.py 中的 Django2 AttributeError

python - 无法从 'ParserError' 导入 'dateutil.parser'

Python分配错误的字典值

javascript - 为什么这段代码日志返回 false?