Blackjack

Blackjack is a simple, popular card game that is played in many casinos. Cards in Blackjack have the following values: an ace may be valued as either 1 or 11 (player’s choice), face cards (kings, queens and jacks) are valued at 10 and the value of the remaining cards corresponds to their number. During a round of Blackjack, the players plays against a dealer with the goal of building a hand (a collection of cards) whose cards have a total value that is higher than the value of the dealer’s hand, but not over 21. (A round of Blackjack is also sometimes referred to as a hand.)

The game logic for our simplified version of Blackjack is as follows. The player and the dealer are each dealt two cards initially with one of the dealer’s cards being dealt faced down (his hole card). The player may then ask for the dealer to repeatedly “hit” his hand by dealing him another card. If, at any point, the value of the player’s hand exceeds 21, the player is “busted” and loses immediately. At any point prior to busting, the player may “stand” and the dealer will then hit his hand until the value of his hand is 17 or more. (For the dealer, aces count as 11 unless it causes the dealer’s hand to bust). If the dealer busts, the player wins. Otherwise, the player and dealer then compare the values of their hands and the hand with the higher value wins. The dealer wins ties in our version.

Mini-project development process

We suggest you develop your Blackjack game in two phases. The first phase will concentrate on implementing the basic logic of Blackjack while the second phase will focus on building a more full-featured version. In phase one, you will use buttons to control the game and print the state of the game to the console using print statements. In the second phase, you will replace the print statements by drawing images and text on the canvas and add some extra game logic.

In phase one, we will provide testing templates for four of the steps. The templates are designed to check whether your class implementations work correctly. You should copy your class definition into the testing template and compare the console output generated by running the template with the provided output. If the output matches, it is likely that your implementation of the class is correct. DO NOT PROCEED TO THE NEXT STEP UNTIL YOUR CODE WORKS WITH THE PROVIDED TESTING TEMPLATE. Debugging code that uses incorrectly implemented classes is extremely difficult. Avoid this problem by using our provided testing templates.

Phase one
  1. Download the program template for this mini-project and review the class definition for the Card class. This class is already implemented so your task is to familiarize yourself with the code. Start by pasting the Card class definition into the provided testing template and verifying that our implementation works as expected.
  2. Implement the methods __init__, __str__, add_card for the Hand class. We suggest modeling a hand as a list of Card objects that are stored in a field in the Hand object. The __init__ method should initialize the Hand object to have an empty list of Card objects. The add_card should append a Card object to this list of cards. The __str__ method should return a string representation of a Hand object in a human-readable form. For help in implementing the __str__ method, refer back to the solution to question four in the Practice Exercises for week 5a. Remember to use the string method for Card objects to convert each card in the hand’s list of cards into a string. (Don’t convert a Card object into a string in add_card to make your string method work.) Once you have implemented the Hand class, test it using the provided testing template.
  3. Implement the methods for the Deck class listed in the mini-project template. We suggest modeling a deck of cards as list of cards. You can generate this list using a pair of nested for loops or a list comprehension. Remember to use the Card initializer to create your cards. Use random.shuffle() to shuffle this deck of cards. Once you have implemented the Deck class, test your Deck class using the provided testing template. Remember that the deck is randomized after shuffling, so the output of the testing template should match the output in the comments in form but not in exact value.
  4. Implement the handler for a “Deal” button that shuffles the deck and deals the two cards to both the dealer and the player. The event handler deal for this button should shuffle the deck (stored as a global variable), create new player and dealer hands (stored as global variables), and add two cards to each hand. To transfer a card from the deck to a hand, you should use the deal_card method of the Deck class and the add_card method of Hand class in combination. The resulting hands should be printed to the console with an appropriate message indicating which hand is which.
  5. Implement the get_value method for the Hand class. You should use the provided VALUE dictionary to look up the value of a single card in conjunction with the logic explained in the video lecture for this project to compute the value of a hand. Once you have implemented the get_value method, test it using the provided testing template.
  6. Implement the handler for a “Hit” button. If the value of the hand is less than or equal to 21, clicking this button adds an extra card to player’s hand. If the value exceeds 21 after being hit, print “You have busted”.
  7. Implement the handler for a “Stand” button. If the player has busted, remind the player that they have busted. Otherwise, repeatedly hit the dealer until his hand has value 17 or more (using a while loop). If the dealer busts, let the player know. Otherwise, compare the value of the player’s and dealer’s hands. If the value of the player’s hand is less than or equal to the dealer’s hand, the dealer wins. Otherwise the player has won. Remember the dealer wins ties in our version.

In our version of Blackjack, a hand is automatically dealt to the player and dealer when the program starts. In particular, the program template includes a call to the deal() function during initialization. At this point, we would suggest testing your implementation of Blackjack extensively.

Phase two

In the second phase of your implementation, you will add five features. For those involving drawing with global variables, remember to initialize these variables to appropriate values (like creating empty hands for the player and dealer) just before starting the frame.

  1. Implement your own draw method for the Hand class using the draw method of the Card class. We suggest drawing a hand as a horizontal sequence of cards where the parameter pos is the position of the upper left corner of the leftmost card. To simplify your code, you may assume that only the first five cards of a player’s hand need to be visible on the canvas.
  2. Replace printing in the console by drawing text messages on the canvas. We suggest adding a global outcome string that is drawn in the draw handler using draw_text. These messages should prompt the player to take some require action and have a form similar to “Hit or stand?” and “New deal?”. Also, draw the title of the game, “Blackjack”, somewhere on the canvas.
  3. Add logic using the global variable in_play that keeps track of whether the player’s hand is still being played. If the round is still in play, you should draw an image of the back of a card (provided in the template) over the dealer’s first (hole) card to hide it. Once the round is over, the dealer’s hole card should be displayed.
  4. Add a score counter that keeps track of wins and losses for your Blackjack session. In the simplest case (see our demo), the program displays wins minus losses. However, you are welcome to implement a more sophisticated betting/scoring system.
  5. Modify the logic for the “Deal” button to create and shuffle a new deck (or restock and shuffle an existing deck) each time the “Deal” button is clicked. This change avoids the situation where the deck becomes empty during play.
  6. Finally, modify the deal function such that, if the “Deal” button is clicked during the middle of a round, the program reports that the player lost the round and updates the score appropriately.

Congratulations! You have just built Blackjack. To wrap things up, please review the demo of our version of Blackjack in the Blackjack video lecture to ensure that your version has full functionality.

Grading Rubric - 18 pts total (scaled to 100 pts)

  • 1 pt - The program displays the title “Blackjack” on the canvas.
  • 1 pt - The program displays 3 buttons (“Deal”, “Hit” and “Stand”) in the control area.
  • 2 pts - The program graphically displays the player’s hand using card images. (1 pt if text is displayed in the console instead)
  • 2 pts - The program graphically displays the dealer’s hand using card images. Displaying both of the dealer’s cards face up is allowable when evaluating this bullet. (1 pt if text displayed in the console instead)
  • 1 pt - The dealer’s hole card is hidden until the current round is over. After the round is over, it is displayed.
  • 2 pts - Pressing the “Deal” button deals out two cards each to the player and dealer. (1 pt per player)
  • 1 pt - Pressing the “Deal” button in the middle of the round causes the player to lose the current round.
  • 1 pt - Pressing the “Hit” button deals another card to the player.
  • 1 pt - Pressing the “Stand” button deals cards to the dealer as necessary.
  • 1 pt - The program correctly recognizes the player busting.
  • 1 pt - The program correctly recognizes the dealer busting.
  • 1 pt - The program correctly computes hand values and declares a winner. Evaluate based on messages.
  • 2 pts - The program accurately prompts the player for an action with messages similar to “Hit or stand?” and “New deal?”. (1 pt per message)
  • 1 pt - The program implements a scoring system that correctly reflects wins and losses. Please be generous in evaluating this item.

Submission

# Mini-project #6 - Blackjack

import simplegui
import random

# load card sprite - 936x384 - source: jfitz.com
CARD_SIZE = (72, 96)
CARD_CENTER = (36, 48)
card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png")

CARD_BACK_SIZE = (72, 96)
CARD_BACK_CENTER = (36, 48)
card_back = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/card_jfitz_back.png")    

# initialize some useful global variables
in_play = False
outcome = "Press Deal button!"
score = 0
win, lose = 0, 0

# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}


# define card class
class Card:
    def __init__(self, suit, rank):
        if (suit in SUITS) and (rank in RANKS):
            self.suit = suit
            self.rank = rank
        else:
            self.suit = None
            self.rank = None
            print "Invalid card: ", suit, rank
        self.show = True

    def __str__(self):
        return self.suit + self.rank

    def get_suit(self):
        return self.suit

    def get_rank(self):
        return self.rank

    def draw(self, canvas, pos):
        if self.show:
            card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), 
                        CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
            canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
        else:
            canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
       
        
# define hand class
class Hand:
    def __init__(self):
        self.cards = list()  # create Hand object

    def __str__(self):
        ans = "Hand contains "
        for item in self.cards:
            ans += str(item) + " "
        return ans  # return a string representation of a hand

    def add_card(self, card):
        self.cards.append(card) # add a card object to a hand

    def get_value(self):
        # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust
        value = 0
        aces = 0
        for card in self.cards:
            rank = card.get_rank()
            value += VALUES.get(rank)
            if rank == "A":
                aces += 1
        if aces == 0:
            return value
        else:
            if value + 10 <= 21:
                return value + 10
            else:
                return value
   
    def draw(self, canvas, pos):
        # draw a hand on the canvas, use the draw method for cards
        for i in range(len(self.cards)):
            self.cards[i].draw(canvas, (pos[0] + (80 * i), pos[1]))
        
# define deck class 
class Deck:
    def __init__(self):
        self.cards = list()  # create a Deck object
        for suit in SUITS:
            for rank in RANKS:
                self.cards.append(Card(suit, rank))

    def shuffle(self):
        # shuffle the deck 
        random.shuffle(self.cards)    # use random.shuffle()

    def deal_card(self):
        return self.cards.pop() # deal a card object from the deck
    
    def __str__(self):
        ans = "Deck contains "
        for item in self.cards:
            ans += str(item) + " "
        return ans  # return a string representing the deck




#define event handlers for buttons
def deal():
    global outcome, in_play, deck, dealer, player, win, lose
    if in_play:
        lose += 1
    deck = Deck()
    deck.shuffle()
    dealer = Hand()
    player = Hand()
    for time in range(2):
        dealer.add_card(deck.deal_card())
        player.add_card(deck.deal_card())
    # print "Dealer: ", str(dealer)
    # print "Player: ", str(player)
    dealer.cards[0].show = False
    in_play = True
    outcome = "Hit or Stand?"

def hit():
    global outcome, in_play, player, win, lose
    if not in_play:
        return
    if player.get_value() <= 21:
        player.add_card(deck.deal_card())
        # print "Player: ", str(player)
        outcome = "Hit or Stand?"
    else:
        # print "You have busted"
        outcome = "You have busted! New deal?"
        in_play = False
        dealer.cards[0].show = True
        lose += 1
    
    
def stand():
    global outcome, in_play, player, dealer, win, lose
    if not in_play:
        return
    if player.get_value() > 21:
         # print "You have busted"
        outcome = "You have busted! New deal?"
        in_play = False
        dealer.cards[0].show = True
        lose += 1
    else:         
        while dealer.get_value() < 17:
            dealer.add_card(deck.deal_card())
        # print "Dealer: ", str(dealer)
        if dealer.get_value() > 21:
            # print "Dealer Busted!"
            outcome = "Dealer Busted! New deal?"
            in_play = False
            dealer.cards[0].show = True
            win += 1
        elif dealer.get_value() < player.get_value():
            # print "You win!"
            outcome = "You win! New deal?"
            in_play = False
            dealer.cards[0].show = True
            win += 1
        else:
            # print "You lose."
            outcome = "You lose. New deal?"
            in_play = False
            dealer.cards[0].show = True
            lose += 1
    
    
    
    
    
# draw handler    
def draw(canvas):
    # test to make sure that card.draw works, replace with your code below
    canvas.draw_text("BLACKJACK", (20,50), 40, "Black")
    canvas.draw_text("Dealer", (80,130), 25, "White")
    dealer.draw(canvas, (100, 150))
    canvas.draw_text("Player", (80,280), 25, "White")
    player.draw(canvas, (100, 300))
    canvas.draw_text(outcome, (180, 280), 30, "Silver")
    canvas.draw_text("Win: ", (320, 40), 30, "White")
    canvas.draw_text(str(win), (400, 40), 30, "White")
    canvas.draw_text("Lose: ", (320, 70), 30, "White")
    canvas.draw_text(str(lose), (400, 70), 30, "White")
    


# initialization frame
frame = simplegui.create_frame("Blackjack", 600, 600)
frame.set_canvas_background("Green")

#create buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit",  hit, 200)
frame.add_button("Stand", stand, 200)
frame.set_draw_handler(draw)


# get things rolling
dealer = Hand()
player = Hand()
frame.start()


# remember to review the gradic rubric