forked from oldschoolgg/oldschoolbot
/
LootTable.js
71 lines (56 loc) · 1.39 KB
/
LootTable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const { rand } = require('../../config/util');
module.exports = class LootTable {
constructor(limit) {
this.table = [];
this.length = 0;
this.totalWeight = 0;
this.limit = limit;
}
addMany(arrayOfItems) {
for (const item of arrayOfItems) {
this.add(...item);
}
return this;
}
add(item, weight, quantity) {
// eslint-disable-next-line eqeqeq
if (weight == null || weight <= 0) weight = 1;
// eslint-disable-next-line eqeqeq
if (quantity == null || quantity <= 0) quantity = 1;
this.length += 1;
this.totalWeight += weight;
this.table.push({
item,
weight,
quantity
});
return this;
}
roll() {
// If this loot table has no items, return null;
if (this.length === 0) return null;
// Random number between 1 and the total weighting
const randomWeight = rand(1, this.limit || this.totalWeight);
if (randomWeight > this.totalWeight) return null;
// The index of the item that will be used.
let result;
let weight = 0;
for (let i = 0; i < this.table.length; i++) {
const item = this.table[i];
weight += item.weight;
if (randomWeight <= weight) {
result = i;
break;
}
}
const chosenItem = this.table[result];
if (chosenItem.item === undefined) return null;
return {
item: chosenItem.item,
quantity:
typeof chosenItem.quantity === 'function'
? chosenItem.quantity()
: chosenItem.quantity
};
}
};