创建一副牌的最佳方法是什么?

时间:2017-02-01 02:07:40

标签: python

我正在考虑为纸牌游戏制作一副纸牌。我可以列出所有卡片(我不太关心西装),但我想知道是否有更简单的方法来做这件事。

cards = ['1','1','1','1'....]

我很肯定你可以制作for循环来创建4张相同值的牌并将其添加到列表中,但我想知道这是否是最佳解决方案。我不够先进,不知道或创建Class,我已经看到它作为其他解决方案提供,但我愿意解释。

我已经制作了一个字典来定义卡片值。

14 个答案:

答案 0 :(得分:9)

我建议您使用基本类的解决方案。

首先,让我们创建一个Card类:

class Card:
    def __init__(self, value, color):
        self.value = value
        self.color = color

然后,让我们列出颜色:

colors = ['heart', 'diamonds', 'spades', 'clubs']

最后,让我们用列表理解构建你的套牌:

deck = [Card(value, color) for value in range(1, 14) for color in colors]

Card类只是一个包装器,只是为了操纵卡而不是元组,感觉更自然。

在当前状态下,它几乎等同于重命名tuple类型......基本上,它只包含一个构造函数__init__,用于设置实例的属性。

因此,当我在列表推导中调用Card(value, color)时,例如Card(11, 'spades'),创建了Card类的新实例,其value属性集已设置到11,其color属性设置为'spades'

我建议您阅读一些关于OOP的教程,以深入理解这些概念。

现在,您可以尝试改进这个想法,例如使用更详细的values列表而不是range(1, 14)

values = ['ace', '2', ..., 'king']

答案 1 :(得分:4)

可以使用namedtuple模块中的collections来完成另一种方法,例如:

from collections import namedtuple

Card = namedtuple('Card', ['value', 'suit'])
suits = ['hearts', 'diamonds', 'spades', 'clubs']
cards = [Card(value, suit) for value in range(1, 14) for suit in suits]

您可以访问以下值:

print(cards[0])
>>> Card(value=1, suit='hearts')
print(cards[0].value, cards[0].suit)
>>> 1 hearts

答案 2 :(得分:4)

首先是一些实用功能:

import random
from random import shuffle

def RANKS(): return [ "Ace", "2", "3", "4", "5", "6", "7","8", "9", "10", "Jack", "Queen", "King" ]
def SUITS(): return [ "Clubs", "Diamonds", "Hearts", "Spades" ]

然后是卡类:

class Card:

    def __init__( self, rank, suit ):
        self.rank = rank
        self.suit = suit

    def __str__( self ):
        return self.rank + " of " + self.suit

然后是甲板课:

class Deck:

    def __init__( self ):
        self.contents = []
        self.contents = [ Card( rank, suit ) for rank in RANKS() for suit in SUITS() ]
        random.shuffle( self.contents )

答案 3 :(得分:1)

values = ['2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace']
suites = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
deck = [[v + ' of ' + s,v] for s in suites for v in values]

答案 4 :(得分:1)

您可以将您的套牌表示为元组列表。这是一种较轻的替代课程。在像python这样的动态语言中,通常会这样做以避免通过定义自己的类而产生的样板代码。

import itertools
import random

vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace']
suits = ['spades', 'clubs', 'hearts', 'diamonds']

deck = list(itertools.product(vals, suits))

random.shuffle(deck)

for val, suit in deck:
    print('The %s of %s' % (val, suit))

您可能希望用整数表示卡值,这可以通过更改输入列表轻松实现。

答案 5 :(得分:0)

我认为你是对的,for loop会完成工作,但可能不是最优雅的解决方案。我从来没有在Python中编程,所以我不知道确切的语法,但我可以给你一个类的伪代码纲要,可以完成工作。

答案 6 :(得分:0)

也可以这样做:

card_deck = []

for i in range(3,11):
    card_deck.extend([i]*4)

for c in ['Jack', 'Queen', 'King', 'Ace']:
    card_deck.extend([c]*4)

答案 7 :(得分:0)

此解决方案使用枚举类(包enum34)。

两个枚举类用自定义 str 函数表示套装和数字。 from enum import Enum from enum import unique @unique class Suit(Enum): Spade = 1 Heart = 2 Dimond = 3 Club = 4 def __str__(self): return self.name @unique class Number(Enum): N1 = 1 N2 = 2 N3 = 3 N4 = 4 N5 = 5 N6 = 6 N7 = 7 N8 = 8 N9 = 9 N10 = 10 J = 11 Q = 12 K = 13 def __str__(self): if self.value <= 10: return str(self.value) return self.name class Card(object): def __init__(self, suit, number): self.suit = suit self.number = number def __str__(self): return '{} {}'.format(self.suit, self.number) cards = [ Card(suit, number) for suit in Suit for number in Number ] for card in cards: print card 类采用Suit + a Number

css

答案 8 :(得分:0)

此代码使40张卡片的甲板上有两个for循环。甲板由40根巫婆线组成,最后一个角色[-1]是c b s d(意大利式纸牌甲板中的coppe,bastoni,spade和denari)之间的颜色。由于第10张卡的值编号为2位,因此最好使用[:-1]来获得卡的值,这样将需要1,2,3 ...直到9和10为止。 2位数字的卡。

class Cards:
    def __init__(self):
        self.deck = []                  # the deck is empty
        for n in range(1,11):           # numbers
            for c in "cbsd":            # colors
                self.deck.append(str(n) + c)  # a string for each card


deck = Cards()
deck.deck
  

输出:

     

['1c','1b','1s','1d','2c','2b','2s','2d','3c','3b','3s','3d ','4c','4b','4s','4d','5c','5b','5s','5d','6c','6b','6s','6d', '7c','7b','7s','7d','8c','8b','8s','8d','9c','9b','9s','9d','10c ','10b','10s','10d']

答案 9 :(得分:0)

我为此找到了一个非常有用的教程

https://projects.raspberrypi.org/en/projects/deck-of-cards

它看起来很幼稚,但其中包含一些非常优质的代码

其中包含的代码如下:

class Card:

    """
    The Card class represents a single playing card and is initialised by passing a suit and number.
    """

    def __init__(self, suit, number):
        self._suit = suit
        self._number = number

    def __repr__(self):
        return self._number + " of " + self._suit

    @property
    def suit(self):

        """
        Gets or sets the suit of a card
        """

        return self._suit

    @suit.setter
    def suit(self, suit):
        if suit in ["hearts", "clubs", "diamonds", "spades"]:
            self._suit = suit
        else:
            print("That's not a suit!")

    @property
    def number(self):
        """
        Gets or sets the number of a card
        """
        return self._number

    @number.setter
    def number(self, number):
        valid = [str(n) for n in range(2,11)] + ["J", "Q", "K", "A"]
        if number in valid:
            self._number = number
        else:
            print("That's not a valid number")

答案 10 :(得分:0)

“简单代码,带有52张卡片组合的卡片组列表”:

card_type=['Diamond', 'Heart', 'Spade', 'Clover']
card_number=['1','2','3','4', '5', '6', '7', '8', '9', 'J', 'Q', 'K']
for c in card_type:
    ...:     for n in card_number:
    ...:         deck.append([c,n])

答案 11 :(得分:0)

deck = {}
//i represents order
// 0,1,2,3 represents suits
// 0,1,2,...,12 represents ranks 

for i in range(52):
  deck[i] = [i%4,i%13]

答案 12 :(得分:0)

一种选择是使用“for循环”为每个等级和花色创建一张卡片,然后赋予值,并将所有数据放在每张卡片的元组中,并将所有卡片保留在列表中。

我使用以下代码在不使用类的情况下创建了一副纸牌:(请注意,我所赋予的值适用于二十一点游戏,但您可以随意更改)

ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
cards = []
def deck_of_cards():
    for rank in ranks:
        for suit in suits:
            a = rank
            b = suit
            if ranks.index(a) == 0:
                c = 11
            elif ranks.index(a) > 9:
                c = 10
            else:
                c = ranks.index(a) + 1
            new_card = (a, b, c)
            cards.append(new_card)

deck_of_cards()

答案 13 :(得分:0)

cards = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]

deck = []

suits = ["Spades", "Diamonds", "Clubs", "Hearts"]
suit = 0
for card in range(52):
    if card >= 13 * (suit + 1):
        suit += 1
    deck.append(str(cards[card % 13] + "|" + suits[suit]))