lootgen-mayank 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +313 -2
- package/examples/basic.js +7 -0
- package/examples/boss.js +16 -0
- package/examples/chest.js +13 -0
- package/examples/custom-config.js +14 -0
- package/index.js +11 -0
- package/lib/generator.js +206 -0
- package/lib/items.js +90 -0
- package/lib/loot-tables.js +66 -0
- package/lib/rarity.js +69 -0
- package/lib/utils.js +77 -0
- package/package.json +28 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mayank
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,314 @@
|
|
|
1
|
-
#
|
|
1
|
+
# LootGen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
LootGen is a small, dependency-free Node.js package for creating randomized RPG loot and rewards. Generate weapons, armor, potions, accessories, collectibles, chest contents, boss rewards, and custom-table drops. Configure rarity, levels, luck, enchantments, gold, and reproducible seeded randomness.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Five built-in item categories with useful stats, values, names, and descriptions.
|
|
8
|
+
- Common, Rare, Epic, and Legendary rarities with configurable weights.
|
|
9
|
+
- Optional elemental and magical enchantments.
|
|
10
|
+
- Item level scaling for stats and value.
|
|
11
|
+
- Configurable luck that improves higher-rarity odds and is capped at `1`.
|
|
12
|
+
- Gold, chest, and boss reward generation.
|
|
13
|
+
- Weighted custom loot tables with per-entry drop chances.
|
|
14
|
+
- Reproducible output with a numeric or string seed.
|
|
15
|
+
- CommonJS API and no runtime dependencies.
|
|
16
|
+
|
|
17
|
+
## Requirements and installation
|
|
18
|
+
|
|
19
|
+
LootGen requires Node.js 18 or newer.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install lootgen
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
const LootGenerator = require('lootgen');
|
|
29
|
+
|
|
30
|
+
const loot = new LootGenerator().generateLoot();
|
|
31
|
+
console.log(loot);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
A generated item has this shape:
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
{
|
|
38
|
+
name: 'Fire Iron Sword',
|
|
39
|
+
type: 'Weapon',
|
|
40
|
+
rarity: 'Rare',
|
|
41
|
+
level: 1,
|
|
42
|
+
value: 34,
|
|
43
|
+
stats: { damage: 12, speed: 0.9 },
|
|
44
|
+
enchantment: 'Fire',
|
|
45
|
+
description: 'A dependable blade with a well-balanced edge.'
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The name and numbers above illustrate the format; actual results are randomized.
|
|
50
|
+
`enchantment` is `null` when the item is not enchanted.
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
Pass an optional object to `new LootGenerator(options)`:
|
|
55
|
+
|
|
56
|
+
| Option | Default | Description |
|
|
57
|
+
| --- | --- | --- |
|
|
58
|
+
| `seed` | No seed | A finite number or string used for repeatable pseudo-random results. |
|
|
59
|
+
| `level` | `1` | Default item level, an integer from `1` to `1000`. |
|
|
60
|
+
| `luck` | `0` | Rarity luck modifier from `0` to `1`, inclusive. |
|
|
61
|
+
| `rarityWeights` | `{ Common: 60, Rare: 25, Epic: 10, Legendary: 5 }` | Non-negative rarity weights; at least one must be positive. |
|
|
62
|
+
| `enchantmentChance` | `0.15` | Chance from `0` to `1` for an eligible item to have an enchantment. |
|
|
63
|
+
| `gold` | `{ min: 5, max: 25 }` | Default gold range. Both ends are inclusive non-negative integers. |
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
const LootGenerator = require('lootgen');
|
|
67
|
+
|
|
68
|
+
const generator = new LootGenerator({
|
|
69
|
+
seed: 'dungeon-entrance',
|
|
70
|
+
level: 10,
|
|
71
|
+
luck: 0.2,
|
|
72
|
+
enchantmentChance: 0.3,
|
|
73
|
+
rarityWeights: { Common: 50, Rare: 30, Epic: 15, Legendary: 5 },
|
|
74
|
+
gold: { min: 10, max: 40 }
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Rarity weights are relative, not percentages that must add up to 100. For the
|
|
79
|
+
defaults, all weights total 100 and correspond to 60%, 25%, 10%, and 5%.
|
|
80
|
+
For custom weights, a rarity's chance is its weight divided by the sum of all
|
|
81
|
+
weights (before the luck modifier).
|
|
82
|
+
|
|
83
|
+
## Public API
|
|
84
|
+
|
|
85
|
+
### `new LootGenerator(options)`
|
|
86
|
+
|
|
87
|
+
Creates a generator. Each instance has its own random sequence, configuration,
|
|
88
|
+
and optional seed. Invalid configuration throws a `TypeError` or `RangeError`
|
|
89
|
+
with a message that identifies the problem.
|
|
90
|
+
|
|
91
|
+
### `generateLoot(options)`
|
|
92
|
+
|
|
93
|
+
Generates an item chosen from the five item categories. Optional fields:
|
|
94
|
+
|
|
95
|
+
- `type`: `Weapon`, `Armor`, `Potion`, `Accessory`, or `Miscellaneous`.
|
|
96
|
+
- `level`: item level for this call.
|
|
97
|
+
- `rarity`: exact rarity to generate.
|
|
98
|
+
- `minimumRarity`: rarity floor for the random rarity roll.
|
|
99
|
+
- `luck`, `rarityWeights`, `enchantmentChance`: per-call overrides.
|
|
100
|
+
- `table`: a custom table from `createLootTable`; a miss caused by `dropChance`
|
|
101
|
+
falls back to a normal generated item.
|
|
102
|
+
|
|
103
|
+
### `generateWeapon(options)`, `generateArmor(options)`, `generatePotion(options)`
|
|
104
|
+
|
|
105
|
+
Generate a specific item type. These accept the same rarity, level, luck, and
|
|
106
|
+
enchantment options as `generateLoot`, except `type` is selected for you.
|
|
107
|
+
|
|
108
|
+
Weapons include `damage` and `speed`; armor has `defense` and `durability`;
|
|
109
|
+
potions include `healing`; accessories receive one randomized bonus stat.
|
|
110
|
+
Miscellaneous items are collectibles. Enchantments are generated for weapons,
|
|
111
|
+
armor, potions, and accessories, but not collectibles. Stats and value scale
|
|
112
|
+
with level and rarity.
|
|
113
|
+
|
|
114
|
+
### `generateGold(options)`
|
|
115
|
+
|
|
116
|
+
Returns an integer amount. An optional `{ min, max }` overrides the configured
|
|
117
|
+
gold range for the call; bounds are inclusive.
|
|
118
|
+
|
|
119
|
+
### `generateMultiple(count, options)`
|
|
120
|
+
|
|
121
|
+
Returns an array with `count` generated items. `count` must be an integer from
|
|
122
|
+
`0` to `10000`; generation options match `generateLoot`.
|
|
123
|
+
|
|
124
|
+
### `generateChest(options)`
|
|
125
|
+
|
|
126
|
+
Returns `{ items, gold }`. Defaults to 2–5 items and no gold. Supported options:
|
|
127
|
+
|
|
128
|
+
- `minItems`, `maxItems`: inclusive item-count bounds (integers from `0` to `1000`).
|
|
129
|
+
- `guaranteedRarity`: minimum rarity for the first item, when any is generated.
|
|
130
|
+
- `table`: custom table to draw chest items from. Entries that miss their
|
|
131
|
+
`dropChance` are omitted, so the returned item count can be lower than the
|
|
132
|
+
selected count.
|
|
133
|
+
- `gold`: `true` to use the configured gold range, `{ min, max }` for a custom
|
|
134
|
+
range, or `false`/omitted for no gold.
|
|
135
|
+
- `goldRange`: an optional range used with `gold: true`.
|
|
136
|
+
- `level`, `luck`, `rarityWeights`, `enchantmentChance`, `minimumRarity`.
|
|
137
|
+
|
|
138
|
+
### `generateBossLoot(options)`
|
|
139
|
+
|
|
140
|
+
Returns `{ items, gold }`. Defaults to three items, at least Rare for the first
|
|
141
|
+
item, a boss-weighted rarity distribution (`20/40/25/15`), and 50 bonus gold.
|
|
142
|
+
Options:
|
|
143
|
+
|
|
144
|
+
- `itemCount`: integer from `1` to `1000`.
|
|
145
|
+
- `guaranteedRarity`: minimum rarity for the first reward; defaults to `Rare`.
|
|
146
|
+
- `table`: custom table from which rewards are drawn.
|
|
147
|
+
- `rarityWeights`: override the boss-specific default weights.
|
|
148
|
+
- `bonusGold`: non-negative integer added to a random gold amount.
|
|
149
|
+
- `goldRange`: optional `{ min, max }` for the random portion of gold.
|
|
150
|
+
- `level`, `luck`, `enchantmentChance`, `minimumRarity`.
|
|
151
|
+
|
|
152
|
+
A custom table item without a rarity receives the guaranteed rarity for the
|
|
153
|
+
first reward; a lower rarity is raised to that floor. A table drop miss falls
|
|
154
|
+
back to a generated item so the boss reward count stays complete.
|
|
155
|
+
|
|
156
|
+
### `createLootTable(items)`
|
|
157
|
+
|
|
158
|
+
Validates and returns a custom loot table. Each entry is either an item object
|
|
159
|
+
with optional `weight` and `dropChance` properties, or an object of this form:
|
|
160
|
+
|
|
161
|
+
```js
|
|
162
|
+
{
|
|
163
|
+
item: { name: 'Moonstone', type: 'Accessory', rarity: 'Epic', value: 120 },
|
|
164
|
+
weight: 2,
|
|
165
|
+
dropChance: 0.75
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`weight` defaults to `1` and must be a non-negative finite number.
|
|
170
|
+
`dropChance` defaults to `1` and must be between `0` and `1`. At least one
|
|
171
|
+
entry must have positive weight. The table is copied when
|
|
172
|
+
created, so later changes to the input item objects do not alter it.
|
|
173
|
+
|
|
174
|
+
### `generateFromTable(table)`
|
|
175
|
+
|
|
176
|
+
Selects one item according to its table weight, then checks that entry's
|
|
177
|
+
`dropChance`. Returns a copied item or `null` if it does not drop.
|
|
178
|
+
|
|
179
|
+
### `setLuck(value)`, `setLevel(value)`, `setRarityWeights(weights)`
|
|
180
|
+
|
|
181
|
+
Update the generator's defaults and return the generator to allow chaining.
|
|
182
|
+
`setLuck` accepts values from `0` to `1`; `setLevel` accepts integer levels
|
|
183
|
+
from `1` to `1000`; `setRarityWeights` uses the same validation as the
|
|
184
|
+
constructor.
|
|
185
|
+
|
|
186
|
+
### Exported constants
|
|
187
|
+
|
|
188
|
+
The package's default CommonJS export is the `LootGenerator` class. These
|
|
189
|
+
named properties are also available:
|
|
190
|
+
|
|
191
|
+
```js
|
|
192
|
+
const LootGenerator = require('lootgen');
|
|
193
|
+
const { RARITIES, DEFAULT_RARITY_WEIGHTS, ENCHANTMENTS } = LootGenerator;
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`LootGenerator.LootGenerator` is an alias for the class itself.
|
|
197
|
+
|
|
198
|
+
## Luck and rarity
|
|
199
|
+
|
|
200
|
+
Luck is bounded from `0` (no change) to `1` (maximum supported effect). Each
|
|
201
|
+
rarity's base weight is multiplied by `1 + luck * rarityIndex`, where Common
|
|
202
|
+
has index 0 and Legendary has index 3. The resulting weights are normalized
|
|
203
|
+
for the final selection. Luck tilts odds toward higher rarities without
|
|
204
|
+
guaranteeing a particular rarity. Set a `minimumRarity` or use a
|
|
205
|
+
`guaranteedRarity` option when a floor is needed.
|
|
206
|
+
|
|
207
|
+
## Seeded randomness
|
|
208
|
+
|
|
209
|
+
Using the same seed and the same sequence of calls/configuration produces the
|
|
210
|
+
same results. String and finite-number seeds are supported:
|
|
211
|
+
|
|
212
|
+
```js
|
|
213
|
+
const first = new LootGenerator({ seed: 'test-run', level: 4 });
|
|
214
|
+
const second = new LootGenerator({ seed: 'test-run', level: 4 });
|
|
215
|
+
|
|
216
|
+
console.log(first.generateLoot()); // Same result as the next line
|
|
217
|
+
console.log(second.generateLoot());
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Each generator advances its own random sequence. Calls that consume random
|
|
221
|
+
values (including gold and table rolls) affect subsequent results.
|
|
222
|
+
|
|
223
|
+
## Custom loot tables
|
|
224
|
+
|
|
225
|
+
Tables are useful for enemy-specific drops, chest contents, or boss rewards.
|
|
226
|
+
Weights decide which entry is selected; `dropChance` is checked after the
|
|
227
|
+
selection:
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
const generator = new LootGenerator({ seed: 'crypt-guard' });
|
|
231
|
+
const guardDrops = generator.createLootTable([
|
|
232
|
+
{
|
|
233
|
+
item: { name: 'Rusty Spear', type: 'Weapon', rarity: 'Common', value: 8 },
|
|
234
|
+
weight: 8
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
item: { name: 'Guard Insignia', type: 'Accessory', rarity: 'Rare', value: 45 },
|
|
238
|
+
weight: 2,
|
|
239
|
+
dropChance: 0.6
|
|
240
|
+
}
|
|
241
|
+
]);
|
|
242
|
+
|
|
243
|
+
const drop = generator.generateFromTable(guardDrops);
|
|
244
|
+
if (drop) console.log(`The guard dropped ${drop.name}.`);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Use the same table with a chest or boss:
|
|
248
|
+
|
|
249
|
+
```js
|
|
250
|
+
const chest = generator.generateChest({
|
|
251
|
+
table: guardDrops,
|
|
252
|
+
minItems: 2,
|
|
253
|
+
maxItems: 4,
|
|
254
|
+
guaranteedRarity: 'Rare',
|
|
255
|
+
gold: { min: 10, max: 35 }
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
const boss = generator.generateBossLoot({
|
|
259
|
+
table: guardDrops,
|
|
260
|
+
itemCount: 2,
|
|
261
|
+
guaranteedRarity: 'Epic',
|
|
262
|
+
bonusGold: 150
|
|
263
|
+
});
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## Level scaling and item stats
|
|
267
|
+
|
|
268
|
+
Set a default level in the constructor, use `setLevel`, or override `level`
|
|
269
|
+
per generation call. Levels must be integers from 1 to 1000. Stats and value
|
|
270
|
+
increase with level; higher rarity also increases stats and value. The
|
|
271
|
+
particular stat values are randomized within each item's ranges. Levels are
|
|
272
|
+
intended as a simple game-friendly scale, not a balance system for a specific
|
|
273
|
+
game.
|
|
274
|
+
|
|
275
|
+
## Error handling
|
|
276
|
+
|
|
277
|
+
Invalid options fail explicitly instead of silently generating a fallback:
|
|
278
|
+
expected object types use `TypeError`; out-of-range values and unsupported
|
|
279
|
+
rarities/types use `RangeError`. Examples include negative gold, invalid
|
|
280
|
+
weights, invalid levels, and a chest maximum below its minimum. Validate
|
|
281
|
+
user-supplied configuration at the point where it enters your application.
|
|
282
|
+
|
|
283
|
+
## Examples
|
|
284
|
+
|
|
285
|
+
Runnable scripts are provided in [`examples/`](./examples/):
|
|
286
|
+
|
|
287
|
+
- `basic.js` — create and print an item.
|
|
288
|
+
- `custom-config.js` — configure seed, level, luck, rarity, and enchantments.
|
|
289
|
+
- `chest.js` — create a chest with guaranteed rarity and gold.
|
|
290
|
+
- `boss.js` — define a custom boss table and reward.
|
|
291
|
+
|
|
292
|
+
After installing the package, run an example with Node.js, such as:
|
|
293
|
+
|
|
294
|
+
```sh
|
|
295
|
+
node examples/chest.js
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## Tests
|
|
299
|
+
|
|
300
|
+
LootGen uses Node.js built-in test tools and has no test dependencies:
|
|
301
|
+
|
|
302
|
+
```sh
|
|
303
|
+
npm test
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Contributing
|
|
307
|
+
|
|
308
|
+
Bug reports and improvements are welcome. Please keep changes focused, add
|
|
309
|
+
tests for behavior changes, and ensure `npm test` passes before submitting
|
|
310
|
+
your contribution.
|
|
311
|
+
|
|
312
|
+
## License
|
|
313
|
+
|
|
314
|
+
LootGen is released under the [MIT License](./LICENSE).
|
package/examples/boss.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const LootGenerator = require('..');
|
|
4
|
+
|
|
5
|
+
const generator = new LootGenerator({ level: 15, luck: 0.2 });
|
|
6
|
+
const bossTable = generator.createLootTable([
|
|
7
|
+
{ item: { name: 'Wyrm Scale', type: 'Armor', rarity: 'Epic', value: 250 }, weight: 3 },
|
|
8
|
+
{ item: { name: 'Crown of Embers', type: 'Accessory', rarity: 'Legendary', value: 900 }, weight: 1 }
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
console.log(generator.generateBossLoot({
|
|
12
|
+
table: bossTable,
|
|
13
|
+
itemCount: 2,
|
|
14
|
+
guaranteedRarity: 'Epic',
|
|
15
|
+
bonusGold: 250
|
|
16
|
+
}));
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const LootGenerator = require('..');
|
|
4
|
+
|
|
5
|
+
const generator = new LootGenerator({ level: 6 });
|
|
6
|
+
const chest = generator.generateChest({
|
|
7
|
+
minItems: 3,
|
|
8
|
+
maxItems: 5,
|
|
9
|
+
guaranteedRarity: 'Rare',
|
|
10
|
+
gold: { min: 20, max: 80 }
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
console.log('Chest loot:', chest);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const LootGenerator = require('..');
|
|
4
|
+
|
|
5
|
+
const generator = new LootGenerator({
|
|
6
|
+
seed: 'my-game-session',
|
|
7
|
+
level: 8,
|
|
8
|
+
luck: 0.25,
|
|
9
|
+
enchantmentChance: 0.3,
|
|
10
|
+
rarityWeights: { Common: 45, Rare: 35, Epic: 15, Legendary: 5 }
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
console.log(generator.generateWeapon());
|
|
14
|
+
console.log(generator.generatePotion({ level: 12, rarity: 'Epic' }));
|
package/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const LootGenerator = require('./lib/generator');
|
|
4
|
+
const { DEFAULT_RARITY_WEIGHTS, RARITIES } = require('./lib/rarity');
|
|
5
|
+
const { ENCHANTMENTS } = require('./lib/items');
|
|
6
|
+
|
|
7
|
+
module.exports = LootGenerator;
|
|
8
|
+
module.exports.LootGenerator = LootGenerator;
|
|
9
|
+
module.exports.RARITIES = RARITIES;
|
|
10
|
+
module.exports.DEFAULT_RARITY_WEIGHTS = DEFAULT_RARITY_WEIGHTS;
|
|
11
|
+
module.exports.ENCHANTMENTS = ENCHANTMENTS;
|
package/lib/generator.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { assertObject, makeRandom, randomInt, validateChance, validateGoldRange, validateLevel } = require('./utils');
|
|
4
|
+
const { DEFAULT_RARITY_WEIGHTS, RARITIES, rollRarity, validateRarity, validateWeights } = require('./rarity');
|
|
5
|
+
const { createItem } = require('./items');
|
|
6
|
+
const { createLootTable, selectFromTable } = require('./loot-tables');
|
|
7
|
+
|
|
8
|
+
const ITEM_TYPES = Object.freeze(['Weapon', 'Armor', 'Potion', 'Accessory', 'Miscellaneous']);
|
|
9
|
+
|
|
10
|
+
function higherRarity(first, second) {
|
|
11
|
+
return RARITIES.indexOf(first) >= RARITIES.indexOf(second) ? first : second;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
class LootGenerator {
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
assertObject(options, 'options');
|
|
17
|
+
this.random = makeRandom(options.seed);
|
|
18
|
+
this.level = options.level === undefined ? 1 : validateLevel(options.level);
|
|
19
|
+
this.luck = this._validateLuck(options.luck === undefined ? 0 : options.luck);
|
|
20
|
+
this.rarityWeights = validateWeights(options.rarityWeights === undefined
|
|
21
|
+
? DEFAULT_RARITY_WEIGHTS
|
|
22
|
+
: options.rarityWeights);
|
|
23
|
+
this.enchantmentChance = options.enchantmentChance === undefined
|
|
24
|
+
? 0.15
|
|
25
|
+
: validateChance(options.enchantmentChance, 'enchantmentChance');
|
|
26
|
+
const gold = options.gold === undefined ? {} : options.gold;
|
|
27
|
+
assertObject(gold, 'gold');
|
|
28
|
+
this.goldMin = gold.min === undefined ? 5 : gold.min;
|
|
29
|
+
this.goldMax = gold.max === undefined ? 25 : gold.max;
|
|
30
|
+
validateGoldRange(this.goldMin, this.goldMax);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_validateLuck(value) {
|
|
34
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
35
|
+
throw new RangeError('luck must be a number between 0 and 1.');
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
_options(options = {}) {
|
|
41
|
+
assertObject(options, 'options');
|
|
42
|
+
return {
|
|
43
|
+
level: options.level === undefined ? this.level : validateLevel(options.level),
|
|
44
|
+
luck: options.luck === undefined ? this.luck : this._validateLuck(options.luck),
|
|
45
|
+
rarityWeights: options.rarityWeights === undefined ? this.rarityWeights : validateWeights(options.rarityWeights),
|
|
46
|
+
enchantmentChance: options.enchantmentChance === undefined
|
|
47
|
+
? this.enchantmentChance
|
|
48
|
+
: validateChance(options.enchantmentChance, 'enchantmentChance'),
|
|
49
|
+
minimumRarity: options.minimumRarity === undefined
|
|
50
|
+
? 'Common'
|
|
51
|
+
: validateRarity(options.minimumRarity, 'minimumRarity')
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
setLuck(value) {
|
|
56
|
+
this.luck = this._validateLuck(value);
|
|
57
|
+
return this;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
setLevel(value) {
|
|
61
|
+
this.level = validateLevel(value);
|
|
62
|
+
return this;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
setRarityWeights(weights) {
|
|
66
|
+
this.rarityWeights = validateWeights(weights);
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
generateLoot(options = {}) {
|
|
71
|
+
const config = this._options(options);
|
|
72
|
+
if (options.table !== undefined) {
|
|
73
|
+
return this._generateTableItem(options.table, config, config.minimumRarity, true);
|
|
74
|
+
}
|
|
75
|
+
const type = options.type === undefined ? ITEM_TYPES[randomInt(this.random, 0, ITEM_TYPES.length - 1)] : options.type;
|
|
76
|
+
if (!ITEM_TYPES.includes(type)) throw new RangeError(`type must be one of: ${ITEM_TYPES.join(', ')}.`);
|
|
77
|
+
const rarity = options.rarity === undefined
|
|
78
|
+
? rollRarity(this.random, config.rarityWeights, config.luck, config.minimumRarity)
|
|
79
|
+
: validateRarity(options.rarity);
|
|
80
|
+
if (RARITIES.indexOf(rarity) < RARITIES.indexOf(config.minimumRarity)) {
|
|
81
|
+
throw new RangeError('rarity cannot be lower than minimumRarity.');
|
|
82
|
+
}
|
|
83
|
+
return createItem(this.random, type, { ...config, rarity });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
_generateTableItem(table, config, minimumRarity, fallbackOnMiss = false) {
|
|
87
|
+
const item = selectFromTable(this.random, table);
|
|
88
|
+
if (item === null) {
|
|
89
|
+
return fallbackOnMiss
|
|
90
|
+
? this.generateLoot({ ...config, minimumRarity, table: undefined })
|
|
91
|
+
: null;
|
|
92
|
+
}
|
|
93
|
+
if (minimumRarity && (!item.rarity || RARITIES.indexOf(item.rarity) < RARITIES.indexOf(minimumRarity))) {
|
|
94
|
+
item.rarity = minimumRarity;
|
|
95
|
+
}
|
|
96
|
+
return item;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
generateWeapon(options = {}) {
|
|
100
|
+
return this.generateLoot({ ...options, type: 'Weapon' });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
generateArmor(options = {}) {
|
|
104
|
+
return this.generateLoot({ ...options, type: 'Armor' });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
generatePotion(options = {}) {
|
|
108
|
+
return this.generateLoot({ ...options, type: 'Potion' });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
generateGold(options = {}) {
|
|
112
|
+
assertObject(options, 'options');
|
|
113
|
+
const min = options.min === undefined ? this.goldMin : options.min;
|
|
114
|
+
const max = options.max === undefined ? this.goldMax : options.max;
|
|
115
|
+
validateGoldRange(min, max);
|
|
116
|
+
return randomInt(this.random, min, max);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
generateMultiple(count, options = {}) {
|
|
120
|
+
if (!Number.isInteger(count) || count < 0 || count > 10000) {
|
|
121
|
+
throw new RangeError('count must be an integer between 0 and 10000.');
|
|
122
|
+
}
|
|
123
|
+
const config = this._options(options);
|
|
124
|
+
return Array.from({ length: count }, () => this.generateLoot(config));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
createLootTable(items) {
|
|
128
|
+
return createLootTable(items);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
generateFromTable(table) {
|
|
132
|
+
return selectFromTable(this.random, table);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
generateChest(options = {}) {
|
|
136
|
+
assertObject(options, 'options');
|
|
137
|
+
const minItems = options.minItems === undefined ? 2 : options.minItems;
|
|
138
|
+
const maxItems = options.maxItems === undefined ? 5 : options.maxItems;
|
|
139
|
+
if (!Number.isInteger(minItems) || minItems < 0 || minItems > 1000) {
|
|
140
|
+
throw new RangeError('minItems must be an integer between 0 and 1000.');
|
|
141
|
+
}
|
|
142
|
+
if (!Number.isInteger(maxItems) || maxItems < minItems || maxItems > 1000) {
|
|
143
|
+
throw new RangeError('maxItems must be an integer between minItems and 1000.');
|
|
144
|
+
}
|
|
145
|
+
const config = this._options(options);
|
|
146
|
+
const count = randomInt(this.random, minItems, maxItems);
|
|
147
|
+
const guaranteedRarity = options.guaranteedRarity === undefined
|
|
148
|
+
? undefined
|
|
149
|
+
: validateRarity(options.guaranteedRarity, 'guaranteedRarity');
|
|
150
|
+
const items = Array.from({ length: count }, (_, index) => {
|
|
151
|
+
const minimumRarity = index === 0 && guaranteedRarity
|
|
152
|
+
? higherRarity(guaranteedRarity, config.minimumRarity)
|
|
153
|
+
: config.minimumRarity;
|
|
154
|
+
return options.table === undefined
|
|
155
|
+
? this.generateLoot({ ...config, minimumRarity })
|
|
156
|
+
: this._generateTableItem(options.table, config, minimumRarity);
|
|
157
|
+
}).filter(Boolean);
|
|
158
|
+
|
|
159
|
+
let gold = 0;
|
|
160
|
+
if (options.gold === true) {
|
|
161
|
+
gold = this.generateGold(options.goldRange === undefined ? {} : options.goldRange);
|
|
162
|
+
}
|
|
163
|
+
else if (options.gold && typeof options.gold === 'object') gold = this.generateGold(options.gold);
|
|
164
|
+
else if (options.gold !== undefined && options.gold !== false) {
|
|
165
|
+
throw new TypeError('gold must be false, true, or an object with min and max.');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return { items, gold };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
generateBossLoot(options = {}) {
|
|
172
|
+
assertObject(options, 'options');
|
|
173
|
+
const weights = options.rarityWeights === undefined
|
|
174
|
+
? { Common: 20, Rare: 40, Epic: 25, Legendary: 15 }
|
|
175
|
+
: validateWeights(options.rarityWeights);
|
|
176
|
+
const config = this._options({ ...options, rarityWeights: weights });
|
|
177
|
+
const guaranteedRarity = options.guaranteedRarity === undefined ? 'Rare' : validateRarity(options.guaranteedRarity, 'guaranteedRarity');
|
|
178
|
+
const itemCount = options.itemCount === undefined ? 3 : options.itemCount;
|
|
179
|
+
if (!Number.isInteger(itemCount) || itemCount < 1 || itemCount > 1000) {
|
|
180
|
+
throw new RangeError('itemCount must be an integer between 1 and 1000.');
|
|
181
|
+
}
|
|
182
|
+
const items = Array.from({ length: itemCount }, (_, index) => {
|
|
183
|
+
if (options.table !== undefined) {
|
|
184
|
+
const minimumRarity = index === 0
|
|
185
|
+
? higherRarity(guaranteedRarity, config.minimumRarity)
|
|
186
|
+
: config.minimumRarity;
|
|
187
|
+
return this._generateTableItem(options.table, config, minimumRarity, true);
|
|
188
|
+
}
|
|
189
|
+
return this.generateLoot({
|
|
190
|
+
...config,
|
|
191
|
+
minimumRarity: index === 0
|
|
192
|
+
? higherRarity(guaranteedRarity, config.minimumRarity)
|
|
193
|
+
: config.minimumRarity
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
const bonusGold = options.bonusGold === undefined ? 50 : options.bonusGold;
|
|
197
|
+
if (!Number.isSafeInteger(bonusGold) || bonusGold < 0) {
|
|
198
|
+
throw new RangeError('bonusGold must be a non-negative safe integer.');
|
|
199
|
+
}
|
|
200
|
+
const goldRange = options.goldRange === undefined ? {} : options.goldRange;
|
|
201
|
+
const gold = this.generateGold(goldRange) + bonusGold;
|
|
202
|
+
return { items, gold };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = LootGenerator;
|
package/lib/items.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { RARITY_MULTIPLIERS } = require('./rarity');
|
|
4
|
+
const { randomInt } = require('./utils');
|
|
5
|
+
|
|
6
|
+
const CATALOG = Object.freeze({
|
|
7
|
+
Weapon: [
|
|
8
|
+
['Iron Sword', 'A dependable blade with a well-balanced edge.'],
|
|
9
|
+
['Hunter Bow', 'A light bow made for careful, distant shots.'],
|
|
10
|
+
['Warhammer', 'A heavy hammer built to break stubborn defenses.'],
|
|
11
|
+
['Moonlit Dagger', 'A narrow dagger that catches the light strangely.']
|
|
12
|
+
],
|
|
13
|
+
Armor: [
|
|
14
|
+
['Travel-worn Cuirass', 'Layered protection suited to a long journey.'],
|
|
15
|
+
['Oakguard Shield', 'A sturdy shield reinforced with dark iron.'],
|
|
16
|
+
['Sentinel Helm', 'A close-fitting helm with a clear field of view.'],
|
|
17
|
+
['Scale Vest', 'Overlapping scales offer flexible protection.']
|
|
18
|
+
],
|
|
19
|
+
Potion: [
|
|
20
|
+
['Healing Draught', 'A restorative potion with a bright herbal scent.'],
|
|
21
|
+
['Crimson Tonic', 'A warm, peppery mixture that mends wounds.'],
|
|
22
|
+
['Wellspring Elixir', 'A clear elixir that glows faintly when shaken.']
|
|
23
|
+
],
|
|
24
|
+
Accessory: [
|
|
25
|
+
['Wayfinder Ring', 'A simple ring engraved with a tiny compass rose.'],
|
|
26
|
+
['Warden Pendant', 'A polished pendant that feels warm to the touch.'],
|
|
27
|
+
['Traveler’s Charm', 'A braided charm said to steady a weary traveler.']
|
|
28
|
+
],
|
|
29
|
+
Miscellaneous: [
|
|
30
|
+
['Ancient Coin', 'A curious coin bearing an unfamiliar crest.'],
|
|
31
|
+
['Sealed Map', 'A weathered map marked with a faded trail.'],
|
|
32
|
+
['Runed Trinket', 'A small keepsake etched with unreadable runes.']
|
|
33
|
+
]
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const ENCHANTMENTS = Object.freeze(['Fire', 'Ice', 'Poison', 'Lightning', 'Shadow', 'Holy']);
|
|
37
|
+
const ACCESSORY_STATS = Object.freeze(['strength', 'agility', 'vitality', 'wisdom']);
|
|
38
|
+
|
|
39
|
+
function scaled(base, level, multiplier) {
|
|
40
|
+
return Math.max(1, Math.round(base * (1 + (level - 1) * 0.12) * multiplier));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function createItem(random, type, options) {
|
|
44
|
+
const { level, rarity, enchantmentChance } = options;
|
|
45
|
+
const [name, description] = CATALOG[type][randomInt(random, 0, CATALOG[type].length - 1)];
|
|
46
|
+
const multiplier = RARITY_MULTIPLIERS[rarity];
|
|
47
|
+
const stats = {};
|
|
48
|
+
let valueBase = 8;
|
|
49
|
+
|
|
50
|
+
if (type === 'Weapon') {
|
|
51
|
+
stats.damage = scaled(randomInt(random, 5, 10), level, multiplier);
|
|
52
|
+
stats.speed = Number((randomInt(random, 7, 13) / 10 + (level - 1) * 0.01).toFixed(2));
|
|
53
|
+
valueBase = 18;
|
|
54
|
+
} else if (type === 'Armor') {
|
|
55
|
+
stats.defense = scaled(randomInt(random, 3, 8), level, multiplier);
|
|
56
|
+
stats.durability = scaled(randomInt(random, 35, 65), level, multiplier);
|
|
57
|
+
valueBase = 16;
|
|
58
|
+
} else if (type === 'Potion') {
|
|
59
|
+
stats.healing = scaled(randomInt(random, 18, 35), level, multiplier);
|
|
60
|
+
valueBase = 10;
|
|
61
|
+
} else if (type === 'Accessory') {
|
|
62
|
+
const stat = ACCESSORY_STATS[randomInt(random, 0, ACCESSORY_STATS.length - 1)];
|
|
63
|
+
stats[stat] = scaled(randomInt(random, 1, 3), level, multiplier);
|
|
64
|
+
valueBase = 22;
|
|
65
|
+
} else {
|
|
66
|
+
stats.collectible = true;
|
|
67
|
+
valueBase = 5;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const enchanted = type !== 'Miscellaneous' && random() < enchantmentChance;
|
|
71
|
+
const enchantment = enchanted ? ENCHANTMENTS[randomInt(random, 0, ENCHANTMENTS.length - 1)] : null;
|
|
72
|
+
if (enchantment) {
|
|
73
|
+
const statName = type === 'Weapon' ? 'damage' : type === 'Armor' ? 'defense' : type === 'Potion' ? 'healing' : Object.keys(stats)[0];
|
|
74
|
+
if (statName !== 'collectible') stats[statName] += Math.max(1, Math.round(level * 0.5));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const value = Math.max(1, Math.round(valueBase * (1 + level * 0.18) * multiplier * (enchanted ? 1.25 : 1)));
|
|
78
|
+
return {
|
|
79
|
+
name: enchantment ? `${enchantment} ${name}` : name,
|
|
80
|
+
type,
|
|
81
|
+
rarity,
|
|
82
|
+
level,
|
|
83
|
+
value,
|
|
84
|
+
stats,
|
|
85
|
+
enchantment,
|
|
86
|
+
description
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { CATALOG, ENCHANTMENTS, createItem };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { assertObject, clone, validateChance } = require('./utils');
|
|
4
|
+
const { validateRarity } = require('./rarity');
|
|
5
|
+
|
|
6
|
+
function createLootTable(items) {
|
|
7
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
8
|
+
throw new TypeError('Loot table items must be a non-empty array.');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const table = items.map((entry, index) => {
|
|
12
|
+
assertObject(entry, `Loot table entry ${index}`);
|
|
13
|
+
const item = entry.item === undefined
|
|
14
|
+
? Object.fromEntries(Object.entries(entry).filter(([key]) => key !== 'weight' && key !== 'dropChance'))
|
|
15
|
+
: entry.item;
|
|
16
|
+
assertObject(item, `Loot table entry ${index} item`);
|
|
17
|
+
const weight = entry.weight === undefined ? 1 : entry.weight;
|
|
18
|
+
const dropChance = entry.dropChance === undefined ? 1 : entry.dropChance;
|
|
19
|
+
if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {
|
|
20
|
+
throw new RangeError(`Loot table entry ${index} weight must be a non-negative finite number.`);
|
|
21
|
+
}
|
|
22
|
+
validateChance(dropChance, `Loot table entry ${index} dropChance`);
|
|
23
|
+
if (item.rarity !== undefined) validateRarity(item.rarity, `Loot table entry ${index} item rarity`);
|
|
24
|
+
return { item: clone(item), weight, dropChance };
|
|
25
|
+
});
|
|
26
|
+
if (table.every((entry) => entry.weight === 0)) {
|
|
27
|
+
throw new RangeError('Loot table must contain at least one entry with positive weight.');
|
|
28
|
+
}
|
|
29
|
+
return table;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function selectFromTable(random, table) {
|
|
33
|
+
if (!Array.isArray(table) || table.length === 0) {
|
|
34
|
+
throw new TypeError('table must be a non-empty loot table created with createLootTable().');
|
|
35
|
+
}
|
|
36
|
+
const entries = table.map((entry, index) => {
|
|
37
|
+
assertObject(entry, `Loot table entry ${index}`);
|
|
38
|
+
assertObject(entry.item, `Loot table entry ${index} item`);
|
|
39
|
+
const weight = entry.weight === undefined ? 1 : entry.weight;
|
|
40
|
+
const dropChance = entry.dropChance === undefined ? 1 : entry.dropChance;
|
|
41
|
+
if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {
|
|
42
|
+
throw new RangeError(`Loot table entry ${index} weight must be a non-negative finite number.`);
|
|
43
|
+
}
|
|
44
|
+
validateChance(dropChance, `Loot table entry ${index} dropChance`);
|
|
45
|
+
if (entry.item.rarity !== undefined) validateRarity(entry.item.rarity, `Loot table entry ${index} item rarity`);
|
|
46
|
+
return { item: entry.item, weight, dropChance };
|
|
47
|
+
}).filter((entry) => entry.weight > 0);
|
|
48
|
+
const largestWeight = Math.max(...entries.map((entry) => entry.weight));
|
|
49
|
+
if (!Number.isFinite(largestWeight)) throw new RangeError('Loot table weights must be finite.');
|
|
50
|
+
if (largestWeight === 0) throw new RangeError('Loot table must contain at least one entry with positive weight.');
|
|
51
|
+
const normalized = entries.map((entry) => ({ ...entry, weight: entry.weight / largestWeight }));
|
|
52
|
+
const totalWeight = normalized.reduce((sum, entry) => sum + entry.weight, 0);
|
|
53
|
+
|
|
54
|
+
let choice = random() * totalWeight;
|
|
55
|
+
let selected = normalized[normalized.length - 1];
|
|
56
|
+
for (const entry of normalized) {
|
|
57
|
+
choice -= entry.weight;
|
|
58
|
+
if (choice < 0) {
|
|
59
|
+
selected = entry;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return random() < selected.dropChance ? clone(selected.item) : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { createLootTable, selectFromTable };
|
package/lib/rarity.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const RARITIES = Object.freeze(['Common', 'Rare', 'Epic', 'Legendary']);
|
|
4
|
+
const DEFAULT_RARITY_WEIGHTS = Object.freeze({
|
|
5
|
+
Common: 60,
|
|
6
|
+
Rare: 25,
|
|
7
|
+
Epic: 10,
|
|
8
|
+
Legendary: 5
|
|
9
|
+
});
|
|
10
|
+
const RARITY_MULTIPLIERS = Object.freeze({
|
|
11
|
+
Common: 1,
|
|
12
|
+
Rare: 1.5,
|
|
13
|
+
Epic: 2.25,
|
|
14
|
+
Legendary: 3.5
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
function validateRarity(rarity, name = 'rarity') {
|
|
18
|
+
if (!RARITIES.includes(rarity)) {
|
|
19
|
+
throw new RangeError(`${name} must be one of: ${RARITIES.join(', ')}.`);
|
|
20
|
+
}
|
|
21
|
+
return rarity;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validateWeights(weights) {
|
|
25
|
+
if (weights === null || typeof weights !== 'object' || Array.isArray(weights)) {
|
|
26
|
+
throw new TypeError('rarityWeights must be an object keyed by rarity.');
|
|
27
|
+
}
|
|
28
|
+
const result = {};
|
|
29
|
+
for (const rarity of RARITIES) {
|
|
30
|
+
const weight = weights[rarity] === undefined ? DEFAULT_RARITY_WEIGHTS[rarity] : weights[rarity];
|
|
31
|
+
if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {
|
|
32
|
+
throw new RangeError(`Weight for ${rarity} must be a non-negative finite number.`);
|
|
33
|
+
}
|
|
34
|
+
result[rarity] = weight;
|
|
35
|
+
}
|
|
36
|
+
if (Object.values(result).every((weight) => weight === 0)) {
|
|
37
|
+
throw new RangeError('At least one rarity weight must be greater than zero.');
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function rollRarity(random, weights, luck = 0, minimum = 'Common') {
|
|
43
|
+
const minimumIndex = RARITIES.indexOf(validateRarity(minimum, 'minimum rarity'));
|
|
44
|
+
const largestWeight = Math.max(...Object.values(weights));
|
|
45
|
+
const adjusted = RARITIES.map((rarity, index) => {
|
|
46
|
+
if (index < minimumIndex) return 0;
|
|
47
|
+
return (weights[rarity] / largestWeight) * (1 + luck * index);
|
|
48
|
+
});
|
|
49
|
+
const total = adjusted.reduce((sum, weight) => sum + weight, 0);
|
|
50
|
+
if (total === 0) {
|
|
51
|
+
return RARITIES.slice(minimumIndex).find((rarity) => weights[rarity] > 0) || minimum;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let choice = random() * total;
|
|
55
|
+
for (let index = 0; index < RARITIES.length; index += 1) {
|
|
56
|
+
choice -= adjusted[index];
|
|
57
|
+
if (choice < 0) return RARITIES[index];
|
|
58
|
+
}
|
|
59
|
+
return 'Legendary';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = {
|
|
63
|
+
DEFAULT_RARITY_WEIGHTS,
|
|
64
|
+
RARITIES,
|
|
65
|
+
RARITY_MULTIPLIERS,
|
|
66
|
+
rollRarity,
|
|
67
|
+
validateRarity,
|
|
68
|
+
validateWeights
|
|
69
|
+
};
|
package/lib/utils.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function assertObject(value, name) {
|
|
4
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
5
|
+
throw new TypeError(`${name} must be an object.`);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function validateLevel(value, name = 'level') {
|
|
10
|
+
if (!Number.isInteger(value) || value < 1 || value > 1000) {
|
|
11
|
+
throw new RangeError(`${name} must be an integer between 1 and 1000.`);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function validateChance(value, name) {
|
|
17
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
18
|
+
throw new RangeError(`${name} must be a number between 0 and 1.`);
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function validateGoldRange(min, max) {
|
|
24
|
+
if (!Number.isSafeInteger(min) || min < 0) {
|
|
25
|
+
throw new RangeError('Gold minimum must be a non-negative safe integer.');
|
|
26
|
+
}
|
|
27
|
+
if (!Number.isSafeInteger(max) || max < min) {
|
|
28
|
+
throw new RangeError('Gold maximum must be a safe integer greater than or equal to the minimum.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function randomInt(random, min, max) {
|
|
33
|
+
return Math.floor(random() * (max - min + 1)) + min;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function clone(value) {
|
|
37
|
+
if (Array.isArray(value)) return value.map(clone);
|
|
38
|
+
if (value && typeof value === 'object') {
|
|
39
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function makeRandom(seed) {
|
|
45
|
+
if (seed === undefined || seed === null) return Math.random;
|
|
46
|
+
|
|
47
|
+
let state;
|
|
48
|
+
if (typeof seed === 'number' && Number.isFinite(seed)) {
|
|
49
|
+
state = seed >>> 0;
|
|
50
|
+
} else if (typeof seed === 'string') {
|
|
51
|
+
state = 2166136261;
|
|
52
|
+
for (let i = 0; i < seed.length; i += 1) {
|
|
53
|
+
state ^= seed.charCodeAt(i);
|
|
54
|
+
state = Math.imul(state, 16777619);
|
|
55
|
+
}
|
|
56
|
+
} else {
|
|
57
|
+
throw new TypeError('seed must be a finite number or a string.');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return function seededRandom() {
|
|
61
|
+
state += 0x6D2B79F5;
|
|
62
|
+
let value = state;
|
|
63
|
+
value = Math.imul(value ^ (value >>> 15), value | 1);
|
|
64
|
+
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
|
65
|
+
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
assertObject,
|
|
71
|
+
clone,
|
|
72
|
+
makeRandom,
|
|
73
|
+
randomInt,
|
|
74
|
+
validateChance,
|
|
75
|
+
validateGoldRange,
|
|
76
|
+
validateLevel
|
|
77
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lootgen-mayank",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A customizable, seeded loot and reward generator for RPGs and games.",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "node --test"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"loot-generator",
|
|
12
|
+
"random-loot",
|
|
13
|
+
"rpg",
|
|
14
|
+
"game-development",
|
|
15
|
+
"procedural-generation",
|
|
16
|
+
"rewards"
|
|
17
|
+
],
|
|
18
|
+
"author": "Mayank",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"lib/",
|
|
23
|
+
"examples/",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
}
|
|
30
|
+
}
|