Card game
import json
from collections import namedtuple
"""
Tuple also has a brother called namedtuple. Although they are all tuples, they are more powerful.
For namedtuple, you don’t have to access it by index value anymore, you can think of it as a dictionary
Access by name, but the value cannot be changed.
"""
Card = namedtuple("Card", ["rank< span style="color: #800000;">", "suit"]) # rank is the card size, suit is the suit
class FranchDeck:
ranks = [str(n) for n in range(2, 11)] + list("JQKA") # Card size
suits = ["Red hearts", "Spades", "square piece", "梅花< /span>"]
def __init__(self):
self.__cards = [Card(rank, suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits] # Loop nesting, get numbers, suits
def __len__(self):
return len(self.__cards)
def __getitem__(self, item):
return self.__cards[item]
def __setitem__(self, key, value):
self.__cards[key] = value
def __str__(self):
return json.dumps(self._cards, ensure_ascii=False)
deck = FranchDeck()
print(deck[10]) # Get cards
# Shuffle
from random import choice
print(choice(deck))
print(choice(deck))
# Slice
from random import shuffle
shuffle(deck)
print(deck[10])
print(deck[:5])
import json
from collections import namedtuple
"""
Tuple also has a brother called namedtuple. Although they are all tuples, they are more powerful.
For namedtuple, you don’t have to access it by index value anymore, you can think of it as a dictionary
Access by name, but the value cannot be changed.
"""
Card = namedtuple("Card", ["rank< span style="color: #800000;">", "suit"]) # rank is the card size, suit is the suit
class FranchDeck:
ranks = [str(n) for n in range(2, 11)] + list("JQKA") # Card size
suits = ["Red hearts", "Spades", "square piece", "梅花< /span>"]
def __init__(self):
self.__cards = [Card(rank, suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits] # Loop nesting, get numbers, suits
def __len__(self):
return len(self.__cards)
def __getitem__(self, item):
return self.__cards[item]
def __setitem__(self, key, value):
self.__cards[key] = value
def __str__(self):
return json.dumps(self._cards, ensure_ascii=False)
deck = FranchDeck()
print(deck[10]) # Get cards
# Shuffle
from random import choice
print(choice(deck))
print(choice(deck))
# Slice
from random import shuffle
shuffle(deck)
print(deck[10])
print(deck[:5])