This case is to create a deck of 52 playing cards by Python class attributes, excluding king and wang, and to achieve random drawing, sorting, shuffling and other functions;

Create a card class

A deck of poker in addition to king wang, the rest of the 52 cards based on the color (clubs, diamonds, spades, hearts) can be divided into 4 groups, each group has 13 cards; So you can create two lists one for suits and one for 13 characters; Using a random combination between two lists to generate 52 cards,

The code is as follows:

import collections Card = collections.namedtuple("Card",['rank','suit']) class FrenchDeck: Ranks = [STR (n) for n in range(2,11)] + list("JQKA") suits = 'spades diamonds clubs hearts'.split() def __init__(self): ranks = [STR (n) for n in range(2,11)] + list("JQKA") suits = 'spades diamonds clubs hearts'.split() def __init__(self):  self._cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks] def __len__(self): Return len(self._cards) def __getitem__(self, position): return self._cards[positionCopy the code

The collections.namedtuple module creates A class to represent A set of cards. [‘ rank’,’suit’] represents the characters (2-10,J-A) and suits in the card, respectively.

Len () returns the number of cards and getitem() gets the specified card under position(index)

Beer_card = Card('7','diamonds') print(beer_card) = FrenchDeck() print('len is -----') Print (len(deck)) print(deck[0]) print(deck[-1]) print(deck[-1]) Len is ----- 52 Card(rank='2', suit='spades') Card(rank='A', suit='hearts') copy codeCopy the code

Draw a card at random

The random module is used to realize the function of random card drawing

Print ("random choice -----------") print(choice(deck)) print(choice(deck)) print(choice(deck)) # Output random choice ----------- Card(rank='8', suit='clubs') Card(rank='5', Suit ='hearts') Card(rank='5', suit='spades') copies the codeCopy the code

List iterates and slices

Because the getitem method hands the [] operation to the self._cards list, the FranckDeck() class can slice and iterate in addition to the index position mentioned above.

Print ('\nslice is --') print(deck[:3]) print('\n iterated ') print('\n iterated ') for deck[:3]: Print (card) print('\n reversed operation ') for card in reversed(deck[:3]): print(card) # Output slice is -- [Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', Suit = 'spades)] [Card (rank =' 10 ', suit = 'spades'), the Card (, suit rank =' J '=' spades')] iterative operation Card (rank = '2', Rank ='3', suit='spades') Card(rank='4', suit='spades') Suit ='spades') Card(rank='3', suit='spades') Card(rank='2', suit='spades') copies codeCopy the code

The sorting operation

Generally speaking, when judging the size of A playing card by the number of points, the two is the smallest and the ace is the largest. When creating a list of points in the order mentioned above, you only need to sort the list according to the index of points as a benchmark.

In addition to points, there is also a suit that needs to be considered. For suits, a mapping benchmark (also known as weight) needs to be established, and different suits give different values. Python’s dictionary types meet our needs in many ways

Suit_values = dict(spades = 3, hearts = 2, diamonds = 1, clubs = 0) def spades_high(card): Rank_value = frenchdeck.ranks. Index (card.rank) # rank query return rank_value*len(suit_values) + suit_values[card.suit] # Value print('\nSorted ------------------') # use key = lambda mechanism to sort the list for card in sorted(deck,key = lambda spades_high,reverse= True): print(card) # Output Sorted ------------------ Card(rank='A', suit='spades') Card(rank='A', suit='hearts') Card(rank='A', suit='diamonds') Card(rank='A', suit='clubs') Card(rank='K', suit='spades') Card(rank='K', suit='hearts') Card(rank='K', suit='diamonds') Card(rank='K', Suit ='clubs') Card(rank='Q', suit='spades') Card(rank='Q', suit='hearts') Card(rank='Q', suit='diamonds') duplicates codeCopy the code

Code interpretation:

  • 1, the code uses the dictionary to add a mapping mechanism, spades for 3, hearts for 2, diamonds, followed by clubs;
  • 2. Create spades_high to calculate the total weight of each card;
  • 3. Sorted () function key= spades_high is used as the sorting benchmark to sort cards

shuffling

Shuffle is simply a deck of cards to reorder irregularly; Random. Shuffle can do this fairly well, but only if the object satisfies a mutable protocol, which FranchDeck() does not, and this gives an error:

from random import shuffle print('-------------------\n'*3) deck =FrenchDeck() shuffle(deck) # Output x[i], X [j] = x[j], x[I] TypeError: 'FrenchDeck' object does not support item AssignmentCopy the code

For the above problem, simply change the class from immutable to mutable, creating a function that assigns the setitem property

from random import shuffle print('-------------------\n'*3) def set_deck(deck,position,card): Deck._cards [position] = card deck1 = FrenchDeck() print(deck1[:5]) frenchdeck. __setitem__ = set_deck Card(rank='2', suit='spades') Card(rank='3', suit='spades') Card(rank='4', Rank ='5', suit='spades') Card(rank='6', suit='spades') Card(rank='6', suit='diamonds') Card(rank='4', suit='hearts') Card(rank='Q', suit='diamonds') Card(rank='K', Suit ='clubs') Card(rank='8', suit='spades') copies the codeCopy the code

Here we extract the first 5 elements of the shuffled cards, and have realized the shuffling function!

According to the above code, we can further develop and design 54 visualization pictures of playing cards in advance.

Create a key:value mapping relationship between playing card characters and visual images, as shown in the following figure. Store this relationship set in a specified database or file, and you can call it directly after using it