I'm completely new to programming and have been struggling with this for at least a couple of hours. It simply deals 5 cards to a player. This is the code I have:
<?php
//setting up array开发者_JAVA技巧s
$cardLocation = array();
$suits = array("Hearts", "Diamonds", "Spades", "Clubs");
$ranks = array("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack","Queen", "King");
//filling the deck
for($rank=0; $rank<13; $rank++){
for($suit=0; $suit<4; $suit++){
$cardLocation[$rank][$suit] = "deck";
}
}
//dealing the cards to a player
for($i=0; $i<5; $i++){
$duplicate = true;
while($duplicate){
$suit = rand(1, 4);
$rank = rand(1, 13);
if($cardLocation[$rank][$suit] == "deck"){
$cardLocation[$rank][$suit] = "player";
$duplicate = false;
}
}
}
?>
I'm trying to figure out a way of storing each value of the for loop into an array and then printing it out. Have had a few ideas but all of them failed. Any help would be welcomed.
I'm not sure that a two dimensional array is a requirement, but if it is not you could consider something like this:
<?php
const NUMBER_OF_CARDS_TO_DRAW = 5;
$cardLocation = array();
$suits = array("Hearts", "Diamonds", "Spades", "Clubs");
$ranks = array("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack","Queen", "King");
//filling the deck
$deck = [];
foreach ($suits as $suit) {
foreach ($ranks as $rank) {
$deck[] = "$suit $rank";
}
}
// http://php.net/manual/en/function.shuffle.php
shuffle($deck);
$playerHand = [];
for ($i=0;$i<NUMBER_OF_CARDS_TO_DRAW;$i++) {
// http://php.net/manual/en/function.array-shift.php
$randomCard = array_shift($deck);
if (is_null($randomCard)) {
// this happens if you try to draw too many cards
break;
}
$playerHand[] = $randomCard;
}
print_r($playerHand);
精彩评论