我是编程新手,并且至少在几个小时内一直在努力解决这个问题。它简单地向玩家发放5张牌。这是我的代码:
<?php
//setting up arrays
$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;
}
}
}
?>
我正在试图找出一种方法,将for循环的每个值存储到一个数组中,然后将其打印出来。有一些想法,但所有的想法都失败了。任何帮助都会受到欢迎。
答案 0 :(得分:1)
我不确定是否需要二维数组,但如果不是,你可以考虑这样的事情:
<?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);