search
HomeBackend DevelopmentPHP TutorialPHP实现扎金花游戏之大小比赛的方法_php技巧

本文实例讲述了PHP实现扎金花游戏之大小比赛的方法。分享给大家供大家参考。具体分析如下:

程序离不开算法,前面讨论过寻路的算法。不过,当时的示例图中,可选的路径是唯一的。我们挑选一个算法,就是说要把这个唯一的路径选出来,怎么选呢?

还记得上初中的时候经常下午放学就躲在路边扎金花来赌*钱,貌似还上瘾了,现在过年的时候还经常一起扎金花赌*钱,但运气不啥好,每次都是输啊。

今天阳光明媚,由于清明节才出去玩了,所以今天没有去哪。闲着没事就想了下怎么用程序实现金花中两幅牌的大小比较,现在把它实现了,有些方法还是蛮重要的,因此就记下来。

好了,不废话了。

扎金花两副牌的比较规则就不说了,注明一下是顺子的时候 : JQK

思路:扎金花

1. 随机生成两幅牌,每副牌结构为

复制代码 代码如下:
array( 
    array('Spade','K'), 
    array('Club','6'), 
    array('Spade','J'), 
)

复制代码 代码如下:
array( 
    array('Spade','K'), 
    array('Club','6'), 
    array('Spade','J'), 
)

2. 计算每副牌的分值:每副牌有个原始大小(即排除对子,顺子,金花,顺金,筒子的大小),再

每张牌的分值为一个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':1030314

对于顺子,将结果加上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

3. 比较两幅牌的大小(用所计算的分值来比较)

就这么简单!!

代码如下(PHP)

复制代码 代码如下:
class PlayCards 

    public $suits = array('Spade', 'Heart', 'Diamond', 'Club'); 
    public $figures = array('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'); 
    public $cards = array(); 
    public function __construct() 
    { 
        $cards = array(); 
        foreach($this->suits as $suit){ 
            foreach($this->figures as $figure){ 
                $cards[] = array($suit,$figure); 
            } 
        } 
        $this->cards = $cards; 
    } 
    public function getCard() 
    { 
        shuffle($this->cards); 
        //生成3张牌 
        return array(array_pop($this->cards), array_pop($this->cards), array_pop($this->cards));    
    } 
    public function compareCards($card1,$card2) 
    { 
        $score1 = $this->ownScore($card1); 
        $score2 = $this->ownScore($card2); 
        if($score1 > $score2) return 1; 
        elseif($score1         return 0;        
    } 
    private function ownScore($card) 
    { 
        $suit = $figure = array(); 
        foreach($card as $v){ 
            $suit[] = $v[0]; 
            $figure[] = array_search($v[1],$this->figures)+2; 
        } 
        //补齐前导0 
        for($i = 0; $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; 
    } 

 
//test 
$playCard = new PlayCards(); 
$card1 = $playCard->getCard(); 
$card2 = $playCard->getCard(); 
$result = $playCard->compareCards($card1,$card2); 

echo 'card1 is ',printCard($card1),'
'; 
echo 'card2 is ',printCard($card2),'
'; 
$str = 'card1 equit card2'; 
if($result == 1) $str =  'card1 is larger than card2'; 
elseif($result == -1) $str = 'card1 is smaller than card2'; 
echo $str; 
function printCard($card) 

    $str = '('; 
    foreach($card as $v){ 
        $str .= $v[0].$v[1].','; 
    } 
    return trim($str,',').')'; 
}


复制代码 代码如下:
class PlayCards 

    public $suits = array('Spade', 'Heart', 'Diamond', 'Club'); 
    public $figures = array('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'); 
    public $cards = array(); 
    public function __construct() 
    { 
        $cards = array(); 
        foreach($this->suits as $suit){ 
            foreach($this->figures as $figure){ 
                $cards[] = array($suit,$figure); 
            } 
        } 
        $this->cards = $cards; 
    } 
    public function getCard() 
    { 
        shuffle($this->cards); 
        //生成3张牌 
        return array(array_pop($this->cards), array_pop($this->cards), array_pop($this->cards));    
    } 
    public function compareCards($card1,$card2) 
    { 
        $score1 = $this->ownScore($card1); 
        $score2 = $this->ownScore($card2); 
        if($score1 > $score2) return 1; 
        elseif($score1         return 0;        
    } 
    private function ownScore($card) 
    { 
        $suit = $figure = array(); 
        foreach($card as $v){ 
            $suit[] = $v[0]; 
            $figure[] = array_search($v[1],$this->figures)+2; 
        } 
        //补齐前导0 
        for($i = 0; $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; 
    } 

 
//test 
$playCard = new PlayCards(); 
$card1 = $playCard->getCard(); 
$card2 = $playCard->getCard(); 
$result = $playCard->compareCards($card1,$card2); 

echo 'card1 is ',printCard($card1),'
'; 
echo 'card2 is ',printCard($card2),'
'; 
$str = 'card1 equit card2'; 
if($result == 1) $str =  'card1 is larger than card2'; 
elseif($result == -1) $str = 'card1 is smaller than card2'; 
echo $str; 

function printCard($card) 

    $str = '('; 
    foreach($card as $v){ 
        $str .= $v[0].$v[1].','; 
    } 
    return trim($str,',').')'; 
}

希望本文所述对大家的php程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools