Last active
April 23, 2021 14:44
-
-
Save dsposito/6679592 to your computer and use it in GitHub Desktop.
A simple class for interacting with a deck of cards.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Contains methods for interacting with a deck of cards. | |
* | |
* @author Daniel Sposito <daniel.g.sposito@gmail.com> | |
*/ | |
class Deck | |
{ | |
/** | |
* Builds a deck of cards. | |
* | |
* @return array | |
*/ | |
public static function cards() | |
{ | |
$values = array('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'); | |
$suits = array('S', 'H', 'D', 'C'); | |
$cards = array(); | |
foreach ($suits as $suit) { | |
foreach ($values as $value) { | |
$cards[] = $value . $suit; | |
} | |
} | |
return $cards; | |
} | |
/** | |
* Shuffles an array of cards. | |
* | |
* @param array $cards The array of cards to shuffle. | |
* | |
* @return array | |
*/ | |
public static function shuffle(array $cards) | |
{ | |
$total_cards = count($cards); | |
foreach ($cards as $index => $card) { | |
// Pick a random second card. | |
$card2_index = mt_rand(1, $total_cards) - 1; | |
$card2 = $cards[$card2_index]; | |
// Swap the positions of the two cards. | |
$cards[$index] = $card2; | |
$cards[$card2_index] = $card; | |
} | |
return $cards; | |
} | |
} | |
$cards = Deck::cards(); | |
echo "Cards: " . implode(', ', $cards); | |
echo "<br /><br />Shuffled Cards: " . implode(', ', Deck::shuffle($cards)); |
I think it's because of the for foreach loop on a changing array.
This seems to work
for($index=0;$index<count($cards);$index++) { $card = $cards[$index]; ......... }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is an issue with the shuffle function duplicating the first card - might be best to replace that function with a less random shuffle function.