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

如何基于百分比整数实现Discord机器人挖矿系统的概率机制?

动态挖矿概率判定实现方案

不用为每个等级单独写if逻辑,核心思路是把数据库中的概率数据转换成权重区间,通过随机数匹配区间来判定结果,完全适配任意等级的概率配置,包括0%概率的矿石自动忽略。

具体步骤

  1. 结构化获取概率数据
    从数据库查询当前玩家等级对应的所有矿石概率,整理成包含矿石名称和对应概率的数组格式,示例:
// 从数据库查询得到的等级1概率数据
const oreChances = [
  { name: 'coal', chance: 80 },
  { name: 'copper', chance: 15 },
  { name: 'iron', chance: 5 },
  { name: 'gold', chance: 0 },
  { name: 'diamond', chance: 0 },
  { name: 'emerald', chance: 0 }
];
  1. 通用概率判定函数
    写一个通用函数,接收上述概率数组,自动完成判定:
function getMinedOre(oreChances) {
  // 过滤掉概率为0的矿石,减少无效计算
  const availableOres = oreChances.filter(ore => ore.chance > 0);
  
  // 极端情况处理(无可用矿石)
  if (availableOres.length === 0) return null;
  
  // 生成0-100之间的随机数
  const randomValue = Math.random() * 100;
  let cumulativeProbability = 0;
  
  // 遍历累加概率,匹配随机数所在区间
  for (const ore of availableOres) {
    cumulativeProbability += ore.chance;
    if (randomValue < cumulativeProbability) {
      return ore.name;
    }
  }
  
  // 兜底处理(概率总和不为100%时返回最后一个矿石)
  return availableOres[availableOres.length - 1].name;
}
  1. 调用示例
// 获取当前玩家等级对应的概率数组(假设从数据库查询得到)
const currentLevelOres = await db.query('SELECT ore_name, chance FROM mining_probabilities WHERE level = ?', [playerLevel]);
// 转换为函数需要的格式
const formattedOres = currentLevelOres.map(row => ({ name: row.ore_name, chance: row.chance }));
// 判定挖矿结果
const minedOre = getMinedOre(formattedOres);

方案优势

  • 完全动态适配:不管等级调整、概率修改还是新增矿石,只要数据库数据更新,代码无需改动
  • 自动忽略0%概率:概率为0的矿石会被自动过滤,不用手动维护判定分支
  • 易扩展:后续新增矿石类型或等级,只需在数据库添加对应记录即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:31:00