[英]blackjack card game php
我需要在 PHP 中處理 BlackJack 紙牌游戲的一個例子......我找到了一些例子並嘗試基於它們構建我的代碼,雖然還沒有成功......此時我創建了一個類和兩個函數來建立一副 52 張牌,然后使用“洗牌”從中隨機選擇一張牌。 我仍在試驗中,但我無法回顯(或打印)這張隨機卡片。 您的建議將不勝感激! 這是我的代碼...
<?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);
?>
我不明白為什么$card
是你班級的成員randomCard()
,因為每次你調用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']
值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.