Skip to content

Instantly share code, notes, and snippets.

@mgldev
Last active December 22, 2015 07:19
Show Gist options
  • Save mgldev/6437221 to your computer and use it in GitHub Desktop.
Save mgldev/6437221 to your computer and use it in GitHub Desktop.
A colleague set a task of creating a Rock, Paper, Scissors game for our junior developers to tackle, and I thought I'd give it a shot.
<?php
$pieces = ['r' => 'Rock', 'p' => 'Paper', 's' => 'Scissors'];
$stack = [[['p','r'],'p'],[['r','s'],'r'],[['s','p'],'s']];
$takes = 5;
function request_player_piece() {
global $pieces;
echo "\nChoose piece: ";
$playerPiece = strtolower(trim(fgets(STDIN)));
if (!in_array($playerPiece, array_keys($pieces))) {
echo "Invalid choice, please choose from " . implode(', ', array_keys($pieces)) . ".\n";
request_player_piece();
}
return $playerPiece;
};
$computerPlay = function() use($pieces) {
return array_keys($pieces)[rand(0, count($pieces) - 1)];
};
$playerIsWinner = function($playerPiece, $computerPiece) use ($stack) {
if ($playerPiece == $computerPiece) return false;
$played = [$playerPiece, $computerPiece];
foreach ($stack as $config) {
$combination = $config[0];
$winner = $config[1];
if (count(array_diff($played, $combination)) == 0) {
$won = $winner == $playerPiece;
$retval = [
'won' => $won,
'winningPiece' => $won ? $playerPiece : $computerPiece,
'losingPiece' => $won ? $computerPiece : $playerPiece
];
break;
}
}
return $retval;
};
while (true) {
$gameTotal = ['Player' => 0, 'Computer' => 0];
$taken = 0;
while ($taken < $takes) {
echo "\nTake " . ($taken + 1) . ' of ' . $takes . "\n";
echo 'Player has chosen ' . $pieces[($playerPiece = request_player_piece())] . "\n";
echo 'Computer has chosen ' . $pieces[($computerPiece = $computerPlay())] . "\n";
$result = $playerIsWinner($playerPiece, $computerPiece);
if ($result == false) {
echo "It's a draw!\n";
continue;
}
$winner = $result['won'] ? 'Player' : 'Computer';
$gameTotal[$winner]++;
echo sprintf('%s beats %s, %s wins', $pieces[$result['winningPiece']], $pieces[$result['losingPiece']], $winner);
$taken++;
}
if ($gameTotal['Player'] == $gameTotal['Computer']) {
echo 'Nobody wins, score is level';
} else if ($gameTotal['Player'] > $gameTotal['Computer']) {
echo sprintf("\n\nPlayer wins with a ratio of %s wins to %s\n", $gameTotal['Player'], $gameTotal['Computer']);
} else {
echo sprintf("\n\nComputer wins with a ratio of %s wins to %s\n", $gameTotal['Computer'], $gameTotal['Player']);
}
$gameTotal['Player'] = $gameTotal['Computer'] = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment