【问题标题】:I'm having issues with making a scoreboard with discord.js我在使用 discord.js 制作记分牌时遇到问题
【发布时间】:2021-09-02 09:46:20
【问题描述】:

所以我正在尝试使用 discord.js 开发一个不和谐机器人,并且我想制作一个记分牌,但由于某种原因,当调用向记分牌添加点的命令时,我无法更改变量.有人可以帮忙吗?分数始终保持在 0。另外,我是编程的初学者,所以如果您能以简单易懂的方式解释,将不胜感激。谢谢!

client.on('message', msg => {
    
    var x = 0
    var y = 0
    if(msg.content.toLowerCase() === 'r!score x 1') {
        x = x + 1;
        msg.channel.send("Team y has won a point, now they're at " + x + "!")
    }else if(msg.content.toLowerCase() === 'r!score y 1') {
        y = y + 1;
        msg.channel.send("Team y has won a point, now they're at " + y + "!")
    } else if(msg.content.toLowerCase() === 'r!placar') {
        
        const scoreboard = new Discord.MessageEmbed() 
    .setColor("#0099ff")
    .setTitle("**Scoreboard**")
    .addFields(
        {name: "__Team X__", value: x + " points"},
        {name: "__Team Y__", value: y + " points"}
    );
        msg.channel.send(scoreboard)
        
    } 
    
})

【问题讨论】:

    标签: javascript discord.js


    【解决方案1】:

    您可能想使用消息收集器,但我将展示一种不同的方式。这可以适应您的代码以适应某种游戏。

    let x = 0, 
    y = 0;
    client.on("message", msg => {
      if(msg.content === 'r!score x 1') {
        msg.channel.send(`Team x has won a point, now they're at ${++x}!`)
      } else if(msg.content === 'r!score x 2') {
        msg.channel.send(`Team y has won a point, now they're at ${++y}!`)
      } else if(msg.content === 'r!placar') {
        const scoreboard = new Discord.MessageEmbed() 
        .setColor("#0099ff")
        .setTitle("**Scoreboard**")
        .addFields(
          {name: "__Team X__", value: x + " points"},
          {name: "__Team Y__", value: y + " points"}
        );
            msg.channel.send(scoreboard)
      }
    })
    

    为什么您的代码不起作用?

    您的代码只对两者都说 0,因为您在函数内声明了变量。每次回调,都会声明变量并将值设置为 0。然后检查消息内容是否为 r!placar,然后发送嵌入,其中 x0y 相同。我在回调之外声明了它,这样您就可以从回调中的任何位置访问它,并保留该值。

    【讨论】:

    • 非常感谢,现在可以使用了!很抱歉给您带来不便...
    • 没问题。如果有帮助,请将答案标记为正确!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多