beginning implementations of CardCollection and some of its subclasses

This commit is contained in:
2020-03-17 22:43:03 -04:00
parent 2e676e4708
commit c1120bcd93
7 changed files with 57 additions and 1 deletions

View File

@@ -0,0 +1,2 @@
from ._card import Card
from ._playingcard import PlayingCard

View File

@@ -1,6 +1,6 @@
from itertools import chain
from .card import Card
from . import Card
class PlayingCard(Card):

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,10 @@
from collections import deque
from .. import Card
class CardCollection(deque):
def __init__(self, iterable, maxlen=None):
if not len(iterable) == 0 or all([isinstance(Card, item) for item in iterable]):
raise TypeError("CardCollections must only contain Cards")
else:
super().__init__(iterable, maxlen)

View File

@@ -0,0 +1,34 @@
from collections.abc import Iterable
from itertools import cycle
from more_itertools import random_permutation
from ._cardcollection import CardCollection
class Deck(CardCollection):
def draw(self):
return self.pop()
def shuffle(self):
shuffled = list(random_permutation(self))
self.clear()
self.extend(shuffled)
return self
def deal(self, card_collections, cards_per_rotation=1, max_rotations=None):
if not issubclass(card_collections, Iterable) or not all([issubclass(CardCollection, collection) for collection in card_collections]):
raise TypeError("You can only deal cards to an iterable containing CardCollections")
if max_rotations is None:
rotation = cycle(card_collections)
elif isinstance(max_rotations, int):
rotation = card_collections * max_rotations
else:
raise TypeError("Max rotations should be a positive integer")
for card_collection in rotation:
try:
for _ in range(cards_per_rotation):
card_collection.append(self.draw())
except IndexError:
break

View File

@@ -0,0 +1,9 @@
from itertools import product, starmap
from ._deck import Deck
from .. import PlayingCard
class PlayingCardDeck(Deck):
def __init__(self):
#initialize the deck with the product of the ranks and suits
super().__init__(list(starmap(PlayingCard, product(PlayingCard.ranks.keys(), PlayingCard.suits.keys()))))