Been a while away from PHP, what SPL interface?
Posted: Thu Nov 08, 2012 2:05 pm
Hello Devnet! It's been a long time! I've taken almost a year break from PHP for various reasons (not least of which was a detour into Ruby/Rails and various other technologies), resulting in my being a tad bit rusty. I'm doing a little personal project just to brush up and make sure I still understand PHP's newest features and its SPL. So, a question I have is, what would be the best SPL interface to use in order to create a "deck of cards"? The deck will consist, basically, of an array of "Card" objects. I want to be able to "deal" cards off the top of the deck in a loop (like array_shift), shuffle it, count() it, So something like:
I also need to be able to put cards back on the bottom of the deck (like array_push)
I want to be able to count and treat the deck as an array
I want to be able to cut the deck too (at a specific position)
I also want to be able to simply loop through the deck without "dealing" any cards
So... basically I need the deck to behave similar to an array, but there are all these SPL interfaces and classes like ArrayObject, Countable, and SeekableIterator and I'm not sure which one(s) are most appropriate for my class. What do y'all think?
Code: Select all
$deck = new Cards\Deck;
$deck->shuffle();
$players = Game\Hearts\Factory::buildPlayers(); // I haven't actually created any game/player code yet. this is pseudo-code.
// Deal out 13 cards to each player...
while ($deck->hasCards()) {
foreach ($players as $player) {
$card = $deck->deal();
$player->getHand()->addCard($card);
}
}Code: Select all
$deck = new Cards\Deck;
// .. snip
$deck->burn(); // takes a card off the top and places it on the bottom
$flop = $deck->deal(3);
// .. or ..
$turn = $deck->deal();
$deck->accept($players[3]->getHand()); // player 3 folds, so his cards go back on bottom
// .. or ..
$deck->accept($discard); // deck gets a player's discard and puts it on bottomCode: Select all
if (count($deck) != 52) {
throw new Cards\Exception\InvalidDeck('Deck is short of cards');
}
$lastcard = $deck[51];Code: Select all
$deck = new Cards\Deck;
$deck->shuffle();
$deck->cut(15); // Cuts the deck in half at the 15th card, and places the top half under the bottom halfCode: Select all
foreach ($deck as $card) {
// do something with $card but dont take it outta the deck
}