掷骰子。 DND,将数组中的数字加在一起

Dice roll. DND, add numbers from an array together

所以我为龙与地下城创建了一个基本的掷骰子 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);

应该这样做。

Reduce 将回调函数应用于给定数组的每个元素,因此您可以使用它来添加数组的所有值并报告它。

将数组 'totalArr' 传递给此函数应该会得到数组中所有数字的总和

Javascript

const rollTotal = function (totalArr) {
const startingRoll = 0;
const subTotal = totalArr.reduce(
(previousValue, currentValue) => 
 previousValue + currentValue,
startingRoll
);
return subTotal;
};

测试

console.log(rollTotal([1, 2, 3]));

输出=6

好像您在声明变量时没有使用 letvarzmatchesxy) .没有理由再使用 var 了。我使用 toLowerCase and trim methods, and wrapped all the logic in an if (msg) { .. } to scrub input a bit. You had parameters for the rollDice function but then were just pulling from the variables you created and not using the parameters, so I modified that. I used the reduce 方法对数组求和。我更改了一些变量名称以使其更具描述性(例如 z 更改为 msgContent)并在更多可用的地方使用它们。

在您的 rollDie 函数中,您给出的默认模具边数为 6,但由于 if 语句包装它,调用该函数的唯一方法是边数是专门选择的。所以我修改了这个,这样如果有人只想掷 3 个 6 面骰子,他们可以输入“Roll 3”。在报告骰子掷骰时,我使用了 join 方法,因此它们将以逗号和 space 分隔列表而不是数组显示。

const { any } = require("async");
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

client.on("messageCreate", (msg) => {
  if (msg) {
    let msgContent = msg.content.trim().toLowerCase(),
        matches = msgContent.match(/\d+/g),
        numDice = matches[0],
        numSides = matches[1],
        diceResults = [];

    if (msgContent === "ping") {
      msg.reply("pong");
    }

    if (
      msgContent === "roll " + numDice ||
      msgContent === "roll " + numDice + "d" + numSides
    ) {
      function rollDie(sides) {
        if (!sides) sides = 6;

        return 1 + Math.floor(Math.random() * sides);
      }

      function rollDice(number, sides) {
        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"

这是按预期工作的最终机器人程序代码,使用了上面的修复程序并对其进行了调整,因此当有人输入任何其他消息时机器人程序不会中断。

看起来效果不错!

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) => {

  if (msg.content.startsWith('roll ')) {
    let msgContent = msg.content.trim().toLowerCase(),
        matches = msgContent.match(/\d+/g),
        numDice = matches[0],
        numSides = matches[1],
        diceResults = [];

    if (
      msgContent === "roll " + numDice ||
      msgContent === "roll " + numDice + "d" + numSides
    ) {
      function rollDie(sides) {
        if (!sides) sides = 6;

        return 1 + Math.floor(Math.random() * sides);
      }

      function rollDice(number, sides) {
        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);