我正在用 Python 编写一个骰子游戏模拟器。我使用一个包含 1-6 整数的列表来表示一个滚动。所以我可能会有这样的卷:
[1,2,1,4,5,1]
我需要确定一卷是否包含计分组合,例如 3 种、4 种、2 组 3 和顺子。
有没有一种简单的 Pythonic 方式来做到这一点?我尝试了几种方法,但结果都是一团糟。
我正在用 Python 编写一个骰子游戏模拟器。我使用一个包含 1-6 整数的列表来表示一个滚动。所以我可能会有这样的卷:
[1,2,1,4,5,1]
我需要确定一卷是否包含计分组合,例如 3 种、4 种、2 组 3 和顺子。
有没有一种简单的 Pythonic 方式来做到这一点?我尝试了几种方法,但结果都是一团糟。
重新组织成一个 dictvalue: count
并测试各种模式的存在。
我以前写过这样的代码(但用扑克牌)。一定量的代码蔓延是不可避免的来编码所有的游戏规则。例如,查找 n-of-a-kind 的代码将与查找直的代码完全不同。
让我们首先考虑n-of-a-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-a-kind 时,您需要获取计数并忽略这些值。现在我们需要检查这些值并忽略计数:
ranks = set(rolls)
if len(ranks) == 6: # all six values are present
return long_straight
# etc.
一般来说,您应该能够识别具有相似风格的规则,抽象出有助于这些规则的代码,然后每个规则只写几行。某些规则可能是完全唯一的,无法与其他规则共享代码。这就是饼干碎的方式。
有两种方法可以做到这一点:
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