Skip to content

Instantly share code, notes, and snippets.

@mgldev
Last active December 22, 2015 10:48
Show Gist options
  • Save mgldev/6461151 to your computer and use it in GitHub Desktop.
Save mgldev/6461151 to your computer and use it in GitHub Desktop.
Rock paper scissors OOP approach
<?php
class DrawException extends DomainException {}
abstract class Hand {
public function beats(Hand $hand) {
$this->rejectDraw($hand);
$this->assess($hand);
}
protected abstract function assess(Hand $hand);
public function __toString() {
return get_class($this);
}
public function rejectDraw(Hand $hand) {
if ($hand === $this) {
throw new DrawException('No player wins, round is a draw');
}
}
}
interface Wrappable {}
interface Cuttable {}
interface Bluntable {}
class Rock extends Hand implements Wrappable {
protected function assess(Hand $hand) {
return $hand instanceof Bluntable;
}
}
class Paper extends Hand implements Cuttable {
protected function assess(Hand $hand) {
return $hand instanceof Wrappable;
}
}
class Scissors extends Hand implements Bluntable {
protected function assess(Hand $hand) {
return $hand instanceof Cuttable;
}
}
$hands = ['r' => new Rock, 'p' => new Paper, 's' => new Scissors];
echo "Choose hand [r, p, s]: ";
$choices = [
'computer' => array_keys($hands)[rand(0, 2)],
'player' => strtolower(trim(fgets(STDIN)))
];
$computerHand = $hands[$choices['computer']];
$playerHand = $hands[$choices['player']];
echo "Player chose $playerHand\n";
echo "Computer chose $computerHand\n";
try {
if ($playerHand->beats($computerHand)) {
echo sprintf("Player wins, %s beats %s\n", $playerHand, $computerHand);
} else {
echo sprintf("Computer wins, %s beats %s\n", $computerHand, $playerHand);
}
} catch (DrawException $ex) {
echo $ex->getMessage() . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment