GitList
Repositories
Help
Report an Issue
blackjack
Code
Commits
Branches
Tags
Search
Tree:
d7b0224
Branches
Tags
master
blackjack
Objects
Shoe.php
initial commit
Dev Ghai
commited
d7b0224
at 2014-04-17 16:55:27
Shoe.php
Blame
History
Raw
<?php /** * User: dev * Date: 3/13/14 * Time: 9:27 AM */ namespace Blackjack\Objects; require_once 'Deck.php'; require_once 'Config/Config.php'; use Blackjack\Config\Config; class Shoe { private $cards = array(); private $numDecks; private $numCardsPicked = 0; private $config; public function __construct(Config $config) { $this->config = $config; $this->numDecks = mt_rand(1, $config->maxNumDecks); for($i = 0; $i < $this->numDecks; $i++) { $deck = new Deck(); $deck->Shuffle(); $this->cards = array_merge($this->cards, $deck->cards); } } public function PickCard() { if($this->NumCardsInShoe() == 0) throw new \InvalidArgumentException("No more cards in the shoe."); //Reshuffle if 10% cards have been picked. if($this->numCardsPicked >= count($this->cards) * $this->config->cardShuffleFraction) { $this->numCardsPicked = 0; $this->Shuffle(); } $lastShoeIndex = count($this->cards) - 1; $index = mt_rand(0, $lastShoeIndex); $card = $this->cards[$index]; //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. $this->cards[$index] = $this->cards[$lastShoeIndex]; array_pop($this->cards); $this->numCardsPicked++; return $card; } public function NumCardsInShoe() { return count($this->cards); } private 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; } } }