今天同事發來了一個炸金花的PHP程序,這個代碼實現了兩個人通過各自的三張牌進行權重計算,得到分數進行比較得到誰的牌大,我覺得里面還有一些問題,代碼如下:
<?php /** 每張牌的分值為一個2位數,不足2位的補前導0,例如'A':14,‘10':10,'2‘:'02‘,'k‘:13,'7‘:07 將3張牌按點數大小排序(從大到小),湊成一個6位數。例如'A27':140702,‘829':090802,‘JK8':131108,‘2A10':141002 例外,對於對子要將對子的位數放在前兩位(后面會看到為什么這么做)。例如‘779':070709,‘7A7':070714,‘A33':030314 現在的分值是一個6位數,將對子設為一個原始值加上10*100000的值,現在為一個7位數。例如‘779':1070709,‘7A7':1070714,‘A33':030314 對於順子,將結果加上20*100000.。例如‘345':2050403,‘QKA':2141312,‘23A':2140302 對於金花,將結果加上30*100000。例如‘Spade K,Spade 6,Spade J':3131106 因為順金的時候其實是金花和順子的和,所以順金應該是50*10000。 例如‘Spade 7,Spade 6,Spade 8':5080706 對於筒子,將結果加上60*100000。例如'666‘:6060606,'JJJ‘:6111111 */ class PlayCards{ public $suits = ['Spade','Heart','Diamond','Club'];// spades 黑桃 hearts 紅桃 clubs 草花/梅花 diamonds 方片 public $figures = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']; public $cards = []; public function __construct(){ $cards = []; foreach($this->suits as $suit){ foreach($this->figures as $figure){ $cards[] = [$suit,$figure]; } } $this->cards = $cards; //初始化一副撲克 } public function getCard(){ shuffle($this->cards); //洗牌 return [ array_pop($this->cards), array_pop($this->cards), array_pop($this->cards), ];//取出三張牌 } /** * @param $card1 * @param $card2 * 比較兩個人的牌 */ public function compareCards($card1,$card2){ $score1 = $this->ownScore($card1); $score2 = $this->ownScore($card2); if($score1>$score2){ return 1; }elseif($score1<$score2){ return -1; }else{ return 0; } } /** * @param $card * @return int|string * 處理牌型 */ public function ownScore($card){ $suit = [];$figure = []; foreach($card as $v){ $suit[] = $v[0]; $figure[] = array_search($v[1],$this->figures)+2;//從$this->figures中搜索出值為$v[1]的鍵,並將結果+2 } //補齊前導0 for($i = 0; $i < 3; $i++){ $figure[$i] = str_pad($figure[$i],2,'0',STR_PAD_LEFT); } rsort($figure); //將元素降序排序 //對於對子做特殊處理 if($figure[1] == $figure[2]){ $temp = $figure[0]; $figure[0] = $figure[2]; $figure[2] = $temp; } $score = $figure[0].$figure[1].$figure[2]; //豹子 60*100000 if($figure[0] == $figure[1] && $figure[0] == $figure[2]){ $score += 60*100000; } //金花 30*100000 if($suit[0] == $suit[1] && $suit[0] == $suit[2]){ $score += 30*100000; } //順子 20*100000 if($figure[0] == $figure[1]+1 && $figure[1] == $figure[2]+1 || implode($figure) =='140302'){ $score += 20*100000; } //對子 10*100000 if($figure[0] == $figure[1] && $figure[1] != $figure[2]){ $score += 10*100000; } return $score; } } $playCard = new PlayCards(); $card1 = $playCard->getCard(); $card2 = $playCard->getCard(); var_dump($card1); var_dump($card2); $result = $playCard->compareCards($card1,$card2); echo $result;
