确定掷骰子是否包含某些组合?
我正在用 Python 编写一个骰子游戏模拟器。我使用包含 1-6 整数的列表来表示掷骰。所以我可能会进行这样的掷骰:
[1,2,1,4,5,1]
我需要确定掷骰是否包含得分组合,例如 3 种、4 种、2 组 3 和顺子。
有没有一种简单的 Pythonic 方法可以做到这一点?我尝试了几种方法,但结果都是很混乱。
I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this:
[1,2,1,4,5,1]
I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 sets of 3, and straights.
Is there a simple Pythonic way of doing this? I've tried several approaches, but they all have turned out to be messy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
value: count
重新组织成一个字典,并测试是否存在各种模式。Reorganize into a dict with
value: count
and test for presence of various patterns.有两种方法可以做到这一点:
这种方法的灵感来自于 Ignacio Vazquez-Abrams 和 dkamins
There are two ways to do this:
This one is inspired by Ignacio Vazquez-Abrams and dkamins
我以前写过这样的代码(但用的是扑克牌)。为了对游戏的所有规则进行编码,一定量的代码蔓延是不可避免的。例如,查找 n-of-a-kind 的代码与查找顺子的代码完全不同。
让我们首先考虑 n-of-a-kind。正如其他人所建议的,创建一个包含每个元素计数的
dict
。然后:检查直道需要不同的方法。检查 n-of-a-kind 时,您需要获取计数并忽略这些值。现在我们需要检查值并忽略计数:
一般来说,您应该能够识别具有相似风格的规则,抽象出有助于处理这些类型规则的代码,然后为每个规则编写几行。某些规则可能是完全唯一的,并且无法与其他规则共享代码。这就是饼干破碎的方式。
I have written code like this before (but with cards for poker). A certain amount of code-sprawl is unavoidable to encode all of the rules of the game. For example, the code to look for n-of-a-kind will be completely different from the code to look for a straight.
Let's consider n-of-a-kind first. As others have suggested, create a
dict
containing the counts of each element. Then:Checking for straights requires a different approach. When checking for n-of-a-kind, you need to get the counts and ignore the values. Now we need to examine the values and ignore the counts:
In general, you should be able to identify rules with a similar flavor, abstract out code that helps with those kinds of rules, and then write just a few lines per rule. Some rules may be completely unique and will not be able to share code with other rules. That's just the way the cookie crumbles.