Помогите с циклом while
interface DeckInterface {
public function shuffle();
public function dealCard(): Card;
}
class Card {
private string $rank;
private string $suit;
public function __construct(string $rank, string $suit) {
$this->rank = $rank;
$this->suit = $suit;
}
public function getRank(): string {
return $this->rank;
}
public function getSuit():string {
return $this->suit;
}
}
class Deck implements DeckInterface {
private array $card;
private array $suits;
private array $elements;
public function __construct() {
$this->suits = ['♥', '♦', '♣', '♠' ];
$this->elements = ['6', '7', '8', '9', '10', 'В', 'Д', 'К', 'Т'];
foreach($this->elements as $rank) {
foreach($this->suits as $suit) {
// $this->card[] = $rank . $suit;
$this->card[] = new Card($rank, $suit);
}
}
$this->shuffle();
}
public function shuffle() {
shuffle($this->card);
}
public function dealCard(): Card {
return array_shift($this->card);
}
public function getCards() {
return $this->card;
}
}
interface PlayerInterface {
public function addCard($card);
public function countCardInHand(): int;
}
class Player implements PlayerInterface {
protected array $hand;
public function __construct() {
$this->hand = [];
}
public function addCard($card) {
$this->hand[] = $card;
}
public function countCardInHand(): int {
return count($this->hand);
}
}
class Game {
private Deck $deck;
private Player $firstPlayer;
private Player $secondPlayer;
public function __construct() {
$this->deck = new Deck();
$this->firstPlayer = new Player();
$this->secondPlayer = new Player();
}
public function play() {
// $this->dealCard() = $firstPlayer;
// $this->dealCard() = $secondPlayer;
while($this->deck-> getCards()) {
$this->hand[] = $card;
}
}
}
$game = new Game();
var_dump($game->play());
//var_dump($hand);
//$player = new Player();
//var_dump($player->addCard('1'));
//var_dump($player->countCardInHand());
//$deck = new Deck();
//var_dump($deck);
//var_dump($hand->getCards());
["firstPlayer":"Game":private]=>
object(Player)#39 (1) {
["hand":protected]=>
array(0) { -- тут берет карту
}
}
["secondPlayer":"Game":private]=>
object(Player)#40 (1) {
["hand":protected]=>
array(0) { -- тут берет карту
}
}
}
Хотел чтобы тут было видно какие карты я беру. Вообще это игра пьяница насколько я помню. Так вот если убрать из var_dump play() можно посмотреть что выводиться. Нужно исправить цикл while я новичок поэтому помогите.
Ответы (1 шт):
Так во первых в цикле while ты уже проверяешь остались ли карты в колоде, но если они закончились то циклу следует бы остановиться. Дальше в теле цикла бы чередовать выдачу карт каждому по очереди, короче ща покажу как я это всё вижу в коде
public function play() {
while (!empty($this->deck->getCards())) { // Проверяем, остались ли в колоде карты
$this->firstPlayer->addCard($this->deck->dealCard()); // Даем карту первому игроку
if (!empty($this->deck->getCards())) { // Проверяем, остались ли карты после предыдущей раздачи
$this->secondPlayer->addCard($this->deck->dealCard()); // Даем карту второму игроку
}
}
Обрати внимание, что я добавил проверку после того, как первый игрок получает карту. Это нужно для того, чтобы в случае, если карты закончатся после раздачи первому игроку, второй игрок не попытался взять карту из пустой колоды
По поводу вывода карт игроков после раздачи, надо бы сделать метод в классе Player. Допустим назовём его getHand()
public function getHand() {
return $this->hand;
}
Далее делаем метод в классе Game где используем наш метод из класса Player таким образом:
public function getFirstPlayerHand() {
return $this->firstPlayer->getHand();
}
public function getSecondPlayerHand() {
return $this->secondPlayer->getHand();
}
И получится у нас что-то вроде этого
$game->play(); // Сыграть в игру
// Вывести карты первого игрока
echo "Карты первого игрока:\n";
var_dump($game->getFirstPlayerHand());
// Вывести карты второго игрока
echo "Карты второго игрока:\n";
var_dump($game->getSecondPlayerHand());