Skip to content

Instantly share code, notes, and snippets.

@teamvista
Created October 23, 2016 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamvista/b2bdf52244dd320cfc81a692fc178e74 to your computer and use it in GitHub Desktop.
Save teamvista/b2bdf52244dd320cfc81a692fc178e74 to your computer and use it in GitHub Desktop.
PlayingCards created by teamvista - https://repl.it/EDQX/3
# Program Name: ch9_notes_blackjack_5.py
# Developer: James Daniel
# Date: 10/18/2016
# Description: Objects- Chapter 9 Interactive Notes
# Basics to OOP:
# Abstraction
# Encapsulation ===============
# Client code should:
# * communicate w/ objects through method params and return values,
# * avoid directly alering a value of an object's attribs
# Objects should:
# * Update their own attribs
# * Keep themselves safe by providing indirect access to attributes
# through methods
# =============================
# Reuse
# Inheritance
# Create classes to define objects
class Card(object): # "object" is a base class identifier
""" A playing card. """
# Class attributes
RANKS = ["A", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K"]
SUITS = ["\N{BLACK CLUB SUIT}", "\N{BLACK DIAMOND SUIT}",
"\N{BLACK HEART SUIT}", "\N{BLACK SPADE SUIT}"]
V_RANKS = ["Ace", "Deuce", '3', '4', '5', '6', '7', '8',
'9', '10', 'Jack', 'Queen', 'King']
V_SUITS = ['clubs', 'diamonds', 'hearts', 'spades']
RANK_VAL = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
HIGH_ACE = 11
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.value = self.RANK_VAL[self.RANKS.index(self.rank)]
def __str__(self):
st = self.rank + self.suit
return st
def expanded_str(self):
rank_num = self.RANKS.index(self.rank)
suit_num = self.SUITS.index(self.suit)
st = str(self.V_RANKS[rank_num])
st += " of {}".format(self.V_SUITS[suit_num])
return st
def get_cvalue(self):
return self.value
class UnprintableCard(Card):
def __str__(self):
return "###"
class PositionableCard(Card):
def __init__(self, rank, suit, face_up = True):
super(PositionableCard, self).__init__(rank,
suit)
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
st = super(PositionableCard, self).__str__()
else:
st = "###"
return st
def flip_card(self):
self.is_face_up = not self.is_face_up
class Hand(object):
""" A hand of playing cards. """
def __init__(self, name):
self.cards = []
self.name = name
def __str__(self):
if self.cards:
rep = ""
rep += ", ".join(str(i) for i in self.cards)
else:
rep = "No cards"
return rep
def __repr__(self):
if self.cards:
st = []
for card in self.cards:
st.append(str(card))
else:
st = "(empty)"
st = "<Hand object at {} with contents:\n{} />".format(
str(hex(id(self))), str(st))
return st
def __len__(self):
return len(self.cards)
def get_name(self):
return self.name
def get_dvalue(self):
v = 0
for card in self.cards:
v += Card.get_cvalue(card)
return v
def get_cards(self):
return self.cards
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand, verbose = False):
self.cards.remove(card)
other_hand.add(card)
if verbose:
print("From {}, gave {} to {}.".format(
self.get_name(),
card,
other_hand.get_name()))
def disp_hand(self):
print("{} cards in {}. Cards: {}".format(
len(self), self.get_name(), str(self)))
class Deck(Hand): # Inheritance from a base class
""" A deck of playing cards. """
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1, verbose = False):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand, verbose)
else:
print("Out of cards!")
def print_lhands(lhands):
out = ""
for i in lhands:
out += str(i.disp_hand()) + "\n"
return out
def run_trial(deck, seth):
active_deck = deck
active_set = seth
h1, h2, h3 = active_set
print(active_deck.get_name() + " before population: "
+ str(active_deck)) # <empty>
print()
active_deck.populate()
print(active_deck.get_name() + " after population: "
+ str(active_deck)) # ordered deck
print()
active_deck.shuffle()
active_deck.disp_hand()
print()
print_lhands(active_set)
print()
active_deck.deal(active_set, 5, verbose=True)
print()
print_lhands(active_set)
print()
print("Value of cards in {}: {}".format(
h2.get_name(), h2.get_dvalue()))
print()
active_deck.disp_hand()
active_deck.clear()
print("\nAfter deck clear:")
active_deck.disp_hand()
print_lhands(active_set)
print("\nPassing cards:")
h1.give(
h1.get_cards()[0],
h2,
verbose=True)
h2.give(
h2.get_cards()[0],
h3,
verbose=True)
h3.give(
h3.get_cards()[0],
h1,
verbose=True)
print()
print_lhands(active_set)
print()
def main():
deck1 = Deck("Deck #1")
a_hand = Hand("Alpha's hand")
b_hand = Hand("Bravo's hand")
c_hand = Hand("Charlie's hand")
deck2 = Deck("Deck #2")
d_hand = Hand("Delta's hand")
e_hand = Hand("Echo's hand")
f_hand = Hand("Foxtrot's hand")
deck3 = Deck("Deck #3")
g_hand = Hand("Golf's hand")
h_hand = Hand("Hotel's hand")
j_hand = Hand("Juliet's hand")
set1hands = [a_hand, b_hand, c_hand]
set2hands = [d_hand, e_hand, f_hand]
set3hands = [g_hand, h_hand, j_hand]
print("===Trial 1===")
active_deck = deck1
active_set = set1hands
run_trial(active_deck, active_set)
print("=" * 50)
print()
print("===Trial 2===")
active_deck = deck2
active_set = set2hands
run_trial(active_deck, active_set)
print("=" * 50)
print()
print("===Trial 3===")
active_deck = deck3
active_set = set3hands
run_trial(active_deck, active_set)
print("=" * 50)
print()
print("Derived card classes:")
uc1 = UnprintableCard("5", "♥")
print("Unprintable: " + str(uc1))
pc1 = PositionableCard("A", "♠")
print("Positionable, face up: " + str(pc1))
pc1.flip_card()
print("Positionable, face down: " + str(pc1))
print()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment