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

前端 未结 5 400
执念已碎
执念已碎 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: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 "" % (letter, self.suit)
    
    hand = [Card(1, 'spade'), Card(10, 'club')]
    

提交回复
热议问题