我正在做一个"纸牌游戏",在这个游戏中,从所有四套纸牌中随机向最多4名玩家发牌。我创建了两个独立的阵列,一个用于13张卡,另一个用于4个套件。下面是我为一个玩家准备的代码。
阵列:
<?php
$suite=array("Clubs", "Diamonds", "Hearts", "Spades");
$random_suite=array_rand($suite, 4);
?>
<?php
$card=array("Ace", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King");
$random_card=array_rand($card,5);
?>
如果声明(不要相信这里存在问题):
<?php if (!is_numeric($_GET['players']))
{
echo "You did not enter a value for Number of Players; click the 'Return'
button and enter a number.";
}
elseif ($_GET['players'] < 1)
{
echo "You entered a number less than 1 which is the minimum allowed; click
the 'Return' button to enter another number.";
}
elseif ($_GET['players'] > 4)
{
echo "You entered a number greater than 4 which is the maximum allowed; click
the 'Return' button to enter another number.";
}
else {
echo "<br>Dealing up Cards for 4 players
<br>Hand for Player Number 1:
组合阵列:
<br>{$card[$random_card[0]]} of {$suite[$random_suite[0]]}
<br>{$card[$random_card[1]]} of {$suite[$random_suite[1]]}
<br>{$card[$random_card[2]]} of {$suite[$random_suite[2]]}
<br>{$card[$random_card[3]]} of {$suite[$random_suite[3]]}
<br>{$card[$random_card[4]]} of {$suite[$random_suite[4]]}";
}
?>
使用<?php
$suite=array("Clubs", "Diamonds", "Hearts", "Spades");
$random_suite=array_rand($suite, 4);
?>
给我这个,这个数字是4,这是有道理的。然而,如果我把这个改为5,也就是需要发多少张牌,我就会得到这个,可能是因为只有4套。
那么,我的代码出了什么问题?
额外奖励:我还需要弄清楚如何使所有发牌都是独一无二的。我不能有两张黑桃王牌。如果有人也能帮我,我将不胜感激。
如果你想从一副随机的牌中获得给定数量的牌,最好用一副牌中的每一张牌创建一个数组。
<?php
$suits = array("Clubs", "Diamonds", "Hearts", "Spades");
$cards = array("Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King");
$deck = array();
foreach($suits as $suit) {
foreach($cards as $card) {
$deck[] = $card . ' of ' . $suit;
}
}
现在你可以洗牌阵列,并从中获得你需要的特定数量的卡
$num = 5;
shuffle($deck);
$cards = array_slice($deck, 0, $num);
下面是一个表意的例子:https://ideone.com/wQE677
或者你可以再次使用数组rand
$cards = array_rand($deck, 5);