best way to implement a deck for a card game in python

前端 未结 5 401
执念已碎
执念已碎 2020-12-31 05:06

What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable?

For example, if I have a list called

相关标签:
5条回答
  • 2020-12-31 05:32

    You could simply use a number, and decide on a mapping between number and "card". For example:

    number MOD 13 = face value (after a +1)

    number DIV 13 = suit

    0 讨论(0)
  • 2020-12-31 05:39

    A deck of cards is comprised of the same range of values (1 - 13) in each of four suits, which suggests a Cartesian product. List comprehension is an elegant, dense syntax for doing this:

    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]
    

    in python 3:

    deck_of_cards = ["{0} of {1}".format(v, s) for v in values for s in suits]
    

    That's how they are when you take a brand new deck out of the box; to play you need to shuffle them:

    from random import shuffle
    
    shuffle(deck_of_cards)
    
    0 讨论(0)
  • 2020-12-31 05:41

    The simplest thing would be to use a list of tuples, where the cards are ints and the suits are strings:

    hand = [(1, 'spade'), (10, 'club'), ...]
    

    But simplest may not be what you want. Maybe you want a class to represent a card:

    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')]
    
    0 讨论(0)
  • 2020-12-31 05:44

    Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human.

    >>> 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']
    

    Edit: This is actually straight from a poker module I wrote to evaluate poker hands, you can see more here: http://pastebin.com/mzNmCdV5

    0 讨论(0)
  • 2020-12-31 05:52
    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)
    
    0 讨论(0)
提交回复
热议问题