RobsonLittle Red Book ▸ Shuffle and deal

Chapter 7 - Question 16

Represent a pack of card with a suitable data structure. Design a program to shuffle the pack and then deal sample poker or bridge hands.

Solution 1

I've never played bridge before so I don't know what the hands are like in that. I think in normal versions of poker, players are dealt five cards, so that's what I'll do.

<?    // the possible ranks    $ranks = array('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King');    // the possible suits    $suits = array('Clubs', 'Diamonds', 'Hearts', 'Spades');    // make up some players    $players = array('Fred', 'Tim', 'Larry', 'Bob');        // create 52 cards    for ($n = 0; $n < 52; $n++)    {        // work out the rank of the card        $cards[$n]['rank'] = $n % 13;        // work out the suit of the card        $cards[$n]['suit'] = intval($n / 13);    }        // multiple packs of cards could be merged here, like this:    //$cards = array_merge($cards, $cards);        // this is a very appropriately named function!    shuffle($cards);        // deal out several hands    foreach($players as $player)    {        // show the hand number and start the list        echo $player . "'s hand:<ul>";        // in normal poker, the player would be dealt the next five cards from the deck        // so that behaviour is replicated here        for ($n = 0; $n <= 4; $n++)            // show the card rank and suit            echo '<li>' . $ranks[$cards[($hand * 5) + $n]['rank']] . ' of ' . $suits[$cards[($hand * 5) + $n]['suit']] . '</li>';        // increment the hands that have been dealt        $hand++;        // end the list        echo '</ul>';    } ?>

Which produces:

Fred's hand:
  • Two of Spades
  • Queen of Spades
  • Five of Diamonds
  • Five of Clubs
  • King of Hearts
Tim's hand:
  • Ace of Clubs
  • Seven of Diamonds
  • Eight of Diamonds
  • Seven of Spades
  • Queen of Diamonds
Larry's hand:
  • King of Clubs
  • Seven of Hearts
  • Eight of Spades
  • Three of Hearts
  • Four of Spades
Bob's hand:
  • Four of Diamonds
  • Five of Spades
  • Ten of Diamonds
  • Three of Spades
  • Two of Hearts

Log

© 2004-20 robson | cc unless stated