* [Galene] [PATCH] Add /roll command to roll dice in the chat
@ 2021-04-07 21:12 Toke Høiland-Jørgensen
0 siblings, 0 replies; only message in thread
From: Toke Høiland-Jørgensen @ 2021-04-07 21:12 UTC (permalink / raw)
To: Juliusz Chroboczek; +Cc: Toke Høiland-Jørgensen, galene
This adds a /roll command to the chat that will take a dice specifier (like
'1d20' or '2d10+5'), generate some random numbers corresponding to the roll
and print the result in the chat. This is useful for role playing sessions,
and other situations where a ready source of random numbers is needed.
Signed-off-by: Toke Høiland-Jørgensen <toke@toke.dk>
---
static/galene.js | 45 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/static/galene.js b/static/galene.js
index d79a56d2b20a..341ab3a39a7e 100644
--- a/static/galene.js
+++ b/static/galene.js
@@ -2279,6 +2279,51 @@ commands.msg = {
}
};
+commands.roll = {
+ parameters: 'dice',
+ description: 'roll dice and send results',
+ f: (c, r) => {
+ let p = parseCommand(r);
+ if(!p[0])
+ throw new Error('/roll requires dice');
+
+ let regxp = new RegExp(/^(\d*)d(\d+)([+-]\d+)?$/);
+ let m = regxp.exec(p[0]);
+ if (!m)
+ throw new Error(`invalid dice: ${p[0]} - format is XdY, e.g. "2d10" or "d100"`);
+ let reps = m[1] || 1;
+ let range = m[2];
+ let s = `rolls ${reps}d${range}`;
+
+ let sum = 0;
+ let mod = 0;
+
+ // If there's a space between the modifier and the dice, the modifier
+ // ends up in p[1] instead of in m[3]. Support either, but not both
+ if (m[3] && p[1]) {
+ throw new Error('only one modifier allowed')
+ } else if (m[3] || p[1]) {
+ mod = parseInt(m[3] || p[1]);
+ if (Number.isNaN(mod))
+ throw new Error(`invalid modifier: ${p[1]} - format is +X or -X`)
+ s = s + `${mod < 0 ? mod : '+' + mod}`;
+ }
+ s = s + ':';
+
+ for (let i = 0; i < reps; i++) {
+ let roll = Math.floor((Math.random() * range) + 1);
+ s = s + ` ${roll}`;
+ sum += roll;
+ }
+
+ sum += mod;
+ if (reps > 1 || mod)
+ s = s + ` = ${sum}`;
+
+ serverConnection.chat('me', '', s);
+ }
+};
+
/**
@param {string} c
@param {string} r
--
2.31.1
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2021-04-07 21:12 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-04-07 21:12 [Galene] [PATCH] Add /roll command to roll dice in the chat Toke Høiland-Jørgensen
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox