php阵列扑克手牌结果

时间:2012-01-02 01:28:51

标签: php arrays

我在PHP中创建一个简单的扑克脚本,直到我分析5张牌的玩家手牌。

我将手存放在数组($ hand)中,如:

Array (
    [0] => Array (
        [face] => k
        [suit] => d
    )
    [1] => Array (
        [face] => 6
        [suit] => s
    )
    [2] => Array (
        [face] => 6
        [suit] => h
    )
    [3] => Array (
        [face] => 4
        [suit] => d
    )
    [4] => Array (
        [face] => 7
        [suit] => h
    )
)

我不确定如何开始寻找结果。例如,我如何知道玩家是否有四种类型,或4张同一张牌?

或者如果玩家获得了连续面孔的运行(3,4,5,6,7)?

(我不太擅长数组)

1 个答案:

答案 0 :(得分:2)

四种类型很简单。你遍历你的卡片阵列,并累计你拥有的每张脸的数量:

$have = array();

foreach($hand as $card) {
   $have[$card['face']]++;
}

这会给你

$have = array(
    'k' => 1,
    '6' => 2,
    '4' => 1,
    '7' => 1
);

然后搜索这个新数组以查看是否有任何值为4.如果你有一个4,那么你就得到了一个4类。在这种情况下,你有一个单一的两个单身和一堆单身。

对于连续跑步,你需要按照套装,然后按脸部对原始阵列进行排序,这样你就可以将所有的钻石放在一起,所有的心脏都在一起......等等。在每套服装中,所有的卡片都是按升序排列。然后是一个简单的“状态机”来检查你是否有5次运行。假设你的手部阵列已经排序,并且“面部”牌用数值表示('j' - > 10,' q'=> 11,'k'=> 12,'a'=> 13):

$last_suit = null;
$last_face = null;
$consecutive = 0;

foreach($hand as $card) {
   if ($last_suit != $card['suit']) { // got a new suit, reset the counters
      $consecutive = 0;
      $last_face = $card['face']; // remember the current card
      $last_suit = $card['suit']; // remember the new suit
      continue; // move on to next card
   }
   if (($card['face'] - $last_face) == 1)) {
      // the new card is 1 higher than the previous face, so it's consecutive
      $consecutive++;
      $last_face = $card['face']; // remember the new card
      continue; // move on to next card
   }
   if ($consecutive == 5) {
      break; // got a 5 card flush
   }
}