You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord.js(JavaScript)中计算游戏胜率?

在Discord.js中实现游戏胜率计算

核心计算逻辑

胜率的计算公式为:

胜率 = (获胜数 / 总游戏数) × 100

需要注意两个关键点:

  • 先去除数字中的千位分隔符(逗号),再转换为数值类型进行计算
  • 结果保留两位小数,和你提供的参考案例格式一致

Discord.js 实现代码

可以封装一个通用计算函数,再结合Discord.js的交互系统返回结果(以v14版本为例):

// 封装胜率计算函数
function calculateWinRate(totalGames, wins) {
    // 去除数字中的逗号并转为整数
    const total = parseInt(totalGames.replace(/,/g, ''), 10);
    const winCount = parseInt(wins.replace(/,/g, ''), 10);
    
    // 处理总场数为0的边界情况
    if (total === 0) return '0.00%';
    
    // 计算胜率并保留两位小数
    const winRate = ((winCount / total) * 100).toFixed(2);
    return `${winRate}%`;
}

// 示例:以斜杠命令形式实现
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('winrate')
        .setDescription('计算游戏胜率')
        .addStringOption(option =>
            option.setName('total')
                .setDescription('总游戏数(可带逗号)')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('wins')
                .setDescription('获胜数(可带逗号)')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('losses')
                .setDescription('失败数(可带逗号)')
                .setRequired(true)),
    async execute(interaction) {
        const total = interaction.options.getString('total');
        const wins = interaction.options.getString('wins');
        const losses = interaction.options.getString('losses');
        
        const winRate = calculateWinRate(total, wins);
        
        // 格式化返回结果
        await interaction.reply(`
📊 游戏胜率统计
总场次:${total}
获胜:${wins}
失败:${losses}
胜率:${winRate}
        `);
    },
};

测试验证

用你提供的两组数据测试:

  • 场景1:总场数12,751,获胜6,957 → 计算得胜率约 54.56%
  • 参考案例:总场数1,275,获胜638 → 计算得胜率 50.04%,与示例结果完全匹配

内容的提问来源于stack exchange,提问作者vitor shw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:42:40