Advertisement
Foxxything

Untitled

Sep 26th, 2022
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.86 KB | None | 0 0
  1. <?php
  2.   namespace Foxx\ComputerScience\U1;
  3.  
  4.   /**
  5.    * A simple game of rock, paper, scissors.
  6.    * @author Foxx Azalea Pinkerton
  7.    * @since 2022-09-26
  8.    * @teacher Mr.Wachs
  9.    */
  10.   class RockPaperScissors {
  11.     const OPTIONS = ['R', 'P', 'S'];
  12.     const WINNING_COMBINATIONS = [
  13.       ['R', 'S'],
  14.       ['P', 'R'],
  15.       ['S', 'P']
  16.     ];
  17.     const KEY = [
  18.       'R' => 'Rock',
  19.       'P' => 'Paper',
  20.       'S' => 'Scissors'
  21.     ];
  22.  
  23.     public function __construct() {
  24.       // create a variable to store the user's choice
  25.       $userChoice = readline("Rock (R), Paper (P), or Scissors (S): ");
  26.       $userChoice = strtoupper($userChoice);
  27.  
  28.       // create a variable to store the computer's choice
  29.       $computerChoice = $this->getComputerChoice();
  30.  
  31.       // create a variable to store the winner
  32.       $winner = $this->getWinner($userChoice, $computerChoice);
  33.  
  34.       // display the winner
  35.       echo "You chose " . self::KEY[$userChoice] . " and the computer chose " . self::KEY[$computerChoice] . ".\n";
  36.       echo "The winner is $winner!\n";
  37.  
  38.  
  39.     }
  40.  
  41.     /**
  42.      * Gets the computer's choice.
  43.      * @return string
  44.      */
  45.     private function getComputerChoice(): string {
  46.       $randomNumber = rand(0, 2);
  47.       $computerChoice = self::OPTIONS[$randomNumber];
  48.       return $computerChoice;
  49.     }
  50.  
  51.     /**
  52.      * Gets the winner of the game.
  53.      * @param string $userChoice
  54.      * @param string $computerChoice
  55.      * @return string
  56.      */
  57.     private function getWinner(string $userChoice, string $computerChoice): string {
  58.       if ($userChoice == $computerChoice) {
  59.         return "Tie";
  60.       } else {
  61.         $combination = [$userChoice, $computerChoice];
  62.         if (in_array($combination, self::WINNING_COMBINATIONS)) {
  63.           return "User";
  64.         } else {
  65.           return "Computer";
  66.         }
  67.       }
  68.     }
  69.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement