schat2-clive/src/games/dice.js

51 lines
1.6 KiB
JavaScript
Executable File

'use strict';
const config = require('config');
const crypto = require('crypto');
const style = require('../utils/style');
const dieFaces = ['⚀', '⚁', '⚂', '⚃', '⚄', '⚅'];
const coinFaces = ['🗿', '🏛️'];
function onCommand(args, context) {
const type = ['coin', 'flip'].includes(context.command) ? 'coin' : 'dice';
const pattern = args[0]?.match(/(\d+)?d(\d+)?/i);
if (pattern) {
onCommand(pattern.slice(1), context);
return;
}
const rolls = Math.max(Number(args[0]) || 1, 1);
const faces = type === 'coin' ? 2 : Math.max(Number(args[1]) || 6, 1);
if (rolls > config.dice.maxRolls) {
context.sendMessage(`You can only roll ${config.dice.maxRolls} dice at one time`, context.room.id, { label: type });
return;
}
if (faces > config.dice.maxFaces) {
context.sendMessage(`Your dice can have at most ${config.dice.maxFaces} faces`, context.room.id, { label: type });
return;
}
const results = Array.from({ length: rolls }, () => {
const result = crypto.randomInt(1, faces + 1);
if (type === 'coin') {
return `${style.yellow(`(${coinFaces[result - 1]})`)} ${style.bold(result === 1 ? 'heads' : 'tails')}`; // eslint-disable-line no-irregular-whitespace
}
return `${style.grey(dieFaces[result - 1] || '☐')} ${style.bold(result)}`; // eslint-disable-line no-irregular-whitespace
});
context.sendMessage(results.join(style.grey(' | ')), context.room.id, { label: type });
}
module.exports = {
onCommand,
commands: ['dice', 'die', 'roll', 'coin', 'coins', 'flip'],
help: 'What\'s your next move? Try ~dice [rolls] [faces], ~die, ~roll, ~coin or ~flip',
};