【问题标题】:Discord.JS LeaderboardsDiscord.JS 排行榜
【发布时间】:2021-05-14 15:56:34
【问题描述】:

我目前有一些代码可以检测你在特定秒数内可以点击多少次反应。

我正在尝试为每个人创建一个排行榜,以保存具有最高 CPS(每秒点击次数)的前 10 名。否则代码可以完美运行,但我被困在排行榜上。

这是我的代码:

let CPStest = new Discord.MessageEmbed()
    .setColor("#8f82ff")
    .setTitle("CPS Test")
    .setDescription(`Alright, ${message.author.username}. Ready to begin your CPS test? All you have to do is spam click this reaction above ^ as fast as you can, you have 10 seconds before the timer runs out. Good Luck!`)
    .setFooter("Note: This may be inaccurate depending on Discord API and Rate Limits.")
    message.channel.send(CPStest)
    message.react('????️');

  // Create a reaction collector
  const filter = (reaction, user) => reaction.emoji.name === '????️' && user.id === message.author.id;

  var clicks = 1 * 3; // (total clicks)
  var timespan = 10; // (time in seconds to run the CPS test)

  const collector = message.createReactionCollector(filter, { time: timespan * 1000 });

  collector.on('collect', r => {
      console.log(`Collected a click on ${r.emoji.name}`);
      clicks++;
});

  collector.on('end', collected => {
    message.channel.send(`Collected ${clicks} raw clicks (adding reactions only)`);
  clicks *= 2;
      message.channel.send(`Collected ${clicks} total approximate clicks.`);

  var cps = clicks / timespan / 0.5; // Use Math.round if you want to round the decimal CPS
    message.channel.send(`Your CPS averaged ~${cps} clicks per second over ${timespan} seconds.`);
  
  let userNames = '';
  const user = (bot.users.fetch(message.author)).tag;
    
  userNames += `${user}\n`;
    
  let cpsLeaderboard = new Discord.MessageEmbed()
  .setColor("#8f82ff")
  .setTitle("Current CPS Record Holders:")
  .addFields({ name: 'Top 10', value: userNames, inline: true },
    { name: 'CPS', value: cps, inline: true })
  .setTimestamp()
  message.channel.send(cpsLeaderboard)
    
});

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    如果你想要一个排行榜,你要么需要将它保存到一个文件中,使用一个数据库,要么(如果你对它没问题,当你重新启动你的机器人时你会丢失它)你可以声明一个client.on('message') 之外的变量。它似乎足以用于测试目的。

    您可以创建一个topUsers 数组,每次游戏结束时将玩家推送到该数组,然后对其进行排序并创建排行榜。

    检查以下sn-p:

    const topUsers = [];
    
    client.on('message', (message) => {
      if (message.author.bot) return;
    
      let CPStest = new Discord.MessageEmbed()
        .setColor('#8f82ff')
        .setTitle('CPS Test')
        .setDescription(
          `Alright, ${message.author.username}. Ready to begin your CPS test? All you have to do is spam click this reaction above ^ as fast as you can, you have 10 seconds before the timer runs out. Good Luck!`,
        )
        .setFooter(
          'Note: This may be inaccurate depending on Discord API and Rate Limits.',
        );
      message.channel.send(CPStest);
      message.react('?️');
    
      // Create a reaction collector
      const filter = (reaction, user) =>
        reaction.emoji.name === '?️' && user.id === message.author.id;
    
      let clicks = 1 * 3; // (total clicks)
      const timespan = 10; // (time in seconds to run the CPS test)
    
      const collector = message.createReactionCollector(filter, {
        time: timespan * 1000,
      });
    
      collector.on('collect', (r) => {
        console.log(`Collected a click on ${r.emoji.name}`);
        clicks++;
      });
    
      collector.on('end', (collected) => {
        message.channel.send(
          `Collected ${clicks} raw clicks (adding reactions only)`,
        );
        clicks *= 2;
        message.channel.send(`Collected ${clicks} total approximate clicks.`);
    
        const cps = clicks / timespan / 0.5;
        message.channel.send(
          `Your CPS averaged ~${cps} clicks per second over ${timespan} seconds.`,
        );
    
        topUsers.push({ tag: message.author, cps });
    
        let cpses = '';
        let usernames = '';
    
        topUsers
          // sort the array by CPS in descending order
          .sort((a, b) => b.cps - a.cps)
          // only show the first ten users
          .slice(0, 10)
          .forEach((user) => {
            cpses += `${user.cps}\n`;
            usernames += `${user.tag}\n`;
          });
    
        const cpsLeaderboard = new Discord.MessageEmbed()
          .setColor('#8f82ff')
          .setTitle('Current CPS Record Holders:')
          .addFields(
            { name: 'Top 10', value: usernames, inline: true },
            { name: 'CPS', value: cpses, inline: true },
          )
          .setTimestamp();
        message.channel.send(cpsLeaderboard);
      });
    });
    

    【讨论】: