mm_bag 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.
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 背包领域示例:装备、道具、数量与属性差异的处理
5
+ * 运行:node example/bag_demo.js
6
+ *
7
+ * 数据按「一格一条记录」存放,记录形如:
8
+ * {role_id: '1001', slot: 1, template_id: '4001', count: 99, bind: false, attrs: null}
9
+ * 堆叠规则由物品模板的 stack 决定,属性不同则分格存放。
10
+ */
11
+ const path = require('path');
12
+ const { dataAdmin } = require('mm_datas');
13
+ const { bagAdmin } = require('../index.js');
14
+
15
+ const ROOT_DIR = path.join(__dirname, 'data');
16
+ const ROLE_ID = 1001;
17
+
18
+ /**
19
+ * 初始化数据与背包实例
20
+ * @returns {Promise<object>} 背包实例
21
+ */
22
+ async function init() {
23
+ const data = dataAdmin('os', { stores: ['item', 'bag'], root_dir: ROOT_DIR });
24
+ await data.load('item');
25
+ return bagAdmin('os', { size: 8, data_scope: 'os' });
26
+ }
27
+
28
+ /**
29
+ * 打印背包明细
30
+ * @param {object} bag 背包实例
31
+ * @returns {Promise<void>} 无返回值
32
+ */
33
+ async function print(bag) {
34
+ const slots = await bag.slots(ROLE_ID);
35
+ const templates = await dataAdmin('os').getMany('item', slots.map((it) => it.template_id));
36
+ slots.forEach((it) => {
37
+ const tpl = templates[it.template_id];
38
+ const name = tpl ? tpl.name : '未知物品';
39
+ const attrs = it.attrs ? ` 属性${JSON.stringify(it.attrs)}` : '';
40
+ console.log(` 格${it.slot}: ${name} x${it.count}${it.bind ? '(绑定)' : ''}${attrs}`);
41
+ });
42
+ console.log(` 已用 ${slots.length} 格,剩余 ${await bag.free(ROLE_ID)} 格`);
43
+ }
44
+
45
+ /**
46
+ * 场景一:可叠加道具超出单格上限时自动拆格
47
+ * @param {object} bag 背包实例
48
+ * @returns {Promise<void>} 无返回值
49
+ */
50
+ async function showStack(bag) {
51
+ console.log('--- 道具:可叠加,超上限拆格 ---');
52
+ console.log('放入 120 瓶红药水,堆叠上限 99');
53
+ await bag.add(ROLE_ID, 4001, 120);
54
+ await print(bag);
55
+ }
56
+
57
+ /**
58
+ * 场景二:装备不可叠加,一件一格
59
+ * @param {object} bag 背包实例
60
+ * @returns {Promise<void>} 无返回值
61
+ */
62
+ async function showEquip(bag) {
63
+ console.log('--- 装备:堆叠上限 1,一件一格 ---');
64
+ console.log('放入 2 把绑定铁剑');
65
+ await bag.add(ROLE_ID, 4003, 2, { bind: true });
66
+ await print(bag);
67
+ }
68
+
69
+ /**
70
+ * 场景三:同模板但附加属性不同,不能合并
71
+ * @param {object} bag 背包实例
72
+ * @returns {Promise<void>} 无返回值
73
+ */
74
+ async function showAttrs(bag) {
75
+ console.log('--- 属性:同模板不同属性分格存放 ---');
76
+ console.log('放入 3 颗攻击力+5、2 颗攻击力+8 的攻击宝石');
77
+ await bag.add(ROLE_ID, 4005, 3, { attrs: { atk: 5 } });
78
+ await bag.add(ROLE_ID, 4005, 2, { attrs: { atk: 8 } });
79
+ await print(bag);
80
+ }
81
+
82
+ /**
83
+ * 场景四:跨格统计与数量判定
84
+ * @param {object} bag 背包实例
85
+ * @returns {Promise<void>} 无返回值
86
+ */
87
+ async function showCount(bag) {
88
+ console.log('--- 数量:跨格累加 ---');
89
+ console.log('红药水总数:', await bag.count(ROLE_ID, 4001));
90
+ console.log('攻击宝石总数:', await bag.count(ROLE_ID, 4005));
91
+ console.log('仅统计攻击力+5 的宝石:', await bag.count(ROLE_ID, 4005, { attrs: { atk: 5 } }));
92
+ console.log('是否有 200 瓶红药水:', await bag.has(ROLE_ID, 4001, 200));
93
+ }
94
+
95
+ /**
96
+ * 场景五:按属性筛选扣减,扣空的格子自动回收
97
+ * @param {object} bag 背包实例
98
+ * @returns {Promise<void>} 无返回值
99
+ */
100
+ async function showRemove(bag) {
101
+ console.log('--- 扣除:按属性筛选 ---');
102
+ console.log('扣 2 颗攻击力+5 的宝石,剩余该类:', await bag.remove(ROLE_ID, 4005, 2, { attrs: { atk: 5 } }));
103
+ console.log('再留 5 颗攻击力+8 的宝石不动,其他扣完');
104
+ console.log('扣掉 100 瓶红药水,剩余:', await bag.remove(ROLE_ID, 4001, 100));
105
+ await print(bag);
106
+ try {
107
+ await bag.remove(ROLE_ID, 4001, 999);
108
+ } catch (e) {
109
+ console.log('扣除超额:', e.message);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 场景六:格子容量不足时整体拒绝,不会写入一半
115
+ * @param {object} bag 背包实例
116
+ * @returns {Promise<void>} 无返回值
117
+ */
118
+ async function showFull(bag) {
119
+ console.log('--- 容量:格子有限 ---');
120
+ const free = await bag.free(ROLE_ID);
121
+ console.log(`剩余 ${free} 格,尝试放入 10 把铁剑`);
122
+ try {
123
+ await bag.add(ROLE_ID, 4003, 10);
124
+ } catch (e) {
125
+ console.log('放入失败:', e.message);
126
+ }
127
+ console.log('失败后背包未被改动:');
128
+ await print(bag);
129
+ }
130
+
131
+ /**
132
+ * 示例入口
133
+ * @returns {Promise<void>} 无返回值
134
+ */
135
+ async function main() {
136
+ const bag = await init();
137
+ await showStack(bag);
138
+ await showEquip(bag);
139
+ await showAttrs(bag);
140
+ await showCount(bag);
141
+ await showRemove(bag);
142
+ await showFull(bag);
143
+ }
144
+
145
+ main();
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "红药水",
3
+ "quality": 1,
4
+ "stack": 99,
5
+ "desc": "可叠加,一格最多 99 瓶"
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "铁剑",
3
+ "quality": 3,
4
+ "stack": 1,
5
+ "desc": "装备不可叠加,一件一格"
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "攻击宝石",
3
+ "quality": 2,
4
+ "stack": 20,
5
+ "desc": "可叠加,但附加属性不同的宝石不能合并"
6
+ }
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ const Bag = require('./lib/bag.js');
2
+ const adminLib = require('./lib/admin.js');
3
+
4
+ module.exports = {
5
+ Bag,
6
+ ...adminLib
7
+ };
package/lib/admin.js ADDED
@@ -0,0 +1,20 @@
1
+ const { reg } = require('mm_admin');
2
+ const Bag = require('./bag.js');
3
+
4
+ const admin = reg('bag');
5
+ admin.setClass(Bag);
6
+
7
+ /**
8
+ * 获取(或创建)指定作用域的背包实例
9
+ * @param {string} [scope] - 作用域,缺省为 os
10
+ * @param {object} [config] - 配置参数,仅首次创建时生效
11
+ * @returns {Bag} 背包实例
12
+ */
13
+ function bagAdmin(scope, config) {
14
+ return admin.get(scope || 'os', config);
15
+ }
16
+
17
+ module.exports = {
18
+ admin,
19
+ bagAdmin
20
+ };
package/lib/bag.js ADDED
@@ -0,0 +1,319 @@
1
+ const { dataAdmin } = require('mm_datas');
2
+
3
+ /**
4
+ * 背包类
5
+ * 以「一格一条记录」存放物品,记录内嵌角色标识与槽位,主键为 <角色标识>:<槽位>。
6
+ * 堆叠规则由物品模板的 stack 决定:stack 为 1 的物品(装备)一件一格,
7
+ * stack 大于 1 的物品(道具)按「绑定状态 + 附加属性 + 过期时间」分组合并,属性不同的不合并。
8
+ * 底层读写全部委托 mm_datas,本类只负责格子分配、堆叠判定与容量校验。
9
+ */
10
+ class Bag {
11
+ static config = {
12
+ name: '',
13
+ // 背包容量,即最大格子数
14
+ size: 60,
15
+ // mm_datas 实例名
16
+ data_scope: 'os',
17
+ // 物品模板类型
18
+ template_type: 'item',
19
+ // 背包记录类型
20
+ bag_type: 'bag',
21
+ // 模板中表示堆叠上限的字段名
22
+ stack_field: 'stack'
23
+ };
24
+
25
+ /**
26
+ * 构造函数
27
+ * @param {object} [config] - 配置
28
+ */
29
+ constructor(config) {
30
+ this.config = { ...Bag.config };
31
+ this.setConfig(config);
32
+ }
33
+
34
+ /**
35
+ * 设置配置,与已有配置浅合并
36
+ * @param {object} [config] - 配置
37
+ * @returns {void} 无返回值
38
+ */
39
+ setConfig(config) {
40
+ this.config = { ...this.config, ...config };
41
+ }
42
+
43
+ /**
44
+ * 底层数据实例,按 data_scope 获取
45
+ * @returns {object} Data 实例
46
+ */
47
+ get data() {
48
+ return dataAdmin(this.config.data_scope);
49
+ }
50
+
51
+ /**
52
+ * 拼格子主键
53
+ * @param {string|number} role_id - 角色标识
54
+ * @param {number} slot - 槽位
55
+ * @returns {string} 主键
56
+ */
57
+ key(role_id, slot) {
58
+ return `${role_id}:${slot}`;
59
+ }
60
+
61
+ /**
62
+ * 取背包全部格子,按槽位升序
63
+ * @param {string|number} role_id - 角色标识
64
+ * @returns {Promise<Array>} 格子数组
65
+ */
66
+ async slots(role_id) {
67
+ const rows = await this.data.find(this.config.bag_type, { role_id: String(role_id) });
68
+ return Object.values(rows).sort((a, b) => a.slot - b.slot);
69
+ }
70
+
71
+ /**
72
+ * 统计某模板物品的总数量,跨格累加
73
+ * @param {string|number} role_id - 角色标识
74
+ * @param {string|number} template_id - 物品模板标识
75
+ * @param {object} [match] - 附加筛选条件,如 {bind: true} 或 {attrs: {atk: 5}}
76
+ * @returns {Promise<number>} 总数量
77
+ */
78
+ async count(role_id, template_id, match) {
79
+ const rows = await this.data.find(this.config.bag_type, {
80
+ role_id: String(role_id),
81
+ template_id: String(template_id),
82
+ ...match
83
+ });
84
+ return Object.values(rows).reduce((sum, it) => sum + it.count, 0);
85
+ }
86
+
87
+ /**
88
+ * 判断某模板物品的数量是否不少于指定值
89
+ * @param {string|number} role_id - 角色标识
90
+ * @param {string|number} template_id - 物品模板标识
91
+ * @param {number} [num] - 判定数量,缺省为 1
92
+ * @param {object} [match] - 附加筛选条件
93
+ * @returns {Promise<boolean>} 是否足够
94
+ */
95
+ async has(role_id, template_id, num = 1, match) {
96
+ return (await this.count(role_id, template_id, match)) >= num;
97
+ }
98
+
99
+ /**
100
+ * 统计已占用格数
101
+ * @param {string|number} role_id - 角色标识
102
+ * @returns {Promise<number>} 已用格数
103
+ */
104
+ async used(role_id) {
105
+ return (await this.slots(role_id)).length;
106
+ }
107
+
108
+ /**
109
+ * 统计剩余格数
110
+ * @param {string|number} role_id - 角色标识
111
+ * @returns {Promise<number>} 剩余格数
112
+ */
113
+ async free(role_id) {
114
+ return this.config.size - (await this.used(role_id));
115
+ }
116
+
117
+ /**
118
+ * 取物品模板的堆叠上限,未配置或非法时按 1 处理
119
+ * @param {string|number} template_id - 物品模板标识
120
+ * @returns {Promise<number>} 堆叠上限
121
+ */
122
+ async stackOf(template_id) {
123
+ const template = await this.data.get(this.config.template_type, template_id);
124
+ const stack = template ? template[this.config.stack_field] : 1;
125
+ return typeof stack === 'number' && stack > 0 ? stack : 1;
126
+ }
127
+
128
+ /**
129
+ * 判断格子与待放入物品是否属于同一堆叠组
130
+ * @param {object} slot - 已有格子记录
131
+ * @param {object} options - 放入选项
132
+ * @returns {boolean} 是否可合并
133
+ */
134
+ sameStack(slot, options) {
135
+ const bind = options.bind || false;
136
+ const expire_at = options.expire_at || 0;
137
+ const attrs = options.attrs || null;
138
+ return slot.bind === bind
139
+ && slot.expire_at === expire_at
140
+ && JSON.stringify(slot.attrs) === JSON.stringify(attrs);
141
+ }
142
+
143
+ /**
144
+ * 构造一条格子记录
145
+ * @param {string|number} role_id - 角色标识
146
+ * @param {number} slot - 槽位
147
+ * @param {string} template_id - 物品模板标识
148
+ * @param {number} count - 数量
149
+ * @param {object} options - 放入选项
150
+ * @returns {object} 格子记录
151
+ */
152
+ make(role_id, slot, template_id, count, options) {
153
+ return {
154
+ role_id: String(role_id),
155
+ slot,
156
+ template_id,
157
+ count,
158
+ bind: options.bind || false,
159
+ attrs: options.attrs || null,
160
+ expire_at: options.expire_at || 0,
161
+ created_at: Date.now()
162
+ };
163
+ }
164
+
165
+ /**
166
+ * 放入物品:可堆叠的先合并,剩余的开新格;装备按件独立占格
167
+ * @param {string|number} role_id - 角色标识
168
+ * @param {string|number} template_id - 物品模板标识
169
+ * @param {number} [num] - 放入数量,缺省为 1
170
+ * @param {object} [options] - {bind: 绑定, attrs: 附加属性, expire_at: 过期时间戳}
171
+ * @returns {Promise<number>} 实际放入数量
172
+ * @throws {Error} 数量非正数或背包空间不足时抛出
173
+ */
174
+ async add(role_id, template_id, num = 1, options = {}) {
175
+ if (!(num > 0)) {
176
+ throw new Error(`放入数量必须是正数,收到 ${num}`);
177
+ }
178
+ const tid = String(template_id);
179
+ const stack = await this.stackOf(tid);
180
+ let left = num;
181
+ if (stack > 1) {
182
+ left = await this.fill(role_id, tid, stack, num, options);
183
+ }
184
+ if (left > 0) {
185
+ await this.open(role_id, tid, stack, left, options);
186
+ }
187
+ return num;
188
+ }
189
+
190
+ /**
191
+ * 把待放入数量填充到已有格子的剩余空间
192
+ * @param {string|number} role_id - 角色标识
193
+ * @param {string} template_id - 物品模板标识
194
+ * @param {number} stack - 堆叠上限
195
+ * @param {number} num - 待放入数量
196
+ * @param {object} options - 放入选项
197
+ * @returns {Promise<number>} 仍未放入的数量
198
+ */
199
+ async fill(role_id, template_id, stack, num, options) {
200
+ const slots = await this.slots(role_id);
201
+ let left = num;
202
+ for (const slot of slots) {
203
+ if (left <= 0) {
204
+ break;
205
+ }
206
+ if (slot.template_id !== template_id || slot.count >= stack) {
207
+ continue;
208
+ }
209
+ if (!this.sameStack(slot, options)) {
210
+ continue;
211
+ }
212
+ const add = Math.min(stack - slot.count, left);
213
+ const key = this.key(role_id, slot.slot);
214
+ await this.data.patch(this.config.bag_type, key, { count: slot.count + add });
215
+ left -= add;
216
+ }
217
+ return left;
218
+ }
219
+
220
+ /**
221
+ * 从最小空闲槽位开始开新格子
222
+ * @param {string|number} role_id - 角色标识
223
+ * @param {string} template_id - 物品模板标识
224
+ * @param {number} stack - 堆叠上限
225
+ * @param {number} num - 待放入数量
226
+ * @param {object} options - 放入选项
227
+ * @returns {Promise<number>} 放入数量
228
+ * @throws {Error} 背包空间不足时抛出
229
+ */
230
+ async open(role_id, template_id, stack, num, options) {
231
+ const slots = await this.slots(role_id);
232
+ const used = new Set(slots.map((it) => it.slot));
233
+ const need = Math.ceil(num / stack);
234
+ const avail = this.config.size - used.size;
235
+ if (need > avail) {
236
+ throw new Error(`背包空间不足,需要 ${need} 格,当前剩余 ${avail} 格`);
237
+ }
238
+ let left = num;
239
+ let slot_no = 1;
240
+ while (left > 0) {
241
+ while (used.has(slot_no)) {
242
+ slot_no += 1;
243
+ }
244
+ const put = Math.min(stack, left);
245
+ const record = this.make(role_id, slot_no, template_id, put, options);
246
+ await this.data.set(this.config.bag_type, this.key(role_id, slot_no), record);
247
+ used.add(slot_no);
248
+ left -= put;
249
+ }
250
+ return num;
251
+ }
252
+
253
+ /**
254
+ * 扣除物品:从末尾格子开始扣,扣空的格子直接移除
255
+ * @param {string|number} role_id - 角色标识
256
+ * @param {string|number} template_id - 物品模板标识
257
+ * @param {number} [num] - 扣除数量,缺省为 1
258
+ * @param {object} [match] - 附加筛选条件,如 {bind: true} 只扣绑定物品
259
+ * @returns {Promise<number>} 扣除后的总数量
260
+ * @throws {Error} 数量非正数或持有量不足时抛出
261
+ */
262
+ async remove(role_id, template_id, num = 1, match) {
263
+ if (!(num > 0)) {
264
+ throw new Error(`扣除数量必须是正数,收到 ${num}`);
265
+ }
266
+ const tid = String(template_id);
267
+ const rows = await this.data.find(this.config.bag_type, {
268
+ role_id: String(role_id),
269
+ template_id: tid,
270
+ ...match
271
+ });
272
+ const slots = Object.values(rows).sort((a, b) => b.slot - a.slot);
273
+ const total = slots.reduce((sum, it) => sum + it.count, 0);
274
+ if (total < num) {
275
+ throw new Error(`物品 ${tid} 数量不足,当前 ${total},需要 ${num}`);
276
+ }
277
+ let left = num;
278
+ for (const slot of slots) {
279
+ if (left <= 0) {
280
+ break;
281
+ }
282
+ const take = Math.min(slot.count, left);
283
+ left -= take;
284
+ await this.saveSlot(role_id, slot, slot.count - take);
285
+ }
286
+ return total - num;
287
+ }
288
+
289
+ /**
290
+ * 更新或移除单个格子,数量归零时删除记录
291
+ * @param {string|number} role_id - 角色标识
292
+ * @param {object} slot - 格子记录
293
+ * @param {number} count - 更新后的数量
294
+ * @returns {Promise<void>} 无返回值
295
+ */
296
+ async saveSlot(role_id, slot, count) {
297
+ const key = this.key(role_id, slot.slot);
298
+ if (count > 0) {
299
+ await this.data.patch(this.config.bag_type, key, { count });
300
+ } else {
301
+ await this.data.del(this.config.bag_type, key);
302
+ }
303
+ }
304
+
305
+ /**
306
+ * 清空整个背包
307
+ * @param {string|number} role_id - 角色标识
308
+ * @returns {Promise<number>} 清空前的格子数
309
+ */
310
+ async clear(role_id) {
311
+ const slots = await this.slots(role_id);
312
+ for (const slot of slots) {
313
+ await this.data.del(this.config.bag_type, this.key(role_id, slot.slot));
314
+ }
315
+ return slots.length;
316
+ }
317
+ }
318
+
319
+ module.exports = Bag;
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "mm_bag",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "背包领域模块:以「一格一条记录」存放物品,模板 stack 决定堆叠上限,装备一件一格、道具按绑定与附加属性分组合并;支持跨格数量统计、按属性筛选扣减、容量校验与空格回收,底层数据读写委托 mm_datas",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "lib",
9
+ "tool",
10
+ "example"
11
+ ],
12
+ "scripts": {
13
+ "demo": "node example/bag_demo.js",
14
+ "lint": "eslint .",
15
+ "lint:fix": "eslint . --fix --rule \"naming-convention/class-name:off\" --rule \"naming-convention/function-name:off\" --rule \"naming-convention/variable-name:off\" --rule \"naming-convention/constant-name:off\" --rule \"naming-convention/param-name:off\" --rule \"prefer-arrow-callback:off\""
16
+ },
17
+ "keywords": [
18
+ "mm_mod",
19
+ "mm_bag",
20
+ "domain",
21
+ "bag",
22
+ "inventory",
23
+ "item",
24
+ "stack",
25
+ "equipment",
26
+ "背包",
27
+ "游戏数据"
28
+ ],
29
+ "layer": "domain",
30
+ "group": "bag",
31
+ "author": "邱文武",
32
+ "license": "ISC",
33
+ "dependencies": {
34
+ "mm_admin": "^1.2.2",
35
+ "mm_datas": "^6.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "eslint": "^10.15.0",
39
+ "eslint-plugin-jsdoc": "^65.5.7",
40
+ "mm_eslint": "^2.15.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=18.0.0"
44
+ }
45
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.