forked from leftypol/leftypol
functions.php: add new dice function
This commit is contained in:
parent
dcede2e175
commit
56ad753b76
1 changed files with 45 additions and 0 deletions
|
@ -2786,6 +2786,51 @@ function diceRoller($post) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls a dice and generates the appropiate html from the markup.
|
||||
* @param array $matches The array of the matches according to the default configuration.
|
||||
* 1 -> The number of dices to roll.
|
||||
* 3 -> The number faces of the dices.
|
||||
* 4 -> The offset to apply to the dice.
|
||||
* @param string $img_path Path to the image to use. Null if none.
|
||||
* @return string The html to replace the original markup with.
|
||||
*/
|
||||
function handle_dice_roll_markup(array $matches, ?string $img_path): string {
|
||||
function get_or_default(array $arr, int $index, int $default) {
|
||||
return (isset($arr[$index]) && is_numeric($arr[$index])) ? (int)$arr[$index] : $default;
|
||||
}
|
||||
global $config;
|
||||
|
||||
$dice_count = get_or_default($matches, 1, 1);
|
||||
$dice_faces = get_or_default($matches, 3, 6);
|
||||
$dice_offset = get_or_default($matches, 4, 0);
|
||||
|
||||
// Clamp between 1 and max_roll_count.
|
||||
$dice_count = max(min($dice_count, $config['max_roll_count']), 1);
|
||||
// Must be at least 2.
|
||||
if ($dice_faces < 2) {
|
||||
$dice_faces = 6;
|
||||
}
|
||||
|
||||
$acc = '';
|
||||
$text = "$dice_count d $dice_faces + $dice_offset";
|
||||
for ($i = 0; $i < $dice_count; $i++) {
|
||||
$res = $dice_offset + mt_rand(0, $dice_faces);
|
||||
if ($img_path === null) {
|
||||
$fmt = "<span>$text </span> <b>$res</b>";
|
||||
} else {
|
||||
$fmt = "<img src='$img_path' alt='$text' title='$text' class=\"inline-dice\"/> <b>$res</b>";
|
||||
}
|
||||
if (empty($acc)) {
|
||||
$acc = $fmt;
|
||||
} else {
|
||||
$acc .= " $fmt";
|
||||
}
|
||||
}
|
||||
|
||||
return $acc;
|
||||
}
|
||||
|
||||
function slugify($post) {
|
||||
global $config;
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue