0

这让我很难过。基本上我正在尝试发牌。我得到了正确数量的卡片,但它复制了它随机生成的卡片。相反,如果用户输入 52,我需要有 52 张不同的卡。

我一直在尝试这样做,但无法弄清楚。我尝试使用 in_array 函数但无济于事

有人可以帮忙吗

<?php
$input = $_POST["txtNumberOfCards"];

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");

$randsuit = rand(0,3);
$randcard = rand(0,12);

for($x = 0; $x < $input; $x++){
echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
}

?>
4

3 回答 3

1

使用数组来跟踪已使用的卡片并采取相应措施。同样在您的代码中,您在 for 循环之外有 rand 函数,这意味着它只会生成一次随机数

$input = $_POST["txtNumberOfCards"];;

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");

$setCards = array();
for($x = 0; $x < $input; $x++){
    $randsuit = rand(0,3);
    $randcard = rand(0,12); 
    if( isset($setCards[$suit[$randsuit].$card[$randcard]]) ) {
        $x--;
        continue;
    }
    echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
    $setCards[$suit[$randsuit].$card[$randcard]] = true;
}

phpFiddle:注意 fiddle 会回显 html,因此可以查看而不是渲染它。

于 2013-10-05T20:29:46.573 回答
0

您需要$input使用该函数将其转换为 int 变量intval()

此外,每次循环随机分配变量标签以生成不同的卡片:

<?php
$input = intval($_POST["txtNumberOfCards"]);

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");


for($x = 0; $x < $input; $x++){
$randsuit = rand(0,3);
$randcard = rand(0,12);
echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
}

?>
于 2013-10-05T20:23:46.757 回答
0

你得到重复牌的原因是因为你没有检查牌组合是否已经被处理过。

最好的解决方案是建立一组卡片并使用它来检查是否已创建卡片组合。然后回显构建的数组。

<?php
//The user input
$input = $_POST["txtNumberOfCards"];

$suit = array( "Hearts" , "Diamonds" , "Clubs" , "Spades" );
$card = array( "Ace" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "Jack" , "Queen" , "King");
//$dealArray holds the cards as they are dealt and used to compare what cards have all ready been dealt
$dealArray= array( );
//$count the while loop counter variable
$count = 0;
//while the $count variable is less then the $input
while( $count < $input )
{
  //generate a card combination array
  $cardCombo = array( 'suit' => $suit[ rand( 0 , 3 ) ],//Generate Random suit
                      'card' => $card[ rand( 0 , 12 ) ] );//Generate Random card

  //if the $cardCombo array that was generated is not in the $dealArray
  if ( !in_array( $cardCombo , $dealArray ) )
  {
    //Add the $cardCombo array to the end of the $dealArray
    array_push( $dealArray , $cardCombo );
    //Output an HTML image for the $cardCombo array
    echo ( '<img src="Images/' . $cardCombo['card'] . 'of' . $cardCombo['suit'] . '.gif">' );
    $count++;//Add 1 to the counter
  }
}
?>
于 2013-10-05T20:32:45.663 回答