Simulating a deck of cards

  • We have studied how to represent a deck of cards with an array of int:

  • In this lesson, we will represent a deck of cards using objects

  • We will also study how to implement these instance methods to:

      • Shuffle a deck of cards
      • Deal a card from a deck of cards

Defining a the Card class to represent a card

  • A card has the following properties:

      A suit (e.g.: Spades, Hearts, Diamond, Clubs)
      A rank (e.g.: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Quuen, King)

  • In our example, a card does not have any actions

  • The skeleton code for Card class that represents a cord is therefore:

    public class Card
    {
        private String suit;
        private String rank;
    
        Card(...) // Constructor to create a Card< object
        {
            ...
        }
    }

Defining a the Card class to represent a card

  • The Card class that represents a card:

    public class Card
    {
        private String suit;
        private String rank;
    
        public Card(String cardSuit, String cardRank)
        {
            suit = cardSuit;
            rank = cardRank;
        }
    
    }

    Let's create some Card objects and print them out...

How to use the Card class to make card objects

Sample program that uses the Card class:

public class myProg
{
    public static void main(String[] args)
    {
        Card c1 = new Card("Spades", "Ace");
        Card c2 = new Card("Hearts", "10");
        
        System.out.println( c1 );
        System.out.println( c2 );
    } 
}

You will see output like this:   Card@c72318e

I like to show you how to make the System.out.println( ) method output look nicer first...

The toString( ) method to return a String representation of objects

  • The System.out.println(object) call will always print the output of object.toString() :

    public class Card
    {
        private String suit;
        private String rank;
    
        public Card(String cardSuit, String cardRank)
        {
            suit = cardSuit;
            rank = cardRank;
        }
    
        // Define the toString() method to control object print out
        public String toString() // Used to print an object
        {
            return rank + " of " + suit;
        }
    }

How to use the Card class to make card objects

Run the same program that uses the Card class:

public class myProg
{
    public static void main(String[] args)
    {
        Card c1 = new Card("Spades", "Ace");
        Card c2 = new Card("Hearts", "10");
        
        System.out.println( c1 );
        System.out.println( c2 );
    } 
}

The output is now:   Ace of Spades !

Representing a deck of card with computer program

  • A computer program cannot replace a real deck of cards:

                

  • But, a computer program can imitate the things you can do with a deck of cards

  • We will imitate these "things that you can do" with a deck of cards:

      • Shuffle a deck of cards

      • Deal a card from a deck of cards

Defining a the DeckOfCards class to represent a deck of cards

  • A deck of cards has the following properties:

      52 playing cards consisting of:
    
          Ace of Spades,   2 of Spades,   ...., King of Spades
          Ace of Hearts,   2 of Hearts,   ...., King of Hearts
          Ace of Diamonds, 2 of Diamonds, ...., King of Diamonds
          Ace of Clubs,    2 of Clubs,    ...., King of Clubs

  • A deck of cards can perform the following actions:

      shuffle( ): re-arranges the cards randomly
                  After shuffle( ), all cards are available
    	      for dealing                              
                                       
      deal( ):    deals out the top of the card in the deck
                  A card that is dealt cannot be dealt again

Defining a the DeckOfCards class to represent a deck of cards

  • Representing the 52 cards in a deck:

      52 different cards:
    
                   
     
      Use: array of Card objects:
    
                   

Defining a the DeckOfCards class to represent a deck of cards

  • Representing the card shuffle action of a deck of cards:

      shuffle( ):
    
                   
     
      Use: random shuffle algorithm:
    
                   

Defining a the DeckOfCards class to represent a deck of cards

  • Representing the "deal a card" action of a deck of cards:

      deal( ): deal the next card from the deck
    
                   
     
      Use: variable dealPosition to mark the top position in deck:
    
                   

Defining a the DeckOfCards class to represent a deck of cards

Based on the properties and actions, the skeleton code for the DeckOfCards class is as follows:

public class DeckOfCards
{
    private Card[] deck;  // Hold 52 cards (to be created)
    private int    dealPosition;  // Location of the top card in deck

    DeckOfCards()  // Constructor to make a deck of cards
    {
       ....
    }

    public void shuffle() // Shuffle this deck of cards
    {
       perform a shuffle on the deck of cards   
    }
    
    public Card deal() // Deal the next card from this deck
    {
       returns the dealt card
    }
}  

The constructor of the DeckOfCards class

Making a deck of cards consists of making 52 specific cards:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition;

    DeckOfCards()  // Constructor to make a deck of cards
    {
        deck = new Card[52];    // Make a holder for 52 cards

        deck[0] = new Card( "Spades", "Ace");
        deck[1] = new Card( "Spades", "2");
        ...
        and so on 

        (How can we code this easily ??)
    }

    ...
}  

The constructor of the DeckOfCards class

Making a deck of cards consists of making 52 specific cards:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition;

    DeckOfCards()  // Constructor to make a deck of cards
    {
        deck = new Card[52];    // Make a holder for 52 cards
        // Define 2 arrays with all the suits and ranks
        String[] suit = {"Spades", "Hearts", "Diamonds", "Clubs"};
        String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8",
                         "9", "10", "Jack", "Queen", "King"};


 
       
        
         
        
       
    }
}  

The constructor of the DeckOfCards class

Making a deck of cards consists of making 52 specific cards:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition;

    DeckOfCards()  // Constructor to make a deck of cards
    {
        deck = new Card[52];    // Make a holder for 52 cards

        String[] suit = {"Spades", "Hearts", "Diamonds", "Clubs"};
        String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8",
                         "9", "10", "Jack", "Queen", "King"};
        int k = 0;   // Index into deck[ ]
        // Use a nested loop to make all 52 cards and assign to deck[ ]
        for ( int i = 0; i < suit.length; i++ )
            for (int j = 0; j < rank.length; j++ )
            {
                deck[k] = new Card( suit[i], rank[j] );
                k++;
            }
    }
}  

The shuffle() method of the DeckOfCards class

The shuffle() method will re-arrange the cards randomly and allow all cards to be dealt:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition;

    DeckOfCards() ...

    public void shuffle()  // Shuffle this deck of cards
    { 
        for (int i = 0; i < deck.length; i++) 
        { // Generate an index randomly
            int j = (int)(Math.random() * deck.length);

            Card temp = deck[i];   // Swap
            deck[i] = deck[j];
            deck[j] = temp;
        }
        
        dealPosition = 0;
    }
} 

The shuffle() method of the DeckOfCards class

Generate random numbers j and swap card[i] and card[j]:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition;

    DeckOfCards() ...

    public void shuffle()  // Shuffle this deck of cards
    {
        for (int i = 0; i < deck.length; i++) 
        {  // Generate an index j randomly
            int j = (int)(Math.random() * deck.length);

            Card temp = deck[i];   // Swap card[i] and card[j]
            deck[i] = deck[j];
            deck[j] = temp;
        }
         
        dealPosition = 0;
    }
} 

The shuffle() method of the DeckOfCards class

Reset a dealPosition variable that marks the index of the next card that will be dealt:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition; // Marks the position of next card

    DeckOfCards() ...

    public void shuffle()  // Shuffle this deck of cards
    {
        for (int i = 0; i < deck.length; i++) 
        {  // Generate an index j randomly
            int j = (int)(Math.random() * deck.length);

            Card temp = deck[i];   // Swap card[i] and card[j]
            deck[i] = deck[j];
            deck[j] = temp;
        }
       
        dealPosition = 0; // Reset the next deal card position
    }
} 

The deal() method of the DeckOfCards class

The deal() method will deal out (= returns) the next card in the deck of cards

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition; // Marks the position of next card

    DeckOfCards() ...

    public void shuffle() ...

    public void deal()  // deals (= returns) the next card in this deck
    {
        Card result = deck[dealPosition];

        dealPosition++;

        return result;
    }
} 

The deal() method of the DeckOfCards class

Save the next card in the deck in the variable nextCard:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition; // Marks the position of next card

    DeckOfCards() ...

    public void shuffle() ...

    public void deal()  // deals (= returns) the next card in this deck
    {
        Card nextCard = deck[dealPosition];

        dealPosition++;

        return nextCard;
    }
} 

The deal() method of the DeckOfCards class

Advance the dealPosition by 1 card (so we don't deal the same card out again):

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition; // Marks the position of next card

    DeckOfCards() ...

    public void shuffle() ...

    public void deal()  // deals (= returns) the next card in this deck
    {
        Card nextCard = deck[dealPosition];

        dealPosition++;

        return nextCard;
    }
} 

The deal() method of the DeckOfCards class

Return the saved next card:

public class DeckOfCards
{
    private Card[] deck;
    private int    dealPosition; // Marks the position of next card

    DeckOfCards() ...

    public void shuffle() ...

    public void deal()  // deals (= returns) the next card in this deck
    {
        Card nextCard = deck[dealPosition];

        dealPosition++;

        return nextCard;
    }
} 

How to use the DeckOfCards class

This Java program shows how to create one deck of cards and deal out some cards:

public class myProg
{
    public static void main(String[] args)
    {
        DeckOfCards d = new DeckOfCards();   // Create 1 deck of cards
        
        for ( int i = 0; i < 5; i++ )
            System.out.println( d.deal() );  // Deal out 5 cards
        System.out.println();
            
        d.shuffle();                         // Shuffle the deck d
        for ( int i = 0; i < 5; i++ )
            System.out.println( d.deal() );  // Deal out 5 cards after shuffle
    } 
} 

We can use the DeckOfCards class to create any number of decks of cards
The DeckOfCards class will help you write Java program that play card games !!!