94 lines
1.9 KiB
PHP
94 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Game;
|
|
|
|
use App\Models\Card;
|
|
|
|
use Illuminate\Support\Collection;
|
|
use App\Game\Exceptions\NotEnoughCardsException;
|
|
|
|
class GameBoard
|
|
{
|
|
/**
|
|
* Collection of the cards on the board.
|
|
*/
|
|
protected Collection $cards;
|
|
|
|
/**
|
|
* State of the cards on the board.
|
|
*/
|
|
protected GameBoardState $state;
|
|
|
|
/**
|
|
* Create a new board.
|
|
*/
|
|
public function __construct(GameBoardState $state)
|
|
{
|
|
$this->state = $state;
|
|
$this->regenerate(new GameSettings);
|
|
}
|
|
|
|
/**
|
|
* Return the cards.
|
|
*/
|
|
public function getCards()
|
|
{
|
|
return $this->cards;
|
|
}
|
|
|
|
/**
|
|
* Return the state
|
|
*/
|
|
public function getState(): GameBoardState
|
|
{
|
|
return $this->state;
|
|
}
|
|
|
|
/**
|
|
* Get the size of the board.
|
|
*/
|
|
public function getSize(): int
|
|
{
|
|
return $this->state->getSize();
|
|
}
|
|
|
|
/**
|
|
* Clear the game board.
|
|
*/
|
|
public function clear(): void
|
|
{
|
|
$this->state->clear();
|
|
}
|
|
|
|
/**
|
|
* Check if the board is in an ended state.
|
|
* E.g: all cards is in a winning state.
|
|
*/
|
|
public function hasGameEnded(): bool
|
|
{
|
|
return $this->state->isFull(GameBoardState::STATE_WIN);
|
|
}
|
|
|
|
/**
|
|
* Regenerate the board with new cards.
|
|
*
|
|
* @throw NotEnoughCardsException
|
|
*/
|
|
public function regenerate(GameSettings $settings): self
|
|
{
|
|
$num_cards = $this->getSize();
|
|
$cards = Card::getBySettings($settings, $num_cards);
|
|
|
|
if (count($cards) < $num_cards) {
|
|
$message = sprintf("Impossible to generate cards: requested %d but only %d returned", $num_cards, count($cards));
|
|
throw new NotEnoughCardsException($message);
|
|
}
|
|
|
|
$this->cards = $cards;
|
|
|
|
// Reset the state if we set new cards.
|
|
$this->clear();
|
|
|
|
return $this;
|
|
}
|
|
}
|