0
votes

I'm trying to make a guessing game with my discord bot where when i type "!guessing game", it will react three emojis: 1️⃣,2️⃣,3️⃣. Then it randomly chooses one of those emojis and assigns it to the variable, "answer". And if i click the emoji that corresponds with the one that is set to the "answer" variable then it will say something like "Congratulations! you guessed the correct number!", if not, it would say "Aww! Better luck next time!" or something.

This is what my code is:

    if (msg.content === "!guessing game") {
        const filter = (reaction, user) => {
            return ['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === msg.author.id;
        };
        msg.react('1️⃣');
        msg.react('2️⃣');
        msg.react('3️⃣');
        msg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
        .then(collected => {
        const reaction = collected.first();
        var num = Math.floor(Math.random() * 3) + 1;
        if (num === "1"){
            var answer = "1️⃣"
        }
        else{
            if (num === "2"){
                var answer = "2️⃣"
            }
            else{
                if (num === "3"){
                    var answer = "3️⃣"
                }
                else{
                   console.log("Random num failed")
          
                }
            }
        }
        if (reaction.emoji.name === answer) {
            msg.reply('You did it!');
        } 
        else{
            msg.reply('Better luck next time!');
        }
        


    })

naturally, this is what my console said: "Random num failed" i have a feeling that it would be a lot more efficient to choose a random emoji rather a random number and then converting it to an emoji.

does anyone know how to fix this?

(I would also appreciate it very much if you could make it case insensitive because i cant seem to figure that out.)

2

2 Answers

1
votes

You should use == instead of === in your if (num === "1") statements or remove double quotes around the number - if (num === 1). That's because === operator is more strict - it stands for comparing value and type of the value. Math.random() function returns value of number type, so you are comparing number to string:

console.log(3 == "3"); // will return true
console.log(3 === "3"); // will return false

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

0
votes

You could also have made your code a lot shorter using :

const numbers = ['1️⃣','2️⃣','3️⃣'];
let randNum = numbers[Math.floor(Math.random() * numbers.length)];
// Output : '1️⃣' or '2️⃣' or '3️⃣' :)