python Programming -- python style Solitaire

Posted by allydm on Fri, 28 Jan 2022 18:56:20 +0100

python Programming (I) -- python style Solitaire

Python programming style is also called python. This series of articles records learning bits and pieces.

preface

This article is realized through A simple example__ getitem__ And__ len__ Method, the example is to realize 52 playing cards without size kings, including four decors and 2-10, J, Q, K and A (this is also our default size order).

1, Create a card class

Example code 1-1:

import collections

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

class FrenchDeck:
	ranks = [str(n) for n in range(2,11)] + list('JQKA')  # size
	suits = 'spades diamonds clubs hearts'.split()  # Decor
	
	def __init__(self):
		self._cards = [Card(rank, suit) for suit in self.suits
					        			for rank in self.ranks]  # Created 13 * 4 = 52 cards
					        			
	def __len__(self):
		return len(self._cards)
		
	def __getitem__(self, position):
		return self._cards[position]

First, we use collections Namedtuple builds a simple class to represent a Card. Any Card we want can be obtained through this Card object:

>>> beer_card = Card('K', 'diamonds')
>>> beer_card
Card(rank='K', suit='diamonds')

And in the card class, 13 * 4 = 52 cards are created through two for loops

2, In class method

First, the card class we created is the same as any standard Python collection type. You can use the len() function to see how many cards there are in a stack:

>>> deck = FrenchDeck()
>>> len(deck)
52

Secondly, we can draw a specific card from this deck of playing cards, such as the first or last card:
The code is as follows:

>>> deck[0]
Card(rank='2', suit='spades')
>>> deck[-1]
Card(rank='A', suit='hearts')

These are made by__ getitem__ Method, and you can use a built-in function random Choice can randomly draw a card:

>>> from random import choice
>>> choice(deck)
Card(rank='6', suit='hearts')
>>> choice(deck)
Card(rank='A', suit='spades')

3, Method expansion

The following lists the operations of viewing the top 3 cards of A stack of cards and only looking at the cards whose face is A. The specific method of the second operation is to draw the card with index 12 first, and then take one card every 13 cards:

>>> deck[:3]
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')]
>>> deck[12::13]
[Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]

Note the slicing operation of list [start: end: step], where end is omitted and the step size is directly set.

In addition, through__ getitem__ Method, we can realize the iteration of cards:

>>> for card in deck:
	print(card)

Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
Card(rank='6', suit='spades')
······

There is also the operation of reverse iteration. The method used is the reverse() function that reverses the list:

>>> for card in reversed(deck): # doctest: +ELLIPSIS
... print(card)
Card(rank='A', suit='hearts')
Card(rank='K', suit='hearts')
Card(rank='Q', suit='hearts')
...

Finally, we write A sorting function to sort the playing cards according to the color and size order of spades, hearts, squares and clubs, and the numerical size order of 2-10, J, Q, K and A.

Sorting idea:
Get the index of each card value, and sort by suit in the same index.

Firstly, the pair of tuples in the list is changed into the form of dictionary through dict function. Then in spades_ In the high function, get the index rank of each card value_ Value, the return value is the index of the value plus the size of the decor, and then through the sort function to our rank_value is key. The specific implementation code is as follows:

>>> suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
>>> def spades_high(card):
		rank_value = FrenchDeck.ranks.index(card.rank)
		return rank_value * len(suit_values) + suit_values[card.suit]
>>> for card in sorted(deck, key=spades_high):
	print(card)

	
Card(rank='2', suit='clubs')
Card(rank='2', suit='diamonds')
Card(rank='2', suit='hearts')
Card(rank='2', suit='spades')
Card(rank='3', suit='clubs')
Card(rank='3', suit='diamonds')
Card(rank='3', suit='hearts')
Card(rank='3', suit='spades')
Card(rank='4', suit='clubs')
······

summary

So far, FrenchDeck cannot shuffle because this stack of cards is immutable: cards and their positions are fixed unless we destroy them
The encapsulation of this class is directly related to_ cards.

Topics: Python data structure list