<?php
$allowedweapons = ['Scissors', 'Paper', 'Rock', 'Lizard', 'Spock'];
$rules = [
'scissorspaper' => 'cuts',
'paperrock' => 'covers',
'rocklizard' => 'crushes',
'lizardspock' => 'poisons',
'spockscissors' => 'smashes',
'scissorslizard' => 'decapitates',
'lizardpaper' => 'eats',
'paperspock' => 'disproves',
'spockrock' => 'vaporizes',
'rockscissors' => 'crushes'
];
class Game {
protected $rules;
public function __construct($rules)
{
$this->rules = $rules;
}
public function run($weaponP1, $weaponP2)
{
if ($weaponP1 === $weaponP2) {
echo "It is a tie";
return;
}
$result = $this->checkVerbs($weaponP1, $weaponP2);
$winner = 'Player 1';
if (!$result) {
$result = $this->checkVerbs($weaponP2, $weaponP1);
$winner = 'Player 2';
}
echo "The winner is: $winner\n";
echo "Because of: " . $result;
}
/**
* @param $weaponP1
* @param $weaponP2
* @return bool|string
*/
protected function checkVerbs($weaponP1, $weaponP2)
{
$key = strtolower($weaponP1 . $weaponP2);
if (!array_key_exists($key, $this->rules)) {
return false;
}
return $weaponP1 . ' ' . $this->rules[$key] . ' ' . $weaponP2;
}
}
(new Game($rules))->run('Scissors', 'Paper');
- Output for 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- The winner is: Player 1
Because of: Scissors cuts Paper
preferences:
150.71 ms | 404 KiB | 211 Q