Skip to content

Instantly share code, notes, and snippets.

@andrejb-dev
Last active September 13, 2024 11:05
Show Gist options
  • Save andrejb-dev/fe3ac8b0586e00cd9def9e95191e344b to your computer and use it in GitHub Desktop.
Save andrejb-dev/fe3ac8b0586e00cd9def9e95191e344b to your computer and use it in GitHub Desktop.
DiceRoll
<?php
/**
* Parses string definition of diceroll to random dice rolls
* @param String $diceRoll The string representation of requested roll, e.g. "@ROLL-3d6@"
*/
function generateDiceRoll($diceRoll) {
$designationChar = '@';
$command = "ROLL-";
$cleanedRoll = ltrim(trim($diceRoll, $designationChar),$command);
$splittedRoll = explode("d", $cleanedRoll);
return rollDice($splittedRoll[0], $splittedRoll[1]);
}
/**
* Function to simulate rolling dice.
*
* @param int $numDice The number of dice to roll (1-20).
* @param int $numFaces The number of dice faces on each die (2-100.
*
* @return String The string array containing the results of each dice roll.
*/
function rollDice($numDice, $numFaces) {
if (1 > $numDice || 20 < $numDice || 2 > $numFaces || 100 < $numFaces ) {
return "Error: Dice roll [dice: " . $numDice . ", faces: " . $numFaces . "] is out of range (dices 1-20, faces 2-100)";
}
$results = array();
// Roll each dice and store the result in the array.
for ($i = 0; $i < $numDice; $i++) {
$result = rand(1, $numFaces);
$results[] = $result;
}
return "[" . implode(", ", $results) . "]";
}
echo(generateDiceRoll("@ROLL-3d6@") . "\n");
echo(generateDiceRoll("@ROLL-10d100@") . "\n");
echo(generateDiceRoll("@ROLL-5d2@") . "\n");
echo(generateDiceRoll("@ROLL-1d1@") . "\n");
echo(generateDiceRoll("@ROLL-0d6@") . "\n");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment