watkins1179 watkins1179 - 20 days ago 6
PHP Question

I am having problems with the output of my array

I have a class that I will later break up into multiple classes creating a BlackJack card game. I have the the decks created and accounted for correctly. I am having a problem with the output of my player array in my method "deal". The output only displays one player but my array of outputs should be returning two. The amount of cards that are missing from my deck also indicate that I am missing 4 cards, which makes sense since I have 2 players being dealt 2 cards. Can someone please help me return both players and display both of their respective cards.

<?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);


here is the output I am currently getting back
enter image description here

Answer

The problem is in this chunk here:

for($i = 0; $i < $number; $i++){
  for($j = 0; $j < $numberOfPlayers; $j++){
    $this->player[$j] = $this->cards[0]; // <--- fix me!
    array_shift($this->cards);
  }
}

When that outer loop goes around again, it just straight overwrites the cards issued. Try something like this:

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);
  }
}

This one's creating and pushing the cards into an array for each player, rather than there being just the one (repeatedly overwritten) card.

Comments