在python中存储卡片和套装的最佳方法是什么,以便我可以在另一个变量中保存对这些值的引用?
例如,如果我有一个名为hand的列表(玩家手中的牌),我怎么能保存可以引用特定牌的套装名称和值的值,以及这些名称和套装和牌的价值如何存储?
答案 0 :(得分:25)
扑克服务器倾向于使用2个字符的字符串来识别每张卡片,这很好,因为它很容易以编程方式处理,并且对于人类来说也很容易阅读。
>>> import random
>>> import itertools
>>> SUITS = 'cdhs'
>>> RANKS = '23456789TJQKA'
>>> DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))
>>> hand = random.sample(DECK, 5)
>>> print hand
['Kh', 'Kc', '6c', '7d', '3d']
编辑:这实际上是我用来评估扑克手牌的扑克模块,你可以在这里看到更多:http://pastebin.com/mzNmCdV5
答案 1 :(得分:7)
最简单的方法是使用元组列表,其中卡片是整数,而套装是字符串:
hand = [(1, 'spade'), (10, 'club'), ...]
但最简单的可能不是你想要的。也许你想要一个班级代表一张卡片:
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
letters = {1:'A', 11:'J', 12:'Q', 13:'K'}
letter = letters.get(self.rank, str(self.rank))
return "<Card %s %s>" % (letter, self.suit)
hand = [Card(1, 'spade'), Card(10, 'club')]
答案 2 :(得分:1)
您可以简单地使用一个数字,并决定数字和“卡片”之间的映射。例如:
编号MOD 13 =面值(+1后)
号码DIV 13 =诉讼
答案 3 :(得分:1)
import collections
C, H, D, S = "CLUBS", "HEARTS", "DICE", "SPADE"
Card = collections.namedtuple("Card", "suit value")
hand = []
hand.append(Card(C, 3))
hand.append(Card(H, "A"))
hand.append(Card(D, 10))
hand.append(Card(S, "Q"))
for card in hand:
print(card.value, card.suit)
答案 4 :(得分:1)
一副牌由四个套装中的相同范围的值(1 - 13)组成,这表示笛卡尔积。列表理解是一种优雅,密集的语法:
values = range(1, 10) + "Jack Queen King".split()
suits = "Diamonds Clubs Hearts Spades".split()
deck_of_cards = ["%s of %s" % (v, s) for v in values for s in suits]
在python 3中:
deck_of_cards = ["{0} of {1}".format(v, s) for v in values for s in suits]
当你从盒子里拿出一个全新的套牌时,它们就是这样的;玩你需要洗牌他们:
from random import shuffle
shuffle(deck_of_cards)
答案 5 :(得分:-1)
import random
N = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
S = ['♠', '♣', '♥', '♦']
def card_deck(a, b):
cards = []
for i in a:
for j in b:
cards.append(i + j)
return cards
cards = card_deck(N, S)
hand1 = random.sample(cards, 13)
hand2 = random.sample(set(cards) - set(hand1), 13)
hand3 = random.sample(set(cards) - set(hand1) - set(hand2), 13)
hand4 = random.sample(set(cards) - set(hand1) - set(hand2) - set(hand3), 13)
print(f'Player 1: {hand1}')
print(f'Player 2: {hand2}')
print(f'Player 3: {hand3}')
print(f'Player 4: {hand4}')