dopaminejs 2.3.1 → 2.5.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/dist/DataService-BPXCldpo.cjs +1 -0
- package/dist/DataService-CH9_gv_8.js +398 -0
- package/dist/ScreenShake-9jgNXPS6.cjs +1 -0
- package/dist/ScreenShake-CLvO1wx4.js +827 -0
- package/dist/core.cjs +1 -0
- package/dist/core.js +2 -0
- package/dist/dopamine.cjs +7 -7
- package/dist/dopamine.js +626 -1395
- package/dist/engine.cjs +1 -1
- package/dist/engine.js +2 -1158
- package/dist/style.css +2 -1
- package/package.json +6 -1
- package/src/core/PluginRegistry.js +90 -5
- package/src/dopamine/audio/SoundManager.js +31 -2
- package/src/dopamine/core/DataService.js +25 -5
- package/src/dopamine/core/RewardSystem.js +50 -2
- package/src/dopamine/effects/ParticleSystem.js +3 -3
- package/src/dopamine/feel/haptics.js +21 -0
- package/src/dopamine/feel/motion.js +9 -0
- package/src/dopamine/ui/GameUI.js +193 -8
- package/src/index.js +4 -0
- package/src/progression.js +13 -0
- package/src/systems/Physics.js +89 -0
- package/types/core.d.ts +27 -0
- package/types/index.d.ts +87 -5
|
@@ -5,9 +5,165 @@
|
|
|
5
5
|
|
|
6
6
|
const OVERLAY_ID = 'game-ui-overlay';
|
|
7
7
|
|
|
8
|
+
const DEFAULT_TEXT = {
|
|
9
|
+
levelUp: 'LEVEL UP!',
|
|
10
|
+
achievementUnlocked: 'Achievement Unlocked!',
|
|
11
|
+
nearMiss: 'CLOSE CALL!'
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const DEFAULT_STREAK_ICON = '🔥';
|
|
15
|
+
|
|
16
|
+
// Config comes from callers, so an inherited property (a polluted prototype)
|
|
17
|
+
// must not count.
|
|
18
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
19
|
+
const ownValue = (object, key) =>
|
|
20
|
+
(object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
|
|
21
|
+
|
|
22
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
23
|
+
|
|
24
|
+
const SVG_ELEMENTS = new Set([
|
|
25
|
+
'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline',
|
|
26
|
+
'polygon', 'text', 'tspan', 'title', 'desc', 'defs', 'linearGradient',
|
|
27
|
+
'radialGradient', 'stop', 'clipPath', 'mask'
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
// No style, no href, no event handlers: only geometry and paint.
|
|
31
|
+
const SVG_ATTRIBUTES = new Set([
|
|
32
|
+
'viewBox', 'width', 'height', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy',
|
|
33
|
+
'r', 'rx', 'ry', 'd', 'points', 'transform', 'fill', 'fill-opacity',
|
|
34
|
+
'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
|
|
35
|
+
'stroke-opacity', 'opacity', 'offset', 'stop-color', 'stop-opacity',
|
|
36
|
+
'gradientUnits', 'gradientTransform', 'clip-path', 'mask', 'clip-rule',
|
|
37
|
+
'font-size', 'font-family', 'font-weight', 'text-anchor', 'id',
|
|
38
|
+
'aria-hidden', 'aria-label', 'role'
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
// Attributes that may point at a gradient, clip path or mask in the same icon.
|
|
42
|
+
const REFERENCE_ATTRIBUTES = new Set(['fill', 'stroke', 'clip-path', 'mask']);
|
|
43
|
+
const TRANSFORM_ATTRIBUTES = new Set(['transform', 'gradientTransform']);
|
|
44
|
+
|
|
45
|
+
const SINGLE_FRAGMENT_URL = /^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/;
|
|
46
|
+
const PLAIN_COLOUR = /^[#a-zA-Z0-9(),.%\s-]+$/;
|
|
47
|
+
const PLAIN_TRANSFORM = /^[a-zA-Z0-9(),.\s-]+$/;
|
|
48
|
+
const SAFE_ID = /^[A-Za-z][\w.:-]*$/;
|
|
49
|
+
|
|
50
|
+
// Ids inside an icon are page-global (window.<id>, getElementById), so every
|
|
51
|
+
// render gets its own prefix.
|
|
52
|
+
let iconCounter = 0;
|
|
53
|
+
|
|
54
|
+
function collectIds(node, ids) {
|
|
55
|
+
if (node.nodeType !== 1 || node.namespaceURI !== SVG_NS || !SVG_ELEMENTS.has(node.localName)) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const id = node.getAttribute('id');
|
|
59
|
+
if (id && SAFE_ID.test(id)) ids.add(id);
|
|
60
|
+
for (const child of Array.from(node.childNodes)) collectIds(child, ids);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Returns the value to write, or null to drop the attribute.
|
|
65
|
+
*/
|
|
66
|
+
function cleanValue(name, value, ctx) {
|
|
67
|
+
if (value.includes('\\')) return null;
|
|
68
|
+
const trimmed = value.trim();
|
|
69
|
+
|
|
70
|
+
if (name === 'id') {
|
|
71
|
+
return SAFE_ID.test(trimmed) ? ctx.prefix + trimmed : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (REFERENCE_ATTRIBUTES.has(name)) {
|
|
75
|
+
const ref = SINGLE_FRAGMENT_URL.exec(trimmed);
|
|
76
|
+
if (ref) {
|
|
77
|
+
return ctx.ids.has(ref[1]) ? `url(#${ctx.prefix}${ref[1]})` : null;
|
|
78
|
+
}
|
|
79
|
+
return PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (TRANSFORM_ATTRIBUTES.has(name)) {
|
|
83
|
+
return PLAIN_TRANSFORM.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (value.includes('(')) {
|
|
87
|
+
// Only a plain colour such as rgb() or hsl() is acceptable here.
|
|
88
|
+
return name === 'stop-color' && PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed)
|
|
89
|
+
? trimmed
|
|
90
|
+
: null;
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function cleanNode(source, ctx) {
|
|
96
|
+
// 3 is text, 4 is CDATA.
|
|
97
|
+
if (source.nodeType === 3 || source.nodeType === 4) {
|
|
98
|
+
return document.createTextNode(source.data);
|
|
99
|
+
}
|
|
100
|
+
if (source.nodeType !== 1
|
|
101
|
+
|| source.namespaceURI !== SVG_NS
|
|
102
|
+
|| !SVG_ELEMENTS.has(source.localName)) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const clean = document.createElementNS(SVG_NS, source.localName);
|
|
107
|
+
for (const attr of Array.from(source.attributes)) {
|
|
108
|
+
if (attr.namespaceURI !== null || !SVG_ATTRIBUTES.has(attr.name)) continue;
|
|
109
|
+
const value = cleanValue(attr.name, attr.value, ctx);
|
|
110
|
+
if (value !== null) clean.setAttribute(attr.name, value);
|
|
111
|
+
}
|
|
112
|
+
for (const child of Array.from(source.childNodes)) {
|
|
113
|
+
const kept = cleanNode(child, ctx);
|
|
114
|
+
if (kept) clean.appendChild(kept);
|
|
115
|
+
}
|
|
116
|
+
return clean;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Parse a string as SVG and rebuild it from an allowlist of elements and
|
|
121
|
+
* attributes, so nothing that can run script or load a resource survives.
|
|
122
|
+
* Returns null unless the whole string is one valid <svg> document.
|
|
123
|
+
*/
|
|
124
|
+
function parseSafeSvg(markup) {
|
|
125
|
+
let doc;
|
|
126
|
+
// Inline HTML SVG usually has no xmlns, which the XML parser rejects.
|
|
127
|
+
const source = /^\s*<svg[\s>]/.test(markup) && !/^\s*<svg\b[^>]*\sxmlns\s*=/.test(markup)
|
|
128
|
+
? markup.replace(/^(\s*<svg)/, `$1 xmlns="${SVG_NS}"`)
|
|
129
|
+
: markup;
|
|
130
|
+
try {
|
|
131
|
+
doc = new DOMParser().parseFromString(source,'image/svg+xml');
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const root = doc.documentElement;
|
|
136
|
+
if (!root || root.localName !== 'svg' || doc.getElementsByTagName('parsererror').length > 0) {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
const ids = new Set();
|
|
140
|
+
collectIds(root, ids);
|
|
141
|
+
return cleanNode(root, { ids, prefix: `dj-icon-${++iconCounter}-` });
|
|
142
|
+
}
|
|
143
|
+
|
|
8
144
|
export class GameUI {
|
|
9
|
-
|
|
145
|
+
/**
|
|
146
|
+
* @param {Object} particleSystem
|
|
147
|
+
* @param {Object} [config]
|
|
148
|
+
* @param {{levelUp?: string, achievementUnlocked?: string, nearMiss?: string}} [config.text]
|
|
149
|
+
* Replaces the built-in popup strings.
|
|
150
|
+
* @param {{streak?: string|Node}} [config.icons]
|
|
151
|
+
* @param {boolean} [config.safeIcons] - Render string icons as sanitised
|
|
152
|
+
* SVG or plain text instead of HTML. Default false.
|
|
153
|
+
*/
|
|
154
|
+
constructor(particleSystem, config = {}) {
|
|
10
155
|
this.particleSystem = particleSystem;
|
|
156
|
+
|
|
157
|
+
// Only strings override a default, so a non-string cannot break a
|
|
158
|
+
// popup. An empty string is allowed and hides that text.
|
|
159
|
+
const textConfig = ownValue(config, 'text');
|
|
160
|
+
this.text = { ...DEFAULT_TEXT };
|
|
161
|
+
for (const key of Object.keys(DEFAULT_TEXT)) {
|
|
162
|
+
const value = ownValue(textConfig, key);
|
|
163
|
+
if (typeof value === 'string') this.text[key] = value;
|
|
164
|
+
}
|
|
165
|
+
this.safeIcons = ownValue(config, 'safeIcons') === true;
|
|
166
|
+
this._streakIcon = ownValue(ownValue(config, 'icons'), 'streak') ?? DEFAULT_STREAK_ICON;
|
|
11
167
|
this.container = null;
|
|
12
168
|
this.xpBar = null;
|
|
13
169
|
this.levelDisplay = null;
|
|
@@ -50,7 +206,7 @@ export class GameUI {
|
|
|
50
206
|
</div>
|
|
51
207
|
|
|
52
208
|
<div class="streak-badge">
|
|
53
|
-
<span class="streak-icon"
|
|
209
|
+
<span class="streak-icon"></span>
|
|
54
210
|
<span class="streak-number">1</span>
|
|
55
211
|
</div>
|
|
56
212
|
</div>
|
|
@@ -82,6 +238,31 @@ export class GameUI {
|
|
|
82
238
|
this.xpText = this.container.querySelector('.xp-text');
|
|
83
239
|
this.levelDisplay = this.container.querySelector('.level-number');
|
|
84
240
|
this.streakDisplay = this.container.querySelector('.streak-number');
|
|
241
|
+
this._setIcon(this.container.querySelector('.streak-icon'), this._streakIcon);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Single place where icons reach the DOM. A Node is appended. A string is
|
|
246
|
+
* HTML unless safeIcons is on (see SECURITY.md); then it is a sanitised
|
|
247
|
+
* SVG or plain text.
|
|
248
|
+
* @private
|
|
249
|
+
*/
|
|
250
|
+
_setIcon(el, icon) {
|
|
251
|
+
el.textContent = '';
|
|
252
|
+
if (typeof Node !== 'undefined' && icon instanceof Node) {
|
|
253
|
+
el.appendChild(icon);
|
|
254
|
+
} else if (typeof icon !== 'string') {
|
|
255
|
+
return;
|
|
256
|
+
} else if (!this.safeIcons) {
|
|
257
|
+
el.innerHTML = icon;
|
|
258
|
+
} else {
|
|
259
|
+
const svg = parseSafeSvg(icon);
|
|
260
|
+
if (svg) {
|
|
261
|
+
el.appendChild(svg);
|
|
262
|
+
} else {
|
|
263
|
+
el.textContent = icon;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
85
266
|
}
|
|
86
267
|
|
|
87
268
|
/**
|
|
@@ -173,8 +354,9 @@ export class GameUI {
|
|
|
173
354
|
/**
|
|
174
355
|
* Show achievement unlocked popup
|
|
175
356
|
*
|
|
176
|
-
* `icon` is rendered as HTML by design (documented in
|
|
177
|
-
* games can pass an <img> or inline SVG).
|
|
357
|
+
* A string `icon` is rendered as HTML by design (documented in
|
|
358
|
+
* ARCHITECTURE.md, so games can pass an <img> or inline SVG). A Node is
|
|
359
|
+
* appended as is. Every other field is game state
|
|
178
360
|
* and could carry a player-supplied or server-supplied string, so it goes
|
|
179
361
|
* in as text.
|
|
180
362
|
*/
|
|
@@ -186,7 +368,7 @@ export class GameUI {
|
|
|
186
368
|
<div class="achievement-content">
|
|
187
369
|
<div class="achievement-icon"></div>
|
|
188
370
|
<div class="achievement-info">
|
|
189
|
-
<div class="achievement-title"
|
|
371
|
+
<div class="achievement-title"></div>
|
|
190
372
|
<div class="achievement-name"></div>
|
|
191
373
|
<div class="achievement-desc"></div>
|
|
192
374
|
<div class="achievement-xp"></div>
|
|
@@ -194,7 +376,8 @@ export class GameUI {
|
|
|
194
376
|
</div>
|
|
195
377
|
`;
|
|
196
378
|
|
|
197
|
-
popup.querySelector('.achievement-
|
|
379
|
+
popup.querySelector('.achievement-title').textContent = this.text.achievementUnlocked;
|
|
380
|
+
this._setIcon(popup.querySelector('.achievement-icon'), achievement.icon);
|
|
198
381
|
popup.querySelector('.achievement-name').textContent = achievement.name ?? '';
|
|
199
382
|
popup.querySelector('.achievement-desc').textContent = achievement.description ?? '';
|
|
200
383
|
popup.querySelector('.achievement-xp').textContent = `+${achievement.xp ?? 0} XP`;
|
|
@@ -223,11 +406,12 @@ export class GameUI {
|
|
|
223
406
|
overlay.className = 'level-up-overlay';
|
|
224
407
|
overlay.innerHTML = `
|
|
225
408
|
<div class="level-up-content">
|
|
226
|
-
<div class="level-up-title"
|
|
409
|
+
<div class="level-up-title"></div>
|
|
227
410
|
<div class="level-up-number"></div>
|
|
228
411
|
<div class="level-up-subtitle">Amazing progress!</div>
|
|
229
412
|
</div>
|
|
230
413
|
`;
|
|
414
|
+
overlay.querySelector('.level-up-title').textContent = this.text.levelUp;
|
|
231
415
|
overlay.querySelector('.level-up-number').textContent = newLevel;
|
|
232
416
|
|
|
233
417
|
this._mount(overlay);
|
|
@@ -280,7 +464,7 @@ export class GameUI {
|
|
|
280
464
|
* Show "near miss" indicator
|
|
281
465
|
*/
|
|
282
466
|
showNearMiss(x, y) {
|
|
283
|
-
this.showFloatingText(
|
|
467
|
+
this.showFloatingText(this.text.nearMiss, x, y, '#45b7d1', '20px');
|
|
284
468
|
this.particleSystem.sparkle(x, y, 15, '#45b7d1');
|
|
285
469
|
}
|
|
286
470
|
|
|
@@ -416,5 +600,6 @@ export class GameUI {
|
|
|
416
600
|
this.streakBadge = null;
|
|
417
601
|
this.levelDisplay = null;
|
|
418
602
|
this.streakDisplay = null;
|
|
603
|
+
this._streakIcon = null;
|
|
419
604
|
}
|
|
420
605
|
}
|
package/src/index.js
CHANGED
|
@@ -18,6 +18,10 @@ export { EventEmitter } from './dopamine/core/EventEmitter.js';
|
|
|
18
18
|
// Storage resolution, useful for tests and for SSR where localStorage is absent.
|
|
19
19
|
export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js';
|
|
20
20
|
|
|
21
|
+
// Feel helpers: vibration and the reduced-motion preference
|
|
22
|
+
export { createHaptics } from './dopamine/feel/haptics.js';
|
|
23
|
+
export { prefersReducedMotion } from './dopamine/feel/motion.js';
|
|
24
|
+
|
|
21
25
|
// Export New Engine Core
|
|
22
26
|
export { Game } from './core/Game.js';
|
|
23
27
|
export { Scene } from './core/Scene.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core subpath export: `import { RewardSystem } from 'dopaminejs/core'`
|
|
3
|
+
*
|
|
4
|
+
* The progression API with no UI, effects, sound or engine behind it, so it
|
|
5
|
+
* loads in React Native, Expo and other runtimes that have no browser. Nothing
|
|
6
|
+
* reachable from here may touch window, document, localStorage or navigator
|
|
7
|
+
* at import time. scripts/check-core-import.js enforces that against the build.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export { RewardSystem } from './dopamine/core/RewardSystem.js';
|
|
11
|
+
export { DataService } from './dopamine/core/DataService.js';
|
|
12
|
+
export { EventEmitter } from './dopamine/core/EventEmitter.js';
|
|
13
|
+
export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js';
|
package/src/systems/Physics.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { deprecatedGlobal } from './deprecate.js';
|
|
2
2
|
|
|
3
3
|
import { Collider } from '../core/Collider.js';
|
|
4
|
+
import { EventBus } from '../core/EventBus.js';
|
|
4
5
|
|
|
5
6
|
export class Physics {
|
|
6
7
|
constructor() {
|
|
7
8
|
this.colliders = [];
|
|
8
9
|
this.kernel = null;
|
|
10
|
+
|
|
11
|
+
// Map<Collider, Map<Collider, step>>: the pairs that overlapped as of
|
|
12
|
+
// the last step, each with the step that last saw it. Without it
|
|
13
|
+
// there is no telling a new overlap from one that is still going.
|
|
14
|
+
this._pairs = new Map();
|
|
15
|
+
this._step = 0;
|
|
9
16
|
}
|
|
10
17
|
|
|
11
18
|
/**
|
|
@@ -27,6 +34,7 @@ export class Physics {
|
|
|
27
34
|
*/
|
|
28
35
|
destroy() {
|
|
29
36
|
this.colliders = [];
|
|
37
|
+
this._pairs.clear();
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
add(collider) {
|
|
@@ -36,13 +44,41 @@ export class Physics {
|
|
|
36
44
|
remove(collider) {
|
|
37
45
|
const idx = this.colliders.indexOf(collider);
|
|
38
46
|
if (idx > -1) this.colliders.splice(idx, 1);
|
|
47
|
+
|
|
48
|
+
// A removed collider overlaps nothing, so its pairs end here. Left
|
|
49
|
+
// in the map they would also keep the collider alive.
|
|
50
|
+
const others = this._pairs.get(collider);
|
|
51
|
+
if (others) {
|
|
52
|
+
this._pairs.delete(collider);
|
|
53
|
+
|
|
54
|
+
// Emptied before emitting: step() may be part way through this
|
|
55
|
+
// map when an exit listener removes the collider, and would end
|
|
56
|
+
// the same pairs again.
|
|
57
|
+
const ended = [...others.keys()];
|
|
58
|
+
others.clear();
|
|
59
|
+
for (const other of ended) {
|
|
60
|
+
this._emit(EventBus.Events.COLLISION_EXIT, collider, other);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const [first, seconds] of this._pairs) {
|
|
64
|
+
if (seconds.delete(collider)) {
|
|
65
|
+
this._emit(EventBus.Events.COLLISION_EXIT, first, collider);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
39
68
|
}
|
|
40
69
|
|
|
41
70
|
/**
|
|
42
71
|
* Main Physics Step.
|
|
43
72
|
* Checks all pairs and triggers callbacks.
|
|
73
|
+
*
|
|
74
|
+
* Emits `collision_enter` on the kernel event bus when a pair starts to
|
|
75
|
+
* overlap and `collision_exit` when it stops, each with `{ a, b }` (the
|
|
76
|
+
* two colliders). `onCollisionEnter` on a component is older and runs on
|
|
77
|
+
* every step while the pair overlaps.
|
|
44
78
|
*/
|
|
45
79
|
step() {
|
|
80
|
+
const step = ++this._step;
|
|
81
|
+
|
|
46
82
|
// Naive O(N^2)
|
|
47
83
|
for (let i = 0; i < this.colliders.length; i++) {
|
|
48
84
|
for (let j = i + 1; j < this.colliders.length; j++) {
|
|
@@ -50,12 +86,65 @@ export class Physics {
|
|
|
50
86
|
const b = this.colliders[j];
|
|
51
87
|
|
|
52
88
|
if (this._intersects(a, a.getBounds(), b, b.getBounds())) {
|
|
89
|
+
this._seen(a, b, step);
|
|
90
|
+
|
|
53
91
|
// Notify GameObjects
|
|
54
92
|
this._notifyCollision(a.gameObject, b.gameObject);
|
|
55
93
|
this._notifyCollision(b.gameObject, a.gameObject);
|
|
56
94
|
}
|
|
57
95
|
}
|
|
58
96
|
}
|
|
97
|
+
|
|
98
|
+
for (const [a, others] of this._pairs) {
|
|
99
|
+
for (const [b, seen] of others) {
|
|
100
|
+
if (seen === step) continue;
|
|
101
|
+
|
|
102
|
+
// A collider removed during the loop above shifts the list,
|
|
103
|
+
// and the loop then passes over some pairs. Not being seen
|
|
104
|
+
// is not enough to end one.
|
|
105
|
+
if (this._intersects(a, a.getBounds(), b, b.getBounds())) {
|
|
106
|
+
others.set(b, step);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
others.delete(b);
|
|
111
|
+
this._emit(EventBus.Events.COLLISION_EXIT, a, b);
|
|
112
|
+
}
|
|
113
|
+
if (others.size === 0) this._pairs.delete(a);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Record that a pair overlaps on this step. Emits `collision_enter` when
|
|
119
|
+
* it did not overlap on the step before.
|
|
120
|
+
* @private
|
|
121
|
+
*/
|
|
122
|
+
_seen(a, b, step) {
|
|
123
|
+
// A pair is stored under the collider that was first in the list
|
|
124
|
+
// when it began. `colliders` is public and can be reordered, so look
|
|
125
|
+
// under the other one too.
|
|
126
|
+
if (this._pairs.get(b)?.has(a)) {
|
|
127
|
+
this._pairs.get(b).set(a, step);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let others = this._pairs.get(a);
|
|
132
|
+
if (!others) {
|
|
133
|
+
others = new Map();
|
|
134
|
+
this._pairs.set(a, others);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const known = others.has(b);
|
|
138
|
+
others.set(b, step);
|
|
139
|
+
if (!known) this._emit(EventBus.Events.COLLISION_ENTER, a, b);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @private
|
|
144
|
+
*/
|
|
145
|
+
_emit(event, a, b) {
|
|
146
|
+
// GlobalPhysics and a Physics built by hand have no kernel.
|
|
147
|
+
this.kernel?.events?.emit(event, { a, b });
|
|
59
148
|
}
|
|
60
149
|
|
|
61
150
|
_notifyCollision(go, other) {
|
package/types/core.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for the `dopaminejs/core` subpath. Only what that entry exports at
|
|
3
|
+
* runtime, plus the types those values use, so importing GameUI or another
|
|
4
|
+
* web-only name from it fails to compile instead of being undefined.
|
|
5
|
+
*/
|
|
6
|
+
export {
|
|
7
|
+
RewardSystem,
|
|
8
|
+
DataService,
|
|
9
|
+
EventEmitter,
|
|
10
|
+
createMemoryStorage,
|
|
11
|
+
resolveStorage
|
|
12
|
+
} from './index';
|
|
13
|
+
|
|
14
|
+
export type {
|
|
15
|
+
Player,
|
|
16
|
+
PlayerStreak,
|
|
17
|
+
UnlockedAchievement,
|
|
18
|
+
AchievementDefinition,
|
|
19
|
+
GameResult,
|
|
20
|
+
XPProgress,
|
|
21
|
+
AddXPResult,
|
|
22
|
+
RewardSystemConfig,
|
|
23
|
+
RewardEvent,
|
|
24
|
+
StorageLike,
|
|
25
|
+
AsyncStorageLike,
|
|
26
|
+
DataServiceConfig
|
|
27
|
+
} from './index';
|
package/types/index.d.ts
CHANGED
|
@@ -38,8 +38,12 @@ export interface Player {
|
|
|
38
38
|
export interface AchievementDefinition {
|
|
39
39
|
name: string;
|
|
40
40
|
description?: string;
|
|
41
|
-
/**
|
|
42
|
-
|
|
41
|
+
/**
|
|
42
|
+
* A string is rendered as HTML (an <img> or inline SVG is allowed), or as
|
|
43
|
+
* allowlisted SVG or text when GameUI is built with `safeIcons: true`. A
|
|
44
|
+
* Node is moved into the popup, not copied.
|
|
45
|
+
*/
|
|
46
|
+
icon?: string | Node;
|
|
43
47
|
/** Omitted means 0. Never undefined at runtime. */
|
|
44
48
|
xp?: number;
|
|
45
49
|
check(player: Player, gameName?: string, result?: GameResult): boolean;
|
|
@@ -81,7 +85,17 @@ export type RewardEvent =
|
|
|
81
85
|
/** Payload `{ current, longest }`. Fires when the day rolls over. */
|
|
82
86
|
| 'streak_updated'
|
|
83
87
|
/** Payload `{ key }`. The storage write failed; state lives in memory only. */
|
|
84
|
-
| 'save_failed'
|
|
88
|
+
| 'save_failed'
|
|
89
|
+
/**
|
|
90
|
+
* Payload `{ key, reason, error?, backedUp? }`. `reason: 'read'`: storage
|
|
91
|
+
* could not be read, so nothing is saved this session (call `init()` again
|
|
92
|
+
* to retry). `reason: 'corrupt'`: the saved value was not JSON; it is kept
|
|
93
|
+
* under `player_corrupt` as a JSON string and a new player starts. If that
|
|
94
|
+
* backup fails, `backedUp` is false and nothing is saved this session.
|
|
95
|
+
* A `load()` override must pass its third argument on, or a failed read
|
|
96
|
+
* looks like an empty one.
|
|
97
|
+
*/
|
|
98
|
+
| 'load_failed';
|
|
85
99
|
|
|
86
100
|
export class EventEmitter {
|
|
87
101
|
on(event: string, callback: (data?: unknown) => void): () => void;
|
|
@@ -97,6 +111,11 @@ export class RewardSystem extends EventEmitter {
|
|
|
97
111
|
achievements: Record<string, AchievementDefinition>;
|
|
98
112
|
/** Kernel bus events are mirrored onto, if one was supplied. */
|
|
99
113
|
events: EventBus | null;
|
|
114
|
+
/**
|
|
115
|
+
* True when the last `init()` could not read the saved player, so nothing
|
|
116
|
+
* is saved until `init()` is called again and the read works.
|
|
117
|
+
*/
|
|
118
|
+
readonly loadFailed: boolean;
|
|
100
119
|
|
|
101
120
|
init(): Promise<Player>;
|
|
102
121
|
save(): Promise<void>;
|
|
@@ -153,7 +172,13 @@ export class DataService {
|
|
|
153
172
|
storage: StorageLike | AsyncStorageLike;
|
|
154
173
|
prefix: string;
|
|
155
174
|
save(key: string, data: unknown): Promise<boolean>;
|
|
156
|
-
|
|
175
|
+
/**
|
|
176
|
+
* Resolves `defaultValue` when the read fails, unless `strict` is set:
|
|
177
|
+
* then a storage error rejects as is, and unparseable data rejects with
|
|
178
|
+
* `code: 'DOPAMINE_CORRUPT'` and the raw string on `raw`. `RewardSystem`
|
|
179
|
+
* relies on this, so an override must pass `options` on.
|
|
180
|
+
*/
|
|
181
|
+
load<T = unknown>(key: string, defaultValue?: T | null, options?: { strict?: boolean }): Promise<T | null>;
|
|
157
182
|
clear(key: string): Promise<void>;
|
|
158
183
|
}
|
|
159
184
|
|
|
@@ -162,6 +187,20 @@ export function createMemoryStorage(): StorageLike;
|
|
|
162
187
|
/** localStorage if present and writable, otherwise an in-memory store. */
|
|
163
188
|
export function resolveStorage(): StorageLike;
|
|
164
189
|
|
|
190
|
+
export interface Haptics {
|
|
191
|
+
/** A 10 ms buzz. */
|
|
192
|
+
tap(): void;
|
|
193
|
+
/** Buzzes 10, 40, 10 ms. */
|
|
194
|
+
double(): void;
|
|
195
|
+
setEnabled(enabled: boolean): void;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Silent where the Vibration API is missing or blocked. */
|
|
199
|
+
export function createHaptics(options?: { nav?: { vibrate?: (pattern: number | number[]) => unknown }; enabled?: boolean }): Haptics;
|
|
200
|
+
|
|
201
|
+
/** The reduced-motion query, or `{ matches: false }` without matchMedia. */
|
|
202
|
+
export function prefersReducedMotion(win?: { matchMedia?: (query: string) => { matches: boolean } }): { matches: boolean };
|
|
203
|
+
|
|
165
204
|
// ---------------------------------------------------------------------------
|
|
166
205
|
// UI
|
|
167
206
|
// ---------------------------------------------------------------------------
|
|
@@ -176,8 +215,35 @@ export interface SummaryData {
|
|
|
176
215
|
onExit?: () => void;
|
|
177
216
|
}
|
|
178
217
|
|
|
218
|
+
export interface GameUIConfig {
|
|
219
|
+
/**
|
|
220
|
+
* When true, a string icon (achievement or streak) is parsed as SVG and
|
|
221
|
+
* rebuilt from an allowlist of elements and attributes, and any other
|
|
222
|
+
* string is shown as text. The string must be well-formed XML, so
|
|
223
|
+
* ` ` falls back to text. An `<svg>` with no xmlns is accepted.
|
|
224
|
+
* Default false: string icons are HTML.
|
|
225
|
+
*/
|
|
226
|
+
safeIcons?: boolean;
|
|
227
|
+
/** Replaces the built-in popup strings. Rendered as text. */
|
|
228
|
+
text?: {
|
|
229
|
+
/** Default `LEVEL UP!`. */
|
|
230
|
+
levelUp?: string;
|
|
231
|
+
/** Default `Achievement Unlocked!`. */
|
|
232
|
+
achievementUnlocked?: string;
|
|
233
|
+
/** Default `CLOSE CALL!`. */
|
|
234
|
+
nearMiss?: string;
|
|
235
|
+
};
|
|
236
|
+
icons?: {
|
|
237
|
+
/**
|
|
238
|
+
* A string is HTML (unless `safeIcons` is on), a Node is moved into
|
|
239
|
+
* the badge, not copied. Default is a fire emoji.
|
|
240
|
+
*/
|
|
241
|
+
streak?: string | Node;
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
179
245
|
export class GameUI {
|
|
180
|
-
constructor(particleSystem: ParticleSystem);
|
|
246
|
+
constructor(particleSystem: ParticleSystem, config?: GameUIConfig);
|
|
181
247
|
|
|
182
248
|
container: HTMLElement | null;
|
|
183
249
|
|
|
@@ -279,11 +345,14 @@ export class SoundManager {
|
|
|
279
345
|
|
|
280
346
|
/** Returns false when no Web Audio API is available, rather than throwing. */
|
|
281
347
|
initAudio(): boolean;
|
|
348
|
+
/** Calls initAudio() on the first of `events` on `target`, then removes its listeners. Returns a remover. */
|
|
349
|
+
unlockOn(target: EventTarget, events?: string[]): () => void;
|
|
282
350
|
setVolume(value: number): number;
|
|
283
351
|
getVolume(): number;
|
|
284
352
|
toggleMute(): boolean;
|
|
285
353
|
|
|
286
354
|
registerSound(key: string, url: string): void;
|
|
355
|
+
/** Registers every key, then loads the files. Before the audio context exists they load when it is created. */
|
|
287
356
|
preloadSounds(soundMap: Record<string, string>): Promise<void>;
|
|
288
357
|
loadSound(key: string, url: string): Promise<void>;
|
|
289
358
|
play(key: string): Promise<void>;
|
|
@@ -372,6 +441,7 @@ export class PluginRegistry {
|
|
|
372
441
|
constructor(kernel: DopamineKernel);
|
|
373
442
|
use(plugin: Plugin): this;
|
|
374
443
|
useAsync(plugin: Plugin): Promise<this>;
|
|
444
|
+
/** Calls the plugin's `destroy()`, then unregisters the systems it registered during `init()`. */
|
|
375
445
|
remove(name: string): boolean;
|
|
376
446
|
get(name: string): Plugin | undefined;
|
|
377
447
|
has(name: string): boolean;
|
|
@@ -535,12 +605,24 @@ export class Input {
|
|
|
535
605
|
mouse: { x: number; y: number };
|
|
536
606
|
}
|
|
537
607
|
|
|
608
|
+
/** Payload of `collision_enter` and `collision_exit` on the kernel event bus. */
|
|
609
|
+
export interface CollisionEvent {
|
|
610
|
+
a: Collider;
|
|
611
|
+
b: Collider;
|
|
612
|
+
}
|
|
613
|
+
|
|
538
614
|
export class Physics {
|
|
539
615
|
init(kernel: DopamineKernel): void;
|
|
540
616
|
fixedUpdate(dt: number): void;
|
|
541
617
|
destroy(): void;
|
|
542
618
|
add(collider: Collider): void;
|
|
619
|
+
/** Emits `collision_exit` for each pair the collider was overlapping in. */
|
|
543
620
|
remove(collider: Collider): void;
|
|
621
|
+
/**
|
|
622
|
+
* Emits `collision_enter` once when a pair starts to overlap and
|
|
623
|
+
* `collision_exit` once when it stops. `onCollisionEnter` on a component
|
|
624
|
+
* runs on every step while the pair overlaps.
|
|
625
|
+
*/
|
|
544
626
|
step(): void;
|
|
545
627
|
/** Every collider that overlaps `source`. With a tag, only colliders carrying it. */
|
|
546
628
|
checkOverlap(source: Collider, targetTag?: string): Collider[];
|