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