PHP数组扑克结果


php array poker hand result

我在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张相同的卡片,或者4张相同的卡片?

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

(我不太擅长数组)

四种很简单。你循环遍历你的卡片数组,并将每种面孔的数量加起来:

$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
   }
}