- rand: documentation ( source)
<?php
//
// File Game.php
//
class Game
{
/** @var Player[] */
private $players;
private $rounds;
private $winner;
private $weapons = ["stone", "scissors", "paper"];
public function __construct(array $players)
{
$this->players = $players;
}
public function setRounds(int $rounds)
{
$this->rounds = $rounds;
}
public function getRounds(): int
{
return $this->rounds;
}
public function playRounds(int $rounds): void
{
$this->rounds = $rounds;
}
public function getWinner(): Player
{
return $this->winner;
}
public function setWinner(Player $winner): void
{
$this->winner = $winner;
}
public function play()
{
while ($this->getRounds() !== 0) {
$this->players[0]->setWeapon($this->weapons[rand(0, 2)]);
$this->players[1]->setWeapon($this->weapons[rand(0, 2)]);
if ($this->players[0]->getWeapon() === $this->players[1]->getWeapon()) {
continue;
}
$this->fight()->addScore();
$this->setRounds($this->getRounds() - 1);
}
if ($this->players[0]->getScore() > $this->players[1]->getScore()) {
$this->setWinner($this->players[0]);
} else {
$this->setWinner($this->players[1]);
}
}
public function fight(): Player
{
if ($this->players[0]->getWeapon() === $this->weapons[0]) {
if ($this->players[1]->getWeapon() === $this->weapons[1]) {
return $this->players[0];
}
if ($this->players[1]->getWeapon() === $this->weapons[2]) {
return $this->players[1];
}
}
if ($this->players[0]->getWeapon() === $this->weapons[1]) {
if ($this->players[1]->getWeapon() === $this->weapons[0]) {
return $this->players[1];
}
if ($this->players[1]->getWeapon() === $this->weapons[2]) {
return $this->players[0];
}
}
if ($this->players[0]->getWeapon() === $this->weapons[2]) {
if ($this->players[1]->getWeapon() === $this->weapons[0]) {
return $this->players[0];
}
}
return $this->players[1];
}
}
//
// File Player.php
//
class Player
{
private $name;
private $score = 0;
private $weapon;
public function __construct(string $name)
{
$this->name = $name;
}
public function getWeapon(): string
{
return $this->weapon;
}
public function setWeapon(string $weapon): void
{
$this->weapon = $weapon;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getScore(): int
{
return $this->score;
}
public function addScore(int $score = 1): void
{
$this->score += $score;
}
}
//
// File app.php
//
$pavel = new Player("Pavel");
$gosho = new Player("Gosho");
$game = new Game([$pavel, $gosho]);
$game->playRounds(3);
$game->play();
echo $game->getWinner()->getName();
$anotherGame = new Game([$pavel, $gosho]);
$pavel->setWeapon("paper");
$gosho->setWeapon("stone");
echo PHP_EOL . $anotherGame->fight()->getName();