Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Foxx\ComputerScience\U1;
- /**
- * A simple game of rock, paper, scissors.
- * @author Foxx Azalea Pinkerton
- * @since 2022-09-26
- * @teacher Mr.Wachs
- */
- class RockPaperScissors {
- const OPTIONS = ['R', 'P', 'S'];
- const WINNING_COMBINATIONS = [
- ['R', 'S'],
- ['P', 'R'],
- ['S', 'P']
- ];
- const KEY = [
- 'R' => 'Rock',
- 'P' => 'Paper',
- 'S' => 'Scissors'
- ];
- public function __construct() {
- // create a variable to store the user's choice
- $userChoice = readline("Rock (R), Paper (P), or Scissors (S): ");
- $userChoice = strtoupper($userChoice);
- // create a variable to store the computer's choice
- $computerChoice = $this->getComputerChoice();
- // create a variable to store the winner
- $winner = $this->getWinner($userChoice, $computerChoice);
- // display the winner
- echo "You chose " . self::KEY[$userChoice] . " and the computer chose " . self::KEY[$computerChoice] . ".\n";
- echo "The winner is $winner!\n";
- }
- /**
- * Gets the computer's choice.
- * @return string
- */
- private function getComputerChoice(): string {
- $randomNumber = rand(0, 2);
- $computerChoice = self::OPTIONS[$randomNumber];
- return $computerChoice;
- }
- /**
- * Gets the winner of the game.
- * @param string $userChoice
- * @param string $computerChoice
- * @return string
- */
- private function getWinner(string $userChoice, string $computerChoice): string {
- if ($userChoice == $computerChoice) {
- return "Tie";
- } else {
- $combination = [$userChoice, $computerChoice];
- if (in_array($combination, self::WINNING_COMBINATIONS)) {
- return "User";
- } else {
- return "Computer";
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement