所以我为龙与地下城创建了一个基本的掷骰子 dicord 机器人。
我到目前为止的代码可以掷任何类型的骰子,(例如“roll xdy”“roll 1d20”,“roll 100d100”)
当有人发送匹配的消息时,它会输出结果掷骰。
我的问题是我想将这些数字加在一起并显示结果总数,但我不确定如何到达那里。
// Run dotenv
require('dotenv').config();
const { any } = require('async');
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('messageCreate', msg => {
z = msg.content;
matches = z.match(/\d+/g);
x = matches[0];
y = matches[1];
if (msg.content === 'ping') {
msg.reply('pong');
}
if (msg.content == 'roll ' + x + 'd' + y) {
function rollDie(sides) {
if (!sides) sides = 6;
return 1 + Math.floor(Math.random() * sides);
}
function rollDice(number, sides) {
var total = [];
var number = x;
var sides = y;
while (number-- > 0) total.push(rollDie(sides));
return total;
}
msg.reply("result: " + rollDice());
console.log(rollDice())
}
});
client.login(process.env.DISCORD_TOKEN);
最佳答案
好像你在声明变量时没有使用 let
或 var
(z
, matches
, x
和 y
)。没有理由再使用 var
了。您有 rollDice
函数的参数,但只是从您创建的变量中提取而不使用参数,所以我修改了它。我用了reduce对数组求和的方法。我更改了一些变量名称以使其更具描述性(例如 z
更改为 msgContent
)并在更多可用的地方使用它们。
在您的 rollDie
函数中,您给定的默认骰子边数为 6,但是由于 if
语句将其包装起来,调用该函数的唯一方法是 if边号是专门选择的。所以我修改了这个,这样如果有人只想掷 3 个 6 面骰子,他们可以输入“Roll 3”。在报告掷骰子时,我使用了 join方法,因此它们将显示在逗号和空格分隔的列表中,而不是显示为数组。
我在看到您的编辑后修改了此解决方案。 msgContent
现在在顶部创建,带有我制作的新正则表达式,它足够强大以摆脱toLowerCase 和 trim 方法输入清理以及代码中以前必需的其他字符串检查。 msg
将传递 regular expression test method如果 msg
是 'roll #' 或 'roll #d#'(其中 '#' 是任何数字长度的除 0 之外的任何数字)。正则表达式将自动忽略字符大小写和字符串末尾的任何空格。我将 rollDie
函数转换为更简洁的箭头函数,并将其放在 rollDice
函数范围内,因为这是唯一需要调用它的地方。你不需要写 if (!sides) sides = 6;
因为你可以只使用表达式 (sides || 6)
因为 sides
只使用一次,如果是 falsy该表达式的计算结果仅为 6。我也停止将 diceResults
声明为空数组,因为稍后可以在将 rollDice()
的输出保存到其中时定义它。
require('dotenv').config();
const { any } = require("async");
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on("messageCreate", (msg) => {
const msgContent = msg.content,
msgRegEx = /\s*roll\s[1-9]\d*(d[1-9]\d*)?\s*/i;
if (msgRegEx.test(msgContent)) {
let matches = msgContent.match(/\d+/g),
numDice = matches[0],
numSides = matches[1],
diceResults;
function rollDice(number, sides) {
const rollDie = sides => Math.floor(Math.random() * (sides || 6)) + 1;
let diceArray = [];
while (number-- > 0) diceArray.push(rollDie(sides));
return diceArray;
}
function calcDiceTotal(diceArray) {
return diceArray.reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
);
}
diceResults = rollDice(numDice, numSides);
msg.reply(
"ROLLING... " + diceResults.join(", ") +
" || TOTAL: " + calcDiceTotal(diceResults)
);
}
});
client.login(process.env.DISCORD_TOKEN);
输出应如下所示:"ROLLING... 3, 1, 6, 3, 5 || TOTAL: 18"
关于javascript - 掷骰子。 DND,将数组中的数字加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72496623/