liveBook · Manning

Card

As explained in Get Programming: Learn to code with Python

A playing card is a game object identified by a rank and a suit.

A card is a game object identified by a rank and a suit. In the War game, cards are represented as short strings such as "2H" for the 2 of hearts or "7S" for the 7 of spades. section 34.2 section 34.3

Use these rules to represent and compare cards:

  • Build a deck with four suits—spades, hearts, diamonds, and clubs—and ranks from 2 through 9, producing 32 cards. section 34.2 section 34.4
  • Compare cards first by rank; when ranks match, use the order Spades > Hearts > Diamonds > Clubs. section 34.2 section 34.4
  • Give each player one card per round, transfer the lower card to the player holding the higher card, and stop when the deck is empty. section 34.5

A card in a player's hand

A Player stores cards as strings in a list. Adding "4D" places the 4 of diamonds in the hand; removing "4D" transfers it to the other player. section 34.3

Listing 34.3. Initialization for the CardDeck class
class CardDeck(object):
    """ A deck of cards 2-9 of spades, hearts, diamons, clubs """
    def __init__(self):
        """ a deck of cards (strings e.g. "2C" for the 2 of clubs)
            contains all cards possible """
        hearts = "2H,3H,4H,5H,6H,7H,8H,9H"                             #1
        diamonds = "2D,3D,4D,5D,6D,7D,8D,9D"                           #1
        spades = "2S,3S,4S,5S,6S,7S,8S,9S"                             #1
        clubs = "2C,3C,4C,5C,6C,7C,8C,9C"                              #1
        self.deck = hearts.split(',')+diamonds.split(',')  +  \        #2
                    spades.split(',')+clubs.split(',')

Inspect how all 32 card strings are assembled into a CardDeck list from four suit-specific strings. section 34.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines cards as strings in lists, specifies comparison rules, and applies them through Player and CardDeck classes.
Examples
Uses notations such as 2H, 4D, 7S, and 9C within a 32-card War deck.
What it assumes
Introduces cards while applying classes, methods, lists, strings, loops, and user input in one cumulative program.
What you can do after
Build it from scratch as part of a playable two-player War simulation using Player and CardDeck classes.
How it connects
Connects cards to classes, objects, strings, lists, random selection, and comparison methods.

Also explained in

Compare how 4 books explain card →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.