Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Foxx\ComputerScience\U1;
- /**
- * A simple BlackJack(21) game.
- * @author Foxx Azalea Pinkerton
- * @since 2022-09-26
- * @teacher Mr.Wachs
- */
- class BlackJack {
- const CARDS = [
- 'A' => 11,
- '2' => 2,
- '3' => 3,
- '4' => 4,
- '5' => 5,
- '6' => 6,
- '7' => 7,
- '8' => 8,
- '9' => 9,
- '10' => 10,
- 'J' => 10,
- 'Q' => 10,
- 'K' => 10
- ];
- private $playerHand = [];
- private $dealerHand = [];
- public function __construct() {
- $this->playerHand[] = $this->getCard();
- $this->playerHand[] = $this->getCard();
- $this->dealerHand[] = $this->getCard();
- $this->dealerHand[] = $this->getCard();
- $this->play();
- }
- /**
- * Gets a random card.
- * @return string
- */
- private function getCard(): string {
- $randomNumber = rand(0, count(self::CARDS) - 1);
- $card = array_keys(self::CARDS)[$randomNumber];
- return $card;
- }
- /**
- * Gets the value of a hand.
- * @param array $hand
- * @return int
- */
- private function getHandValue(array $hand): int {
- $value = 0;
- foreach ($hand as $card) {
- $value += self::CARDS[$card];
- }
- return $value;
- }
- /**
- * Plays the game.
- */
- private function play() {
- while (true) {
- $playerValue = $this->getHandValue($this->playerHand);
- $dealerValue = $this->getHandValue($this->dealerHand);
- echo "Your hand: ";
- foreach ($this->playerHand as $card) {
- echo "$card ";
- }
- echo "($playerValue)\n";
- echo "Dealer's hand: ";
- foreach ($this->dealerHand as $card) {
- echo "$card ";
- }
- echo "($dealerValue)\n";
- if ($playerValue > 21) {
- echo "You busted! You have $playerValue points.\n";
- break;
- }
- if ($dealerValue > 21) {
- echo "You win! The dealer busted with $dealerValue points.\n";
- break;
- }
- $choice = readline("Hit (H) or Stand (S)? ");
- $choice = strtoupper($choice);
- if ($choice == 'H') {
- $this->playerHand[] = $this->getCard();
- } else {
- while ($dealerValue < 17) {
- $this->dealerHand[] = $this->getCard();
- $dealerValue = $this->getHandValue($this->dealerHand);
- }
- if ($dealerValue > 21) {
- echo "The dealer busts! You win!\n";
- break;
- }
- if ($playerValue > $dealerValue) {
- echo "You Have $playerValue and the dealer has $dealerValue. You win!\n";
- break;
- } else {
- echo "You Have $playerValue and the dealer has $dealerValue. You lose!\n";
- break;
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment