Python Forum
I need help understanding a program structure using classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need help understanding a program structure using classes
#19
I think you should look again at this post by deanhystad. It is an excellent example of how python and OOP work.
(Dec-24-2021, 01:32 PM)deanhystad Wrote: I think you should make a Card class and a Hand class. The Card class knows how to do things like print its name and sort itself among a list of cards. The Hand class would know how to identify pairs and flushes. Mine is incomplete but should give some idea of how this could be done. The Player would be delt a hand, place bets and acquire or pay out chips.
import collections
import random

class Card():
    """A playing card that has a rank and suit"""
    # These are class variables.  They are associated with the class, not instances of the class
    suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
    rank_names = ["", "", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
    short_rank_names = ["", "", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
    rank_range = range(2, 15)

    def __init__(self, rank, suit):
        # These are instance variables.  Each instance has their own rank an suit
        self.rank = rank
        self.suit = suit

    def __lt__(self, other):
        """For sorting and comparing by rank"""
        return self.rank < other.rank  # self.rank is my rank.  other.rank is the rank of another card

    def __gt__(self, other):
        """For sorting and comparing by rank"""
        return self.rank > other.rank

    def __eq__(self, other):
        """For sorting and comparing by rank"""
        return self.rank == other.rank

    def name(self):
        """Get long name for card"""
        return f"{self.rank_names[self.rank]} {self.suit}"

    def __repr__(self):
        """Get short name for card"""
        return f"{self.short_rank_names[self.rank]}{self.suit[0]}"

class Hand():
    """A list of cards"""
    def __init__(self, cards=None):
        self.cards = [] if cards is None else cards

    def ranks(self):
        """Get list of card ranks and their count.  Use to identify pairs, 3 of a kind etc"""
        def sort_key(counter):
            """Sorting key function for (rank, count) tuples"""
            return (counter[1], counter[0])

        items = list(collections.Counter([card.rank for card in self.cards]).items())
        items.sort(key=sort_key, reverse=True)
        return items

    def suit(self, suit):
        """Get list of cards in specified suit"""
        ranks = [card.rank for card in self.cards if card.suit == suit]
        ranks.sort()
        return ranks

    def suits(self):
        """Get dictionary of cards grouped by suit.  Use to identify flushes"""
        return {suit:self.suit(suit) for suit in Card.suit_names}

    def __repr__(self):
        """Print cards in hand"""
        return ", ".join([str(card) for card in self.cards])


class Deck():
    """Deck of cards"""
    def __init__(self, shuffle=False):
        self.cards = [Card(rank, suit) for rank in Card.rank_range for suit in Card.suit_names]
        if shuffle:
            random.shuffle(self.cards)

    def __len__(self):
        """Return number of cards in deck"""
        return len(self.cards)

    def deal(self, count):
        """Deal count cards from top of deck"""
        cards = self.cards[:count]
        self.cards = self.cards[count:]
        return cards

deck = Deck(True)
hands = [Hand(deck.deal(5)) for _ in range(2)]
for hand in hands:
    print("Hand", hand)
    print("Ranks", hand.ranks())
    print("Suits", hand.suits())
Output:
Hand 4C, 2D, 10D, 2S, 7D Ranks [(2, 2), (10, 1), (7, 1), (4, 1)] Suits {'Clubs': [4], 'Diamonds': [2, 7, 10], 'Hearts': [], 'Spades': [2]} Hand QS, 8H, 5D, 6C, AS Ranks [(14, 1), (12, 1), (8, 1), (6, 1), (5, 1)] Suits {'Clubs': [6], 'Diamonds': [5], 'Hearts': [8], 'Spades': [12, 14]}
Reply


Messages In This Thread
RE: I need help understanding a program structure using classes - by BashBedlam - Dec-27-2021, 03:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Understanding Python classes PythonNewbee 3 1,322 Nov-10-2022, 11:07 PM
Last Post: deanhystad
  Understanding Python super() for classes OmegaRed94 1 1,927 Jun-09-2021, 09:02 AM
Last Post: buran
  Understanding program blocks newbieAuggie2019 2 2,090 Oct-02-2019, 06:22 PM
Last Post: newbieAuggie2019
  help with understanding a program prompt drasil 5 3,094 Feb-14-2019, 05:54 PM
Last Post: ichabod801
  Help, not understanding how classes work... Peter_EU 1 2,429 Jan-20-2018, 06:07 PM
Last Post: wavic
  Using classes? Can I just use classes to structure code? muteboy 5 5,212 Nov-01-2017, 04:20 PM
Last Post: metulburr
  I need help understanding how to use and run this program! Thanks in advance! tc1chosen 6 4,933 Sep-01-2017, 01:56 PM
Last Post: tc1chosen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020