确定骰子卷是否包含某些组合?

时间:2010-10-07 00:37:11

标签: python algorithm list dictionary dice

我正在用Python编写一个骰子游戏模拟器。我通过使用包含1-6的整数的列表来表示滚动。所以我可能会像这样:

[1,2,1,4,5,1]

我需要确定一个卷是否包含得分组合,例如3种,4种,2种3和直道。

有一种简单的Pythonic方式吗?我已经尝试了几种方法,但它们都变得很混乱。

3 个答案:

答案 0 :(得分:4)

使用value: count重新组合成一个字典并测试各种模式的存在。

答案 1 :(得分:2)

我之前编写了这样的代码(但是有扑克牌)。一定数量的代码蔓延不可避免地编码游戏的所有规则。例如,寻找n-of-kind的代码与寻找直接代码的代码完全不同。

让我们首先考虑一种类型。正如其他人所建议的那样,创建一个包含每个元素计数的dict。然后:

counts = sorted(d.values())
if counts[-1] == 4:
   return four_of_a_kind
if counts[-1] and counts[-2] == 3:
   return two_sets_of_three
# etc.

检查直道需要采用不同的方法。检查n-of-kind时,您需要获取计数并忽略这些值。现在我们需要检查值并忽略计数:

ranks = set(rolls)
if len(ranks) == 6: # all six values are present
    return long_straight
# etc.

通常,您应该能够识别具有类似风格的规则,抽象出有助于这些规则的代码,然后每条规则只写几行。某些规则可能完全唯一,并且无法与其他规则共享代码。这就是饼干粉碎的方式。

答案 2 :(得分:1)

有两种方法可以做到这一点:

def getCounts(L):
    d = {}
    for i in range(1, 7):
        d[i] = L.count(i)
    return d # d is the dictionary which contains the occurrences of all possible dice values
             # and has a 0 if it doesn't occur in th roll

这个灵感来自Ignacio Vazquez-Abrams和dkamins

def getCounts(L):
    d = {}
    for i in set(L):
        d[i] = L.count(i)
    return d # d is the dictionary which contains the occurrences of 
             # all and only the values in the roll
相关问题