繁体   English   中英

有人可以帮我为pygame的扑克游戏创建一副纸牌吗

[英]Can someone help me create a deck of Cards for a poker game in pygame

我试图用pygame和OOP在python中制作一个扑克游戏。 之前,我是从一个反复无常的课程中制作一个基于文本的二十一点游戏,而我试图使用某些相同的原理来创建我的套牌,但它不起作用。 我的问题是我要创建52个卡片对象,并且我希望每个卡片对象都具有三个属性(西服,等级和png文件)。

class Card:

    def __init__(self, suit, rank, pic):

        self.suit = suit
        self.pic = pic
        self.rank = rank


class Deck:

    def __init__(self):

        self.deck_comp = []

    def create_deck(self):

        for suit in suits:
            for rank in ranks:
                for pic in deck:

                    self.deck_comp.append(Card(suit, rank, pic))

我觉得三个for循环是问题。 在基于文本的二十一点游戏中,卡仅需要具有两个属性。 对于此游戏,我需要纸牌对象具有图片,值和西装,以便我可以显示它们并进行比较。

西服是四个西服字符串的列表,排名是卡名作为字符串的列表,而pic是52个.png文件的列表(卡组中的每张卡一个)

将所有png名称保存在字典中并在Card类中分配图像会更明智吗?

class Card:
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit
        self.img = png_images[f'{value}{suit}']

class Deck:
        def __init__(self, shuffle_cards=True):
        self.cards = []
        self.shuffle_cards = shuffle_cards
        self.create()

    def create(self):
        for _ in range(number_of_decks):
            for val in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14):
                for suit in ("Hearts", "Spades", "Clubs", "Diamonds"):
                    self.cards.append(Card(val, suit))

        if self.shuffle_cards:
            shuffle(self.cards)

基于其中一本书的示例:

import collections

Card = collections.namedtuple('Card', ['rank', 'suit'])

class Deck:
    ranks = [str(n) for n in range(2, 11)] + ['JQKA']
    suits = ['spades', 'diamonds', 'clubs', 'hearts']
    #  dictionary of dictionaries which maps ranks and suits to the picture
    pic_mapping = {
                    'spades': {
                                '2': 'spades2',
                                '3': 'spades3'
                                ...
                              },
                    'hearts': {
                                '2': 'hearts2',
                                '3': 'hearts3'
                                ...
                              },  


    def __init__(self):
        self._cards = [Card(rank, suit, pic_mapping[suit][rank]) for suit in self.suits
                                        for rank in self.ranks]

请注意,列表可能会变成元组,或者可以使用生成器来构建。 列表仅用于提高可读性。 另外,您可以重载__len____getitem__来支持诸如以下操作:

  • 索引[i]
  • random.choice(collection)
  • 切片
  • 反复
  • reversed(collection)

您可以使用图像命名约定来遵循f'{suit} {rank}'模式,而不是使用dict映射,并将其动态添加到Card对象。

自从我做了这样的事情已经有一段时间了,但是您可以为每套西装创建一个泡菜字典。

看一下: 如何使用泡菜保存字典?

并创建TRIES: 如何在Python中创建TRIE

希望能帮助到你 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM