二十一点纸牌游戏php

时间:2015-09-03 13:23:25

标签: php blackjack

我需要在PHP中使用BlackJack纸牌游戏的一个例子...我已经找到了一些例子并尝试基于它们构建我的代码,虽然还不成功...此时我创建了一个类,两个功能,以建立一个52卡的牌组,然后'shuffle'从中选择一张随机卡。我还在试验,但我无法回复(或打印)这张随机卡片。非常感谢您的建议!这是我的代码......

<?php
/*This class contains a function that sets an array of
 * 4 suits, 13 faces and return a deck of 52 cards with var_dump
 */
Class Deck {
    public $suits = array ('Spades', 'Hearts', 'Clubs', 'Diamonds');
    public $faces = array("A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K");
    public $deck = array();
    public $card;
    public $value=0;


    public function __construct() { 

        //This function will build a simple 52 card deck for me
        foreach($this->suits as $suit) { 
            foreach($this->faces as $face) { 
                //I introduce a local variable $value to hold a score Number of a card

                $value = $face;

                if(!is_numeric($face))  {
                    $value = 10; 
                }

                if($face == 'A') {
                    $value = 11; 
                }

                $this->deck[] = array("suit" => $suit, "face" => $face, "value" => $value); 
            } 
        }// end of a loop in loop

        return $this->randomCard();
    }

    public function randomCard() { 
        shuffle($this->deck);
        $card = array_shift($this->deck);
        //var_dump $this->card;
        return $this->card['face'];
        echo ($this->card['face']);
    }

}//end of the class

$obj = new Deck;
var_dump ($obj->suits);
echo '<br>';
print_r ($obj->faces);
echo '<br>';
echo '<br>';
print_r ($obj->deck);
echo '<br>';
echo '<br>';
echo 'Test test';
print_r ($obj->card);
?>

1 个答案:

答案 0 :(得分:0)

我不明白为什么$card是您班级的成员var,因为每次调用randomCard()时它都会改变,而您只将其用作返回值。因此,请从班级中删除$card

试试这个:

public function randomCard(){
    if(count($this->deck)==0){
        reloadDeck() // you need a funtction which 'reloads' the deck because array_shift will remove the first element
    }

    shuffle($this->deck);
    return array_shift($this->deck);
}

返回孔卡阵列,因为您需要卡的所有信息而不仅仅是['face']

相关问题