{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "___\n", "\n", "\n", "___\n", "
Content Copyright by Pierian Data
" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Milestone Project 2 - Complete Walkthrough Solution\n", "This notebook walks through a proposed solution to the Blackjack Game milestone project. The approach to solving and the specific code used are only suggestions - there are many different ways to code this out, and yours is likely to be different!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Game Play\n", "To play a hand of Blackjack the following steps must be followed:\n", "1. Create a deck of 52 cards\n", "2. Shuffle the deck\n", "3. Ask the Player for their bet\n", "4. Make sure that the Player's bet does not exceed their available chips\n", "5. Deal two cards to the Dealer and two cards to the Player\n", "6. Show only one of the Dealer's cards, the other remains hidden\n", "7. Show both of the Player's cards\n", "8. Ask the Player if they wish to Hit, and take another card\n", "9. If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.\n", "10. If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17\n", "11. Determine the winner and adjust the Player's chips accordingly\n", "12. Ask the Player if they'd like to play again" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Playing Cards\n", "A standard deck of playing cards has four suits (Hearts, Diamonds, Spades and Clubs) and thirteen ranks (2 through 10, then the face cards Jack, Queen, King and Ace) for a total of 52 cards per deck. Jacks, Queens and Kings all have a rank of 10. Aces have a rank of either 11 or 1 as needed to reach 21 without busting. As a starting point in your program, you may want to assign variables to store a list of suits, ranks, and then use a dictionary to map ranks to values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Game\n", "### Imports and Global Variables\n", "** Step 1: Import the random module. This will be used to shuffle the deck prior to dealing. Then, declare variables to store suits, ranks and values. You can develop your own system, or copy ours below. Finally, declare a Boolean value to be used to control while loops. This is a common practice used to control the flow of the game.**\n", "\n", " suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n", " ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n", " values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n", " 'Queen':10, 'King':10, 'Ace':11}" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import random\n", "\n", "suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n", "ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n", "values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n", " 'Queen':10, 'King':10, 'Ace':11}\n", "\n", "playing = True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Class Definitions\n", "Consider making a Card class where each Card object has a suit and a rank, then a Deck class to hold all 52 Card objects, and can be shuffled, and finally a Hand class that holds those Cards that have been dealt to each player from the Deck." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 2: Create a Card Class**
\n", "A Card object really only needs two attributes: suit and rank. You might add an attribute for \"value\" - we chose to handle value later when developing our Hand class.
In addition to the Card's \\_\\_init\\_\\_ method, consider adding a \\_\\_str\\_\\_ method that, when asked to print a Card, returns a string in the form \"Two of Hearts\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Card:\n", "\n", " def __init__(self,suit,rank):\n", " self.suit = suit\n", " self.rank = rank\n", " \n", " def __str__(self):\n", " return self.rank + ' of ' + self.suit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 3: Create a Deck Class**
\n", "Here we might store 52 card objects in a list that can later be shuffled. First, though, we need to *instantiate* all 52 unique card objects and add them to our list. So long as the Card class definition appears in our code, we can build Card objects inside our Deck \\_\\_init\\_\\_ method. Consider iterating over sequences of suits and ranks to build out each card. This might appear inside a Deck class \\_\\_init\\_\\_ method:\n", "\n", " for suit in suits:\n", " for rank in ranks:\n", "\n", "In addition to an \\_\\_init\\_\\_ method we'll want to add methods to shuffle our deck, and to deal out cards during gameplay.

\n", "OPTIONAL: We may never need to print the contents of the deck during gameplay, but having the ability to see the cards inside it may help troubleshoot any problems that occur during development. With this in mind, consider adding a \\_\\_str\\_\\_ method to the class definition." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Deck:\n", " \n", " def __init__(self):\n", " self.deck = [] # start with an empty list\n", " for suit in suits:\n", " for rank in ranks:\n", " self.deck.append(Card(suit,rank)) # build Card objects and add them to the list\n", " \n", " def __str__(self):\n", " deck_comp = '' # start with an empty string\n", " for card in self.deck:\n", " deck_comp += '\\n '+card.__str__() # add each Card object's print string\n", " return 'The deck has:' + deck_comp\n", "\n", " def shuffle(self):\n", " random.shuffle(self.deck)\n", " \n", " def deal(self):\n", " single_card = self.deck.pop()\n", " return single_card" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "TESTING: Just to see that everything works so far, let's see what our Deck looks like!" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The deck has:\n", " Two of Hearts\n", " Three of Hearts\n", " Four of Hearts\n", " Five of Hearts\n", " Six of Hearts\n", " Seven of Hearts\n", " Eight of Hearts\n", " Nine of Hearts\n", " Ten of Hearts\n", " Jack of Hearts\n", " Queen of Hearts\n", " King of Hearts\n", " Ace of Hearts\n", " Two of Diamonds\n", " Three of Diamonds\n", " Four of Diamonds\n", " Five of Diamonds\n", " Six of Diamonds\n", " Seven of Diamonds\n", " Eight of Diamonds\n", " Nine of Diamonds\n", " Ten of Diamonds\n", " Jack of Diamonds\n", " Queen of Diamonds\n", " King of Diamonds\n", " Ace of Diamonds\n", " Two of Spades\n", " Three of Spades\n", " Four of Spades\n", " Five of Spades\n", " Six of Spades\n", " Seven of Spades\n", " Eight of Spades\n", " Nine of Spades\n", " Ten of Spades\n", " Jack of Spades\n", " Queen of Spades\n", " King of Spades\n", " Ace of Spades\n", " Two of Clubs\n", " Three of Clubs\n", " Four of Clubs\n", " Five of Clubs\n", " Six of Clubs\n", " Seven of Clubs\n", " Eight of Clubs\n", " Nine of Clubs\n", " Ten of Clubs\n", " Jack of Clubs\n", " Queen of Clubs\n", " King of Clubs\n", " Ace of Clubs\n" ] } ], "source": [ "test_deck = Deck()\n", "print(test_deck)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! Now let's move on to our Hand class." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 4: Create a Hand Class**
\n", "In addition to holding Card objects dealt from the Deck, the Hand class may be used to calculate the value of those cards using the values dictionary defined above. It may also need to adjust for the value of Aces when appropriate." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Hand:\n", " def __init__(self):\n", " self.cards = [] # start with an empty list as we did in the Deck class\n", " self.value = 0 # start with zero value\n", " self.aces = 0 # add an attribute to keep track of aces\n", " \n", " def add_card(self,card):\n", " self.cards.append(card)\n", " self.value += values[card.rank]\n", " \n", " def adjust_for_ace(self):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "TESTING: Before we tackle the issue of changing Aces, let's make sure we can add two cards to a player's hand and obtain their value:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "test_deck = Deck()\n", "test_deck.shuffle()\n", "test_player = Hand()\n", "test_player.add_card(test_deck.deal())\n", "test_player.add_card(test_deck.deal())\n", "test_player.value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see what these two cards are:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Nine of Hearts\n", "Five of Hearts\n" ] } ], "source": [ "for card in test_player.cards:\n", " print(card)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! Now let's tackle the Aces issue. If a hand's value exceeds 21 but it contains an Ace, we can reduce the Ace's value from 11 to 1 and continue playing." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Hand:\n", " \n", " def __init__(self):\n", " self.cards = [] # start with an empty list as we did in the Deck class\n", " self.value = 0 # start with zero value\n", " self.aces = 0 # add an attribute to keep track of aces\n", " \n", " def add_card(self,card):\n", " self.cards.append(card)\n", " self.value += values[card.rank]\n", " if card.rank == 'Ace':\n", " self.aces += 1 # add to self.aces\n", " \n", " def adjust_for_ace(self):\n", " while self.value > 21 and self.aces:\n", " self.value -= 10\n", " self.aces -= 1 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We added code to the add_card method to bump self.aces whenever an ace is brought into the hand, and added code to the adjust_for_aces method that decreases the number of aces any time we make an adjustment to stay under 21." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 5: Create a Chips Class**
\n", "In addition to decks of cards and hands, we need to keep track of a Player's starting chips, bets, and ongoing winnings. This could be done using global variables, but in the spirit of object oriented programming, let's make a Chips class instead!" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Chips:\n", " \n", " def __init__(self):\n", " self.total = 100 # This can be set to a default value or supplied by a user input\n", " self.bet = 0\n", " \n", " def win_bet(self):\n", " self.total += self.bet\n", " \n", " def lose_bet(self):\n", " self.total -= self.bet" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A NOTE ABOUT OUR DEFAULT TOTAL VALUE:
\n", "Alternatively, we could have passed a default total value as an parameter in the \\_\\_init\\_\\_. This would have let us pass in an override value at the time the object was created rather than wait until later to change it. The code would have looked like this:\n", "\n", " def __init__(self,total=100):\n", " self.total = total\n", " self.bet = 0\n", "\n", "Either technique is fine, it only depends on how you plan to start your game parameters." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Function Defintions\n", "A lot of steps are going to be repetitive. That's where functions come in! The following steps are guidelines - add or remove functions as needed in your own program." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 6: Write a function for taking bets**
\n", "Since we're asking the user for an integer value, this would be a good place to use try/except. Remember to check that a Player's bet can be covered by their available chips." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def take_bet(chips):\n", " \n", " while True:\n", " try:\n", " chips.bet = int(input('How many chips would you like to bet? '))\n", " except ValueError:\n", " print('Sorry, a bet must be an integer!')\n", " else:\n", " if chips.bet > chips.total:\n", " print(\"Sorry, your bet can't exceed\",chips.total)\n", " else:\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We used a while loop here to continually prompt the user for input until we received an integer value that was within the Player's betting limit." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A QUICK NOTE ABOUT FUNCTIONS:
\n", "If we knew in advance what we were going to call our Player's Chips object, we could have written the above function like this:\n", "\n", " def take_bet():\n", " while True:\n", " try:\n", " player_chips.bet = int(input('How many chips would you like to bet? '))\n", " except ValueError:\n", " print('Sorry, a bet must be an integer!')\n", " else:\n", " if player_chips.bet > player_chips.total:\n", " print(\"Sorry, your bet can't exceed\",player_chips.total)\n", " else:\n", " break\n", "\n", "and then we could call the function without passing any arguments. This is generally not a good idea! It's better to have functions be self-contained, able to accept any incoming value than depend on some future naming convention. Also, this makes it easier to add players in future versions of our program!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 7: Write a function for taking hits**
\n", "Either player can take hits until they bust. This function will be called during gameplay anytime a Player requests a hit, or a Dealer's hand is less than 17. It should take in Deck and Hand objects as arguments, and deal one card off the deck and add it to the Hand. You may want it to check for aces in the event that a player's hand exceeds 21." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def hit(deck,hand):\n", " \n", " hand.add_card(deck.deal())\n", " hand.adjust_for_ace()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 8: Write a function prompting the Player to Hit or Stand**
\n", "This function should accept the deck and the player's hand as arguments, and assign playing as a global variable.
\n", "If the Player Hits, employ the hit() function above. If the Player Stands, set the playing variable to False - this will control the behavior of a while loop later on in our code." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def hit_or_stand(deck,hand):\n", " global playing # to control an upcoming while loop\n", " \n", " while True:\n", " x = input(\"Would you like to Hit or Stand? Enter 'h' or 's' \")\n", " \n", " if x[0].lower() == 'h':\n", " hit(deck,hand) # hit() function defined above\n", "\n", " elif x[0].lower() == 's':\n", " print(\"Player stands. Dealer is playing.\")\n", " playing = False\n", "\n", " else:\n", " print(\"Sorry, please try again.\")\n", " continue\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Step 9: Write functions to display cards**
\n", "When the game starts, and after each time Player takes a card, the dealer's first card is hidden and all of Player's cards are visible. At the end of the hand all cards are shown, and you may want to show each hand's total value. Write a function for each of these scenarios." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def show_some(player,dealer):\n", " print(\"\\nDealer's Hand:\")\n", " print(\"