我有一个班级,我稍后会分成几个班级来创建一个BlackJack纸牌游戏。我已经创建了甲板并正确计算了。在我的方法"交易"中我的播放器数组的输出有问题。输出只显示一个播放器,但我的输出数组应该返回两个。我的牌组中缺少的牌数也表明我缺少4张牌,这是有道理的,因为我有2名玩家被发给2张牌。有人可以帮我退回两个玩家并展示他们各自的卡片。
<?php
/* creating a deck of cards class to be used in a blackJack game*/
class Deck{
public $cards = array();
public $player = [];
//creates an instance of a deck of cards (works)
public function __construct(){
$values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
$suits =array('Diamond','Club','Heart','Spade');
foreach ($suits as $suit) {
foreach($values as $value){
$this->cards[] = "$value of $suit's";
//$deck = $this->cards;
}
}
}
/*add more decks to increase number of total cards
in my array (works)*/
public function numberOfDecks($number){
$cards = $this->cards;
$this->number = $number;
for($i = 0 ; $i < $number-1; $i++){
$this->cards = array_merge($this->cards, $cards);
}
return $cards;
}
/*adding elements to a player as expected need to return multiple players and their cards multiple players (does not currently work)*/
public function deal($numberOfPlayers){
$this->numberOfPlayers = $numberOfPlayers;
$player = $this->player;
$number = 2;
for($i = 0; $i < $number; $i++){
for($j = 0; $j < $numberOfPlayers; $j++){
$this->player[$j] = $this->cards[0];
array_shift($this->cards);
}
}
for($k = 0; $k < $numberOfPlayers; $k++)
return $player[$k];
}
}
$deck = new Deck();//works as expected
$deck->numberOfDecks(3);//works as expec
$shuffled = shuffle($deck->cards);//works as expected
$deck->deal(2);
var_dump($deck);
答案 0 :(得分:1)
问题出现在这个块中:
for($i = 0; $i < $number; $i++){
for($j = 0; $j < $numberOfPlayers; $j++){
$this->player[$j] = $this->cards[0]; // <--- fix me!
array_shift($this->cards);
}
}
当外圈再次出现时,它会直接覆盖发出的牌。尝试这样的事情:
for($i = 0; $i < $number; $i++){
for($j = 0; $j < $numberOfPlayers; $j++){
$this->player[$j][] = $this->cards[0]; // <- push into an array
array_shift($this->cards);
}
}
这个人正在为每个玩家创建并将卡片推入阵列,而不是只有一张(反复覆盖)卡片。