【问题标题】:Is there a way to determine successes in a python dice roller?有没有办法确定 python 骰子滚轮的成功?
【发布时间】:2021-11-13 19:57:21
【问题描述】:

我是编程新手(例如非常新),我决定为我最喜欢的角色扮演游戏 Vampire the Masquerade 制作一个掷骰子。对于那些不知道的人,当你想在 VtM 中掷骰子时,你会做 d10s(十面骰子)的骰子池,然后你是否成功取决于你掷出的“成功”数量;任何骰子结果为 6 或更多。

到目前为止,我已经成功制作了一个可以滚动 d10s 的基本滚筒:

#"d" is the number of dice
def roll(d):
    return [randint(1,10) for i in range(d)]

#Main Program
d = int(input("\nHow many dice are you rolling? > "))
results = roll(d)
print(results)

但是,我无法让程序计算卷中的成功次数。我希望输出看起来像

How many dice are you rolling? > 2
[5, 9]
1 success

有什么建议吗?

【问题讨论】:

  • successes = count(results, key=lambda die: die >= 6)

标签: python random dice


【解决方案1】:

只要做:

d = int(input("\nHow many dice are you rolling? > "))
results = roll(d)
print(results)
x = sum(i >= 6 for i in results)
print([f'{x} success', 'failure'][not x])

倒数第二行也可以变成:

x = sum(1 for i in results if i >= 6)

【讨论】:

  • 我建议sum(1 for i in results if i >= 6);这使得意图比依赖 True 转换为 1 以进行加法的细节更加清晰
  • @JiříBaum 好的,编辑了我的答案
  • 我已经尝试了你们推荐的方法,但现在无论有多少个 6 或更多的结果,它都会打印结果和“失败”。从最后一行代码中删除“失败”字符串会引发错误:IndexError: list index out of range
  • @Gloompunk 哦,编辑了我的答案,抱歉!
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 2016-08-10
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多