从数组

时间:2016-04-19 01:29:26

标签: php

我正在制作卡片游戏"其中卡从所有四个套房随机发送到最多4个玩家。我创建了两个独立的阵列,一个用于13个卡,一个用于4个套件。以下是我只有1名玩家​​的代码。

阵列:

<?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); ?> 给了我this,这个数字是4是有意义的。但是,如果我将其改为5,即需要处理多少张牌,我得到this,可能是因为那里有只有4间套房。

那么,我的代码有什么问题?

奖金:我还需要弄清楚如何制作所有独特的牌。我不能有两个黑桃王牌。如果有人也可以帮助我,我会感激不尽。

1 个答案:

答案 0 :(得分:0)

如果你想从一张随机卡片中获得一定数量的牌,最好只用一副牌中的每张牌创建一个阵列。

<?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);