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.
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:Tim's hand:
- Queen of Diamonds
- Three of Clubs
- Eight of Clubs
- Two of Spades
- Ten of Diamonds
Larry's hand:
- Six of Hearts
- King of Clubs
- Queen of Clubs
- Seven of Spades
- Three of Diamonds
Bob's hand:
- Three of Hearts
- Eight of Diamonds
- Eight of Hearts
- Jack of Spades
- Five of Clubs
- Four of Clubs
- Four of Hearts
- King of Hearts
- Nine of Hearts
- Two of Hearts