To realize the process of random draw and shuffle in card games (examples of several built-in methods in item Series)

Posted by bmdsherman on Fri, 27 Dec 2019 18:30:40 +0100

To realize the process of random draw and shuffle in card games (examples of several built-in methods in item Series)

 

1,namedtuple:Named tuples can create a class with no methods but only properties
from collections import namedtuple card = namedtuple('card',['rank','suit']) # rank face size, suit face Decor # card is actually a class created by namedtuple. Its attributes are rank and submit c1 = card(2,'Red heart ') # c1 is an instantiated object print(c1) print(c1.suit)

Operation result:

card(rank=2, suit='Red heart ')
//Red heart 2

 

2,Through objects in circular order[Indexes]Arbitrary card taking
from collections import namedtuple Card = namedtuple('Card',['rank','suit']) # rank Deck size, suit Deck Decor class FranchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits = ['Red heart','Square plate','Plum blossom','Spade'] def __init__(self): self._cards = [Card(rank,suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits] # Nested loop,Each round takes a card and saves it to a list,The cards in this one are in a circular order def __getitem__(self, item): return self._cards[item] deck = FranchDeck() print(deck[10]) # When an object is indexed, the retrieval is triggered__getitem__Method

Operation result:

Card(rank='4', suit='Plum blossom')

Process finished with exit code 0

 

3,choice The process of randomly selecting a card
from collections import namedtuple Card = namedtuple('Card',['rank','suit']) # rank Deck size, suit Deck Decor class FranchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits = ['Red heart','Square plate','Plum blossom','Spade'] def __init__(self): self._cards = [Card(rank,suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits] # Nested loop,Each round takes a card and saves it to a list,The cards in this one are in a circular order def __getitem__(self, item): return self._cards[item] def __len__(self): return len(self._cards) # To extract the corresponding cards in a circular and sequential way deck = FranchDeck() print(deck[10]) # When an object is indexed, the retrieval is triggered__getitem__Method # The process of randomly selecting a card from random import choice print(choice(deck)) # Be careful:# choice To be able to randomly draw cards, you have to rely on__len__Method, if not previously defined__len__The method will report an error,
# That is, as long as the choice is used, the method will be triggered

Operation result:

Card(rank='A', suit='Plum blossom')

Process finished with exit code 0

 

4,shuffle The process of random shuffling
from collections import namedtuple Card = namedtuple('Card',['rank','suit']) # rank Deck size, suit Deck Decor class FranchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits = ['Red heart','Square plate','Plum blossom','Spade'] def __init__(self): self._cards = [Card(rank,suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits] # Nested loop,Each round takes a card and saves it to a list,The cards in this one are in a circular order def __getitem__(self, item): return self._cards[item] def __len__(self): return len(self._cards) # The length of a passing card is drawn from so many cards def __setitem__(self, key, value): self._cards[key] = value deck = FranchDeck() print(deck[10]) # adopt shuffle and__setitem__The process of random shuffling, if not defined previously__setitem__Methods also report errors
# Because the process index of random shuffling will change the corresponding cards, you can only change it through \
from random import shuffle shuffle(deck) print(deck[10])

Operation result:

Card(rank='4', suit='Plum blossom')
Card(rank='K', suit='Red heart')
Conclusion:
The process of random draw and shuffle in the above card games is just using the built-in method, not using our own method The method of definition is implemented, and it should be noted that: "getitem" and object [index], "len" and choice "," setitem "and" shuffle "
Must be used together
Built in function, built-in module, built-in built-in method of basic type < --- > class, for example: = = =======================================================================__

 

5. Total code: the process of random card picking and shuffling in card games
# Through objects in circular order[Indexes]Arbitrary card taking
# choice The process of randomly selecting a card
# shuffle The process of random shuffling
import json
from collections import namedtuple
Card = namedtuple('Card',['rank','suit'])  # rank Deck size, suit Deck Decor
class FranchDeck:
    ranks = [str(n) for n in range(2,11)]+list('JQKA')
    suits = ['Red heart','Square plate','Plum blossom','Spade']
    def __init__(self):
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits]
        # Nested loop,Each round takes a card and saves it to a list,The cards in this one are in a circular order

    def __getitem__(self, item):  # By object[Indexes]Trigger
         return self._cards[item]

    def __len__(self):  # adopt choice Trigger
         return len(self._cards)  # The length of a passing card is drawn from so many cards

    def __setitem__(self, key, value):  # adopt shuffle Trigger
        self._cards[key] = value

    def __str__(self):
         return json.dumps(self._cards,ensure_ascii=False)  # serialize

deck = FranchDeck()

# By object[Indexes]and__getitem__To extract the corresponding cards in a circular and sequential way
print(deck[10])  # When an object is indexed, the retrieval is triggered__getitem__Method

# adopt choice and__len__The process of randomly selecting a card
from random import choice
print(choice(deck))
# choice The ability to randomly draw cards depends on the built-in__len__Method, if not previously defined__len__Method will report error
print(deck[10])

# adopt shuffle and__setitem__The process of random shuffling
from random import shuffle
shuffle(deck)
print(deck[10])
print(deck)  # Serialization is required

print(deck[:5])  # Slicing directly with objects

Operation result:

Card(rank='4', suit='Plum blossom')
Card(rank='A', suit='Red heart')
Card(rank='4', suit='Plum blossom')
Card(rank='A', suit='Plum blossom')
[["6", "Plum blossom"], ["9", "Plum blossom"], ["3", "Plum blossom"], ["9", "Square plate"], ["4", "Square plate"], ["Q", "Red heart"], ["7", "Red heart"], ["J", "Spade"], ["8", "Plum blossom"], ["J", "Red heart"], ["A", "Plum blossom"], ["6", "Spade"], ["Q", "Square plate"], ["4", "Plum blossom"], ["10", "Red heart"], ["A", "Red heart"], ["4", "Red heart"], ["7", "Square plate"], ["5", "Spade"], ["K", "Spade"], ["2", "Square plate"], ["Q", "Plum blossom"], ["2", "Spade"], ["8", "Spade"], ["J", "Plum blossom"], ["A", "Spade"], ["2", "Red heart"], ["6", "Red heart"], ["5", "Red heart"], ["J", "Square plate"], ["10", "Square plate"], ["K", "Square plate"], ["K", "Red heart"], ["3", "Red heart"], ["8", "Red heart"], ["8", "Square plate"], ["5", "Square plate"], ["K", "Plum blossom"], ["9", "Red heart"], ["5", "Plum blossom"], ["7", "Spade"], ["3", "Square plate"], ["Q", "Spade"], ["2", "Plum blossom"], ["7", "Plum blossom"], ["4", "Spade"], ["9", "Spade"], ["10", "Plum blossom"], ["6", "Square plate"], ["3", "Spade"], ["10", "Spade"], ["A", "Square plate"]]
[Card(rank='6', suit='Plum blossom'), Card(rank='9', suit='Plum blossom'), Card(rank='3', suit='Plum blossom'), Card(rank='9', suit='Square plate'), Card(rank='4', suit='Square plate')]

Topics: Python JSON