import random
import itertools
suit = 'CSHD'
rank = '23456789TJQKA'
deck_of_cards = [''.join(card) for card in itertools.product(rank, suit)]
def draw_card(deck,hand, count):
for i in range(count):
hand.append(deck.pop())
def hand_selection(deck):
shuffled_deck = random.sample(deck, len(deck))
dealer_hand = []
player_hand = []
draw_card(shuffled_deck, dealer_hand, 1)
draw_card(shuffled_deck, player_hand, 1)
draw_card(shuffled_deck, dealer_hand, 1)
draw_card(shuffled_deck, player_hand, 1)
return dealer_hand,player_hand
在这里尝试遵循卡片交易的原则。最初我想随机生成一张卡片,将其从shuffled_deck
中删除,但我们不会通过随机搜索卡片来处理卡片,是吗?为了我的目的,代码完成了它应该做的事情,但它看起来并不太好。 (是的,shuffled_deck
,player_hand
和dealer_hand
实际上都是全局的,但目前无关紧要。)
以这种方式处理卡片的更优雅(读取:pythonic)解决方案是什么?例如,我们在3个玩家之间玩中国扑克游戏。像这样一个接一个地处理似乎太乏味了。
答案 0 :(得分:4)
我会让甲板成为一个类,以保持其相关功能:
class Deck(object):
def __init__(self, suits='CSHD', ranks='23456789TJQKA'):
self.cards = [''.join(card) for card in itertools.product(ranks, suits)]
def shuffle(self):
random.shuffle(self.cards)
def deal_cards(self, hand, count=1):
for _ in range(count):
hand.append(self.cards.pop())
def return_cards(self, hand):
self.cards.extend(hand)
简化交易:
deck = Deck()
deck.shuffle()
dealer_hand = []
player_hand = []
for _ in range(2): # number of rounds to deal
for hand in (dealer_hand, player_hand): # hands to deal to
deck.deal(hand)
这更容易适应更多玩家和/或更多回合。