Created
December 12, 2021 04:20
-
-
Save susanBuck/adc9aced4e9411daf24bd5b996082a5e to your computer and use it in GitHub Desktop.
game method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function game() | |
{ | |
# Initialize variables | |
$goal = 25; | |
$playerSum = 0; | |
$playerTurns = []; # We'll use this array to store the player's points and sum for each turn | |
$opponentSum = 0; | |
$opponentTurns = []; # We'll use this array to store the opponent's points and sum for each turn | |
# Play the round until player or opponent reaches the goal | |
while ($playerSum <= $goal && $opponentSum <= $goal) { | |
# Player | |
$points = $this->getPoints(); # See the code for this function below | |
$playerSum += $points; # Accumulate points | |
$playerTurns[] = [$points, $playerSum]; # Build an array of turns, storing both the points and their sum | |
# Opponent | |
$points = $this->getPoints(); # See the code for this function below | |
$opponentSum += $points; # Accumulate points | |
$opponentTurns[] = [$points, $opponentSum]; # Build an array of turns, storing both the points and their sum | |
} | |
# Determine who won (who got to the goal) - player or opponent | |
$winner = ($playerSum >= $goal or $opponentSum >= $goal) ? 'player' : 'opponent'; | |
# Build a final array of results | |
# This results array contains our full details of a "round" of the game including each of | |
# the player/opponent turns (including their points/sum each round) | |
# as well as the final outcome (winner) | |
$results = [ | |
'playerTurns' => $playerTurns, | |
'opponentTurns' => $opponentTurns, | |
'winner' => $winner, | |
]; | |
# Test that results contains the data we expect | |
dump($results); | |
} | |
# This is a "helper" function used to give us back points for each turn | |
# By extracting this specific logic here, it helps simplify our while loop above | |
private function getPoints() | |
{ | |
# Create an array of special numbers | |
# where the keys is the number's value | |
# and the value is the number itself | |
$specialNumbers = [ | |
11 => 5, # Magic | |
6 => 4, # Bonus | |
0 => 9, # Curse | |
1 => 2, # Mystic | |
15 => 7 # Wild | |
]; | |
$randomNumber = random_int(1, 10); | |
# See if the random number is a "special" number by searching in the array | |
# If it's found, array_search will return the key of the special number, which correlates to its poitn value | |
$specialNumber = array_search($randomNumber, $specialNumbers); | |
# If the random number was a special number, return its value | |
# Otherwise, just return the randomNumber itself | |
return ($specialNumber) ? $specialNumber : $randomNumber; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment