Skip to content

Commit

Permalink
Merge pull request #5 from smpotts/cards
Browse files Browse the repository at this point in the history
Cards, Deck and Hand code
  • Loading branch information
smpotts authored Jun 14, 2024
2 parents 5989a25 + 625d38f commit 55e2d43
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/card.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Card:
# instance attributes
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Queen', 'King']

def __init__(self, suit=0, rank=2):
# defaults to a 2 of Clubs

# class attributes
self.suit = suit
self.rank = rank

def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])

def __lt__(self, other):
# using tuple comparison
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return t1 < t2
31 changes: 31 additions & 0 deletions src/deck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from random import random

from src.card import Card


class Deck:

def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)

def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)

def pop_card(self):
return self.cards.pop()

def add_card(self, card):
self.cards.append(card)

def shuffle(self):
random.shuffle(self.cards)

def sort(self):
self.cards.sort()
12 changes: 12 additions & 0 deletions src/hand.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from src.deck import Deck


class Hand(Deck):

def init__(self, label=''):
self.cards = []
self.label = label

def move_cards(self, hand, num):
for i in range(num):
hand.add_card(self.pop_card())
17 changes: 17 additions & 0 deletions tests/test_card.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import unittest
from src.card import Card


class TestCard(unittest.TestCase):
def test_init_card(self):
init_card = Card()
self.assertEqual(init_card.suit, 0)
self.assertEqual(init_card.rank, 2)

def test_str(self):
card1 = Card(2, 11)
print(card1)


if __name__ == '__main__':
unittest.main()
12 changes: 12 additions & 0 deletions tests/test_deck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import unittest
from src.deck import Deck


class TestDeck(unittest.TestCase):
def test_deck_init(self):
d = Deck()
print(d)


if __name__ == '__main__':
unittest.main()

0 comments on commit 55e2d43

Please # to comment.