创建一个生成卡片的类

时间:2018-05-03 03:56:08

标签: python python-3.x

我正在创建一个名为Card的类,它将处理一张卡(随机),然后处理方法,它将使用随机处理一张卡,而不是我将定义face_value,它将返回卡对象的值,例如:1 =一,12 =女王。到目前为止它是如何看待的。我有点困惑如何创建一个类,有人可以向我解释一下吗?因为这本书让我更加困惑。

    import random
class Card:
def __init__(self):
    self.__value = 0

def deal(self):        
    self.__value = random.randint(1,13)        



def find_face_value(self):


    if value == 1:
        print ("Ace")      
    elif value == 2:
        print ("Two")
    elif value == 3:
        print ("Three")
    elif value == 4:
        print ("Four")
    elif value == 5:
        print ("Five")
    elif value == 6:
        print ("Six")
    elif value == 7:
        print ("Seven")
    elif value == 8:
        print ("Eight")
    elif value == 9:
        print ("Nine")
    elif value == 10:
        print ("Ten")
    elif value == 11:
        print ("Jack")
    elif value == 12:
        print ("Queen")
    elif value == 13:
        print ("King")
    else:
        # This will catch any invalid card values
        print ("Invalid card")
    return self.__value

这是第二个测试它的程序:

 import classcard



pla = classcard.Card()

print(pla)

2 个答案:

答案 0 :(得分:0)

你有一个良好的开端!您希望在初始化对象时创建随机卡值(因为这是初始化的目的),并且您不希望在Card类中具有deal函数,因为#39; s适用于甲板。我还建议使用列表值而不是if-elif语句的集合。最后,有一个特定的方法可以打印出对象的状态/值/状态:字符串方法__str__(self)

import random
class Card:
  def __init__(self):
    self.value = random.randint(0,12)
    self.suit = random.randint(0,3)
    self.names = ['Ace', 'Two', 'Three', ..., 'Ten', 'Jack', 'Queen', 'King']
    self.suitNames = ['Spades', 'Diamonds', 'Clubs', 'Hearts']

  def  __str__(self):
    card = self.names[self.value] + 'of' + self.suitNames[self.suit]
    return card

>>>
>>> temp = Card()
>>> print(temp) # 'Two of Clubs'

这仍未经过测试,但您会得到一般的想法。 顺便说一下,几乎所有东西都需要自我。

答案 1 :(得分:0)

您可能希望将Card对象的表示与随机Card的制作分开。
这是一种方法,其中类变量用于指定str表示:

import random


class Card:

    VALUES = {'1': 'Ace', 'A': 'Ace', 'J': 'Jack', '11': 'Jack', 'Q': 'Queen', '12': 'Queen', 'K': 'King', '13': 'King'}
    SUITS = {'H': 'hearts', 'S': 'spades', 'D': 'diamond', 'C': 'clubs'}

    def __init__(self, value, suit):
        self.value = str(value)
        self.suit = suit

    def __str__(self):
        return f"{Card.VALUES.get(self.value, self.value)} of {Card.SUITS[self.suit]}"


def get_random_card():
    return Card(random.randrange(1, 14), random.choice(list(Card.SUITS.keys())))


if __name__ == '__main__':

    for _ in range(10):
        print(get_random_card())

输出示例:

Ace of clubs
10 of hearts
3 of spades
2 of spades
8 of diamond
Ace of hearts
2 of clubs
Ace of spades
8 of diamond
Jack of hearts

注意:

此示例从无限牌组中抽取牌。我可以多次生成相同的卡片。

如果您想限制抽取到多个套牌,可以使用Deck类;也许是这样的:

class Deck:
    """represents a deck of 52 cards or a multiple of 52 cards"""

    def __init__(self, num_decks=1):
        self.cards = [Card(val, suit) for val in range(1, 14) for suit in list(Card.SUITS.keys()) for _ in range(num_decks)]
        self.num_decks = num_decks
        self.shuffled = False

    def __iter__(self):
        for card in self.cards:
            yield card

    def shuffle(self):
        random.shuffle(self.cards)
        self.shuffled = True

    def get_random_card(self):
        """removes a random card from the deck and returns it
        shuffles the deck if not already shuffled"""
        if not self.shuffled:
            self.shuffle()
        return self.cards.pop()


def get_random_card():
    return Card(random.randrange(1, 14), random.choice(list(Card.SUITS.keys())))


if __name__ == '__main__':

    deck = Deck(3)   # creates a Deck that holds 3x52 cards
    deck.shuffle()

    for idx, card in enumerate(deck):
        print(idx, card)

从那里开始,很容易添加一些功能,可以从一个牌组交给各个玩家。