今天我们来制作poker 这个牌类游戏
understanding(理解问题)
Start with a vague understanding that you refine into a problem.
specify (明确问题)
Specify how this problem can be made amenable to being coded.
design (设计程序)
Coding
游戏规则:
所有可能的手牌
• 0- High Card
• 1- One Pair
• 2- Two Pair
• 3- Three of a Kind
• 4- Straight
• 5- Flush
• 6- Full House
• 7- Four of a Kind
• 8- Straight Flush
【注:我们用其对应的数字作为得分】
详细游戏规则自行上维基百科上查看
如何在hands 中存储我们的手牌,手牌由数字和花色组成(可以采用如下方式):
sf = ['6C', '7C', '8C', '9C', 'TC'] # Straight Flush
fk = ['9D', '9H', '9S', '9C' ,'7D'] # Four of a Kind
fh = ['TD', 'TC', 'TH', '7C', '7D'] #Full House
用何种数据结构来存放这些手牌类型:
我们最终要判断哪副手牌可以获胜,所以我们需要一个判断胜负的函数
Def poker(hands):
"return the best hand"
进一步分析我们要判断大小,那么我们需要对手牌有一个大小的衡量机制
Def hand_rank(hand):
"return the rank of hand"
有了这个大小的度量机制之后
return max(hands, key=hand_rank) 就能返回 best hand
于是我们得到我们的poker 函数
def poker(hands):
"Return the best hand: poker([hand,...]) => hand"
return max(hands, key=hand_rank)
接下来我们要完成hand_rank() 函数,因为hand_rank 函数涉及到手牌的类型,所以我们要完成对手牌类型的判断
Straight
straight(ranks):
returns True if the hand is a straight.
Flush
flush(hand):
returns True if the hand is a flush
Kind
kind(n, ranks):
returns the first rank that the hand has exactly n of. For A hand with 4 sevens this function would return 7.
two_pair
two_pair(ranks):
if there is a two pair, this function returns their corresponding ranks as a tuple. For example, a hand with 2 twos and 2 fours would cause this function to return (4, 2).
card_ranks
card_ranks(hand):
returns an ORDERED tuple of the ranks in a hand (where the order goes from highest to lowest rank).
假定以上函数已经完成,那么我们的hand_rank 函数如下
def hand_rank(hand):
ranks = card_ranks(hand)
if straight(ranks) and flush(hand): # straight flush
return (8, max(ranks))
elif kind(4, ranks): # 4 of a kind
return (7, kind(4, ranks), kind(1, ranks))
elif kind(3, ranks) and