首页 > 解决方案 > 我可以制作一个从列表中生成三个不重复短语的机器人吗?

问题描述

我一直在尝试自学 Discord 机器人,但我是菜鸟,所以请多多包涵。首先我想说的是,我确实通过这个网站找到了这个,但我想出的一切似乎只适用于数字,而不是文字......

我正在尝试让机器人从列表中给出三个响应,而没有任何重复的机会。我了解通过防止项目重复,生成的响应不再是“随机的”。这是我现在想出的解决方法:

client.on('message', message => {
        const list1 = [
           'example A', 'example B'
        ]
        const list2 = [
           'example C', 'example D'
        ]
        const list3 = [
           'example E', 'example F'
        ]
        if (message.content.startsWith(`${prefix}fmk`)) {
           message.channel.send(`**redacted, Marry, Kill:**\n\n${list1[Math.floor(Math.random() * list1.length)]}\n${list2[Math.floor(Math.random() * list2.length)]}\n${list3[Math.floor(Math.random() * list3.length)]}`);
        }
});

显然你可以看到这个问题。它阻止了类似的响应,example A, example A, example A,但也使得不可能获得类似的组合example A, example B, example C

有没有一种方法可以让我拥有一个从示例 A 到示例 F 的列表,并且仍然从中获得三个不重复的结果?

我希望这是有道理的。谢谢 :)

标签: javascriptbots

解决方案


You could use a Fisher-Yates Shuffle to move 3 values around randomly:

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {

        j = Math.floor(Math.random() * (i+1));

        // swap randomly chosen element with current element
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;

    }

    return array;
}

var ranStrings = shuffle(["Example A", "Example B", "Example C"]); //calling the func

Note: this function not only shuffles the array, but only allowed unique values to be output

EDIT: As mentioned above, this isn't really a Discord.js question, although it is related to a bot, it is more asking about Javascript, and it would be more suited there.


推荐阅读