From ad1d56d0927f22f924d788ad744eb09b3990ae76 Mon Sep 17 00:00:00 2001 From: Zankaria Date: Mon, 14 Oct 2024 12:23:38 +0200 Subject: [PATCH] dice.php: handle inline dice rolling markup --- inc/functions/dice.php | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/inc/functions/dice.php b/inc/functions/dice.php index f3208b33..558257bf 100644 --- a/inc/functions/dice.php +++ b/inc/functions/dice.php @@ -1,6 +1,11 @@ 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 relative to the root. Null if none. + * @return string The html to replace the original markup with. + */ +function inline_dice_roll_markup(array $matches, ?string $img_path): string { + global $config; + + $dice_count = _get_or_default_int($matches, 1, 1); + $dice_faces = _get_or_default_int($matches, 3, 6); + $dice_offset = _get_or_default_int($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; + } + + $tot = 0; + for ($i = 0; $i < $dice_count; $i++) { + $tot += mt_rand(1, $dice_faces); + } + // Ensure that final result is at least an integer. + $tot = abs((int)($dice_offset + $tot)); + + + if ($img_path !== null) { + $img_text = "dice"; + } else { + $img_text = ''; + } + + if ($dice_offset === 0) { + $dice_offset_text = ''; + } elseif ($dice_offset > 0) { + $dice_offset_text = "+{$dice_offset}"; + } else { + $dice_offset_text = (string)$dice_offset; + } + + return "$img_text {$dice_count}d{$dice_faces}{$dice_offset_text} = $tot"; +}