javascript - 我如何设置百分比机会
问题描述
我正在制作一个机器人,我想添加命运之轮。
bot.on('message', async message => {
if(message.content.startsWith('+wheel')) {
let userbal = db.fetch(`money_${message.author.id}`)
let type = message.content.split(" ").slice(1).join(" ");
let types = ["basic", "classic", "premium"];
if(!type) return message.reply('...');
if(!type === types.some(type => message.content.split(" ").slice(1).join(" ") === type)) return message.reply('...');
if(type === 'basic') {
let cost = 100
//
const wheel = require('./wheel.json');
const wheels = [wheel.s1, wheel.s2, wheel.s3, wheel.s4, wheel.s5, wheel.s6, wheel.s7, wheel.s8];
var slot = Math.floor(Math.random() * wheels.length);
//
if(userbal < cost) return message.reply('...');
db.subtract(`money_${message.author.id}`, cost);
message.channel.send('...');
if(wheels[slot] === wheel.s1) {
message.channel.send('...')
db.push(message.author.id, "...")
}
}}});
但在这里所有的选择都有平等的机会。我怎样才能做到这一点,例如wheels.s1
有 70%、wheels.s2
30%、wheels.s3
45% 的机会等等?
解决方案
最简单的方法是重复数组的元素。就像如果你想加倍 s1 的机会,那么数组看起来像
const wheels = [wheel.s1, wheel.s1, wheel.s2, wheel.s3, wheel.s4, wheel.s5, wheel.s6, wheel.s7, wheel.s8];
其他方法是使用加权数组。您可以为每个元素指定 [0, 1] 之间的范围。例如,
weight= [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
在这里,我们有 3 倍的机会获得 s1。
推荐阅读
- unity3d - 用户可以在 Agora Unity SDK 中同时加入多个视频频道吗?
- ios - Xamarin iOS Shell FlyoutMenu 无法正确呈现
- javascript - 获取当前年份以及从 1901 年到当前年份的年份列表
- reactjs - 我如何知道哪个 React 事件的参数具有哪个 TypeScript 类型?
- maven - 是否可以告诉dependabot根本不连接到中央maven
- kubernetes - 以特权模式运行的 Openshift 容器
- web-scraping - 使用 sed 或更好的方法从网页上刮掉 5 个字符?
- javascript - 如何在Angular 9上根据不同情况更改按钮的点击事件
- reactjs - 无法在 ReactJS 中更新对象中的元素
- azure-logic-apps - Azure Logic App IP Restrictions 通过 powershell 更新