lootgen-mayank 0.0.0-stage → 1.0.1

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 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,117 @@
1
- # Temporary Holding Version
1
+ # LootGen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ LootGen makes random items and rewards for RPG games. It works in Node.js and
4
+ does not need any extra packages.
5
+
6
+ ## Install
7
+
8
+ npm install lootgen-mayank
9
+
10
+ ## Use
11
+
12
+ const LootGenerator = require('lootgen-mayank');
13
+
14
+ const loot = new LootGenerator().generateLoot();
15
+ console.log(loot);
16
+
17
+ Items have a name, type, rarity, level, value, stats, enchantment, and
18
+ description. The available types are `Weapon`, `Armor`, `Potion`, `Accessory`,
19
+ and `Miscellaneous`.
20
+
21
+ You can set options when making a generator:
22
+
23
+ const generator = new LootGenerator({
24
+ seed: 'game-1',
25
+ level: 5,
26
+ luck: 0.2
27
+ });
28
+
29
+ console.log(generator.generateWeapon());
30
+ console.log(generator.generateGold());
31
+
32
+ Using the same seed and making the same calls gives the same results. Without
33
+ a seed, generation uses regular random values.
34
+
35
+ ## Options
36
+
37
+ | Option | Default | What it does |
38
+ | --- | --- | --- |
39
+ | `seed` | None | A string or finite number for repeatable results. |
40
+ | `level` | `1` | Default item level, from 1 to 1000. |
41
+ | `luck` | `0` | Shifts rarity rolls toward better items, from 0 to 1. |
42
+ | `rarityWeights` | Common 60, Rare 25, Epic 10, Legendary 5 | Sets the relative chance of each rarity. |
43
+ | `enchantmentChance` | `0.15` | Chance of an enchantment, from 0 to 1. |
44
+ | `gold` | `{ min: 5, max: 25 }` | Default gold range. |
45
+
46
+ Rarity weights do not have to add up to 100. At least one weight must be
47
+ greater than zero.
48
+
49
+ ## Main methods
50
+
51
+ - `generateLoot(options)` makes a random item. Options can include `type`,
52
+ `level`, `rarity`, `minimumRarity`, `luck`, `rarityWeights`, and
53
+ `enchantmentChance`. It can also use a custom `table`.
54
+ - `generateWeapon(options)`, `generateArmor(options)`, and
55
+ `generatePotion(options)` make a specific type of item.
56
+ - `generateMultiple(count, options)` makes an array of items.
57
+ - `generateGold({ min, max })` returns a random whole number of gold. The
58
+ range can be set on the generator or for one call.
59
+ - `generateChest(options)` returns an object with `items` and `gold`. It makes
60
+ 2 to 5 items by default. Set `minItems` and `maxItems` to change the count.
61
+ Use `guaranteedRarity` to set a rarity floor for the first item, or set
62
+ `gold` to `true` or to a `{ min, max }` range to add gold.
63
+ `goldRange` sets the range used when `gold` is `true`. A custom `table` can
64
+ be used for the items.
65
+ - `generateBossLoot(options)` returns `items` and `gold`. By default it makes
66
+ three items, gives the first item at least Rare rarity, and adds 50 bonus
67
+ gold. You can set `itemCount`, `guaranteedRarity`, `bonusGold`, `goldRange`,
68
+ `rarityWeights`, and a custom `table`.
69
+ - `setLuck(value)`, `setLevel(value)`, and `setRarityWeights(weights)` change
70
+ the generator's defaults. Each method returns the generator.
71
+
72
+ Chest and boss generation also accept `minimumRarity`, `level`, `luck`, and
73
+ `enchantmentChance`.
74
+
75
+ ## Custom loot tables
76
+
77
+ Make a table with `createLootTable`, then use it with `generateFromTable`,
78
+ `generateLoot`, `generateChest`, or `generateBossLoot`.
79
+
80
+ const table = generator.createLootTable([
81
+ {
82
+ item: { name: 'Copper Key', type: 'Miscellaneous', rarity: 'Common' },
83
+ weight: 3
84
+ },
85
+ {
86
+ item: { name: 'Silver Key', type: 'Miscellaneous', rarity: 'Rare' },
87
+ weight: 1,
88
+ dropChance: 0.5
89
+ }
90
+ ]);
91
+
92
+ console.log(generator.generateFromTable(table));
93
+
94
+ Each entry needs an item. `weight` defaults to `1`; `dropChance` also defaults
95
+ to `1` and must be from 0 to 1. A table roll can return `null` if the selected
96
+ item does not drop. When a table is used for a chest, missed drops are left
97
+ out. For boss loot and `generateLoot`, a miss uses a regular generated item
98
+ instead.
99
+
100
+ ## Examples and tests
101
+
102
+ The `examples` folder has short scripts for basic loot, custom settings,
103
+ chests, and boss rewards. Run one from the package folder, for example:
104
+
105
+ node examples/chest.js
106
+
107
+ Run the tests with:
108
+
109
+ npm test
110
+
111
+ ## Exports
112
+
113
+ The package exports the `LootGenerator` class. It also exposes `RARITIES`,
114
+ `DEFAULT_RARITY_WEIGHTS`, and `ENCHANTMENTS` as properties on the class.
115
+
116
+ const LootGenerator = require('lootgen-mayank');
117
+ const { RARITIES, ENCHANTMENTS } = LootGenerator;
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ const LootGenerator = require('..');
4
+
5
+ const loot = new LootGenerator().generateLoot();
6
+ console.log(`${loot.rarity} ${loot.name} (value: ${loot.value} gold)`);
@@ -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;
@@ -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 sword made of iron.'],
9
+ ['Bow', 'A bow for ranged attacks.'],
10
+ ['Warhammer', 'A heavy hammer.'],
11
+ ['Dagger', 'A small dagger.']
12
+ ],
13
+ Armor: [
14
+ ['Chest Armor', 'Armor that protects the chest.'],
15
+ ['Shield', 'A shield made from wood and iron.'],
16
+ ['Helmet', 'A metal helmet.'],
17
+ ['Scale Armor', 'Armor made from metal scales.']
18
+ ],
19
+ Potion: [
20
+ ['Healing Potion', 'A potion that restores health.'],
21
+ ['Health Potion', 'A potion that helps heal injuries.'],
22
+ ['Strong Healing Potion', 'A stronger healing potion.']
23
+ ],
24
+ Accessory: [
25
+ ['Ring', 'A ring with a compass design.'],
26
+ ['Pendant', 'A simple pendant.'],
27
+ ['Charm', 'A small braided charm.']
28
+ ],
29
+ Miscellaneous: [
30
+ ['Old Coin', 'An old coin with a crest.'],
31
+ ['Map', 'A map with a marked trail.'],
32
+ ['Rune Trinket', 'A small trinket with 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": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "A random RPG loot generator for Node.js.",
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
+ }