GitList
Repositories
Help
Report an Issue
blackjack
Code
Commits
Branches
Tags
Search
Tree:
d7b0224
Branches
Tags
master
blackjack
Objects
Deck.php
initial commit
Dev Ghai
commited
d7b0224
at 2014-04-17 16:55:27
Deck.php
Blame
History
Raw
<?php /** * User: dev * Date: 3/13/14 * Time: 9:24 AM */ namespace Blackjack\Objects; require_once 'Card.php'; /* * Using PHP_INT_MAX values so that they do not intersect with other integer constants anywhere. * Suits don't matter in Blackjack. */ define('HEARTS', 'Hearts'); define('DIAMONDS', 'Diamonds'); define('CLUBS', 'Clubs'); define('SPADES', 'Spades'); class Deck { public $cards = array(); private function GenerateDeck() { $suits = array(HEARTS, DIAMONDS, CLUBS, SPADES); //no cards were passed, make the deck yourself $suitsLeft = count($suits); while($suitsLeft > 0) { //default suit is the first one in the array $suit= $suits[0]; if($suitsLeft > 1) { //pick a suit at random $suitIndex = mt_rand(0, $suitsLeft - 1); $suit = $suits[$suitIndex]; //Unsetting values will not reassign the indexes... causing problems. //Hence copying over the last value to the value that needs to be deleted //and popping the last value. End result would be same for last value. $suits[$suitIndex] = $suits[$suitsLeft - 1]; } array_pop($suits); $suitsLeft = count($suits); for($i=1; $i<14; $i++) { $card = null; switch($i) { case 1: $card = new Card($suit, 'A', $i); break; case 11: $card = new Card($suit, 'J', 10); break; case 12: $card = new Card($suit, 'Q', 10); break; case 13: $card = new Card($suit, 'K', 10); break; default: $card = new Card($suit, $i, $i); } array_push($this->cards, $card); } // end of inner for loop } // end of while loop for suits } public function Shuffle() { // http://blog.codinghorror.com/the-danger-of-naivete/ for ($i = count($this->cards) - 1; $i > 0; $i--) { $nextRandomPosition = mt_rand(0, $i); $cardSwapSpace = $this->cards[$i]; $this->cards[$i] = $this->cards[$nextRandomPosition]; $this->cards[$nextRandomPosition] = $cardSwapSpace; } } public function __construct(array $cards=null) { if($cards == null) { $this->GenerateDeck(); } } }