扎金花 (三張牌) 比大小規則 (由大到小):
將每手牌編碼為整數分數,直接比較大小:
<?php
class ZhaJinHua {
private $suits = ['Spade','Heart','Diamond','Club'];
private $ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'];
private $rankVal = ['2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,'10'=>10,'J'=>11,'Q'=>12,'K'=>13,'A'=>14];
private $deck = [];
public function __construct() {
foreach ($this->suits as $s) {
foreach ($this->ranks as $r) $this->deck[] = [$s, $r];
}
}
public function draw() {
shuffle($this->deck);
return [array_pop($this->deck), array_pop($this->deck), array_pop($this->deck)];
}
public function compare($hand1, $hand2) {
$s1 = $this->score($hand1);
$s2 = $this->score($hand2);
return $s1 <=> $s2; // 1 贏, -1 輸, 0 平
}
private function score($hand) {
$suits = []; $ranks = [];
foreach ($hand as $c) { $suits[] = $c[0]; $ranks[] = $this->rankVal[$c[1]]; }
rsort($ranks); // 大到小
// 對子特殊排序:對子點數前置
if ($ranks[1] == $ranks[2]) { // 後兩張相同 (如 9,7,7)
$tmp = $ranks[0]; $ranks[0] = $ranks[2]; $ranks[2] = $tmp; // → 7,7,9
} elseif ($ranks[0] == $ranks[1]) { // 前兩張相同 (如 9,9,7) 已正確
} elseif ($ranks[0] == $ranks[2]) { // 首尾相同 (如 9,7,9) 理論上 rsort 後不會發生
$tmp = $ranks[1]; $ranks[1] = $ranks[2]; $ranks[2] = $tmp;
}
$base = sprintf('%02d%02d%02d', $ranks[0], $ranks[1], $ranks[2]); // 6 位數
$flush = ($suits[0]==$suits[1] && $suits[1]==$suits[2]);
$straight = ($ranks[0]==$ranks[1]+1 && $ranks[1]==$ranks[2]+1) || ($ranks[0]==14 && $ranks[1]==3 && $ranks[2]==2); // A-2-3
$triple = ($ranks[0]==$ranks[1] && $ranks[1]==$ranks[2]);
$pair = (!$triple && ($ranks[0]==$ranks[1] || $ranks[1]==$ranks[2]));
$weight = 0;
if ($triple) $weight = 60;
elseif ($flush && $straight) $weight = 50;
elseif ($flush) $weight = 30;
elseif ($straight) $weight = 20;
elseif ($pair) $weight = 10;
return (int)$base + $weight * 100000;
}
public function describe($hand) {
$types = ['單張','對子','順子','金花','順金','豹子'];
$s = $this->score($hand);
$typeIdx = (int)($s / 100000);
return $types[$typeIdx] . ' (分數:' . $s . ')';
}
}
// 測試
$game = new ZhaJinHua();
$h1 = $game->draw();
$h2 = $game->draw();
echo '手牌1: ' . json_encode($h1) . ' - ' . $game->describe($h1) . '<br>';
echo '手牌2: ' . json_encode($h2) . ' - ' . $game->describe($h2) . '<br>';
$r = $game->compare($h1, $h2);
echo $r==1 ? '手牌1 勝' : ($r==-1 ? '手牌2 勝' : '平手');
14,3,2。score() 回傳陣列 [$weight, $base, $suitRank]。