【问题标题】:Dice game (simulating many throws with 3 dices)骰子游戏(用 3 个骰子模拟多次投掷)
【发布时间】:2018-10-19 04:51:09
【问题描述】:

我正在尝试编写一个骰子游戏:

如何编写一个函数来模拟 3 个骰子的 1000 次投掷,并打印一次投掷导致恰好 2 个骰子(但不是全部 3 个)落在相同数字上的次数。意思不是 (1,2,3) 或 (5,5,5),而是像这样 (1,2,2)。

def throw():

我知道我需要使用随机库来生成 1 到 6 之间的数字。

我需要的是示例代码,说明我如何处理这个问题以及做什么。

【问题讨论】:

  • 这不适合堆栈溢出,因为您没有特定问题;你最好去 python 论坛或聊天室讨论它。

标签: python python-3.x dice


【解决方案1】:

函数可能是这样的:

import random
matches = 0
for i in range(1000):  # 1000 throws
    result = (random.randint(1,6), random.randint(1,6), random.randint(1,6)) # three dices randomly from 1 to 6 in a tuple (list)
    for i in range(1,7): # count from 1 to 6
        if result.count(i) == 2:
            matches += 1
            break # breaking out of this for-loop for performance improvement
print("Got "+str(matches)+" matches.")

当然,这段代码可以大大改进。但是根据您的问题,我假设您对 Python 编程很陌生。这就是我尝试编写不言自明的代码的原因。

Meta:请记住,Stack Overflow 不是要求特定编码的正确位置。它旨在成为您提供包含您无法修复的错误的代码的地方。

【讨论】:

    【解决方案2】:

    使用 for 循环和列表推导生成 throw:

    for i in range(1000):
        throw = [random.randint(1, 6) for x in range(3)]
    

    然后只需编写代码来检查您的状况,例如:

    valid = any([throw.count(i) == 2 for i in range(1, 6)])
    

    如果它是有效的 True 你可以用它做你需要的。

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 2016-02-07
      • 1970-01-01
      • 2012-02-29
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多