dopaminejs 2.4.0 → 3.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/README.md +40 -50
- package/dist/DataService-E4pGQ1V3.cjs +1 -0
- package/dist/DataService-MfmvkqXR.js +737 -0
- package/dist/core.cjs +1 -0
- package/dist/core.js +2 -0
- package/dist/dopamine.cjs +1 -37
- package/dist/dopamine.js +3 -858
- package/dist/games.cjs +1 -0
- package/dist/games.js +82 -0
- package/dist/host-CkRL74ck.js +814 -0
- package/dist/host-Pzb-QBPU.cjs +37 -0
- package/dist/style.css +395 -2
- package/dist/testing.cjs +1 -0
- package/dist/testing.js +474 -0
- package/package.json +28 -8
- package/spec/README.md +227 -0
- package/spec/VERSION +1 -0
- package/spec/fixtures/achievements.json +611 -0
- package/spec/fixtures/levels.json +421 -0
- package/spec/fixtures/merge.json +1739 -0
- package/spec/fixtures/migrate.json +916 -0
- package/spec/fixtures/scores.json +755 -0
- package/spec/fixtures/streaks.json +924 -0
- package/spec/schema.json +61 -0
- package/src/dopamine/audio/SoundManager.js +78 -24
- package/src/dopamine/core/DataService.js +25 -5
- package/src/dopamine/core/DopamineError.js +7 -0
- package/src/dopamine/core/RewardSystem.js +366 -368
- package/src/dopamine/core/achievements.js +49 -0
- package/src/dopamine/core/clock.js +11 -0
- package/src/dopamine/core/levels.js +4 -0
- package/src/dopamine/core/merge.js +68 -0
- package/src/dopamine/core/middleware.js +58 -0
- package/src/dopamine/core/store.js +261 -0
- package/src/dopamine/core/streaks.js +55 -0
- package/src/dopamine/effects/ParticleSystem.js +33 -3
- package/src/dopamine/feel/haptics.js +21 -0
- package/src/dopamine/feel/motion.js +9 -0
- package/src/dopamine/host.js +358 -0
- package/src/dopamine/ui/RewardUI.js +569 -0
- package/src/games.js +138 -0
- package/src/index.js +14 -33
- package/src/progression.js +16 -0
- package/src/testing.js +489 -0
- package/types/core.d.ts +35 -0
- package/types/games.d.ts +46 -0
- package/types/index.d.ts +348 -373
- package/types/testing.d.ts +96 -0
- package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
- package/dist/ScreenShake-CLvO1wx4.js +0 -827
- package/dist/engine.cjs +0 -1
- package/dist/engine.js +0 -2
- package/src/core/Animator.js +0 -62
- package/src/core/Collider.js +0 -86
- package/src/core/Component.js +0 -38
- package/src/core/DopamineKernel.js +0 -170
- package/src/core/EventBus.js +0 -206
- package/src/core/Game.js +0 -90
- package/src/core/GameObject.js +0 -99
- package/src/core/PluginRegistry.js +0 -359
- package/src/core/Scene.js +0 -107
- package/src/core/Sprite.js +0 -51
- package/src/core/SystemRegistry.js +0 -263
- package/src/core/Vector2.js +0 -50
- package/src/dopamine/components/ParticleEmitter.js +0 -50
- package/src/dopamine/components/ScreenShake.js +0 -50
- package/src/dopamine/components/index.js +0 -2
- package/src/dopamine/index.js +0 -93
- package/src/dopamine/ui/GameUI.js +0 -420
- package/src/dopamine/utils/TextureGenerator.js +0 -90
- package/src/engine.js +0 -38
- package/src/interfaces/IAudioSystem.js +0 -58
- package/src/interfaces/IParticleSystem.js +0 -51
- package/src/interfaces/IPhysicsSystem.js +0 -52
- package/src/interfaces/ISystem.js +0 -48
- package/src/interfaces/index.js +0 -7
- package/src/renderer/Renderer.js +0 -45
- package/src/systems/Director.js +0 -34
- package/src/systems/Input.js +0 -81
- package/src/systems/Loader.js +0 -48
- package/src/systems/Physics.js +0 -210
- package/src/systems/Ticker.js +0 -91
- package/src/systems/deprecate.js +0 -38
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export const builtinAchievements = () => ({
|
|
2
|
+
first_game: {
|
|
3
|
+
name: 'First Steps',
|
|
4
|
+
description: 'Play your first game',
|
|
5
|
+
icon: '\u{1F3AE}',
|
|
6
|
+
xp: 50,
|
|
7
|
+
check: (player) => player.totalGamesPlayed >= 1
|
|
8
|
+
},
|
|
9
|
+
level_5: {
|
|
10
|
+
name: 'Rising Star',
|
|
11
|
+
description: 'Reach level 5',
|
|
12
|
+
icon: '\u{2B50}',
|
|
13
|
+
xp: 100,
|
|
14
|
+
check: (player) => player.level >= 5
|
|
15
|
+
},
|
|
16
|
+
level_10: {
|
|
17
|
+
name: 'Expert Player',
|
|
18
|
+
description: 'Reach level 10',
|
|
19
|
+
icon: '\u{1F3C6}',
|
|
20
|
+
xp: 250,
|
|
21
|
+
check: (player) => player.level >= 10
|
|
22
|
+
},
|
|
23
|
+
streak_3: {
|
|
24
|
+
name: 'Dedicated',
|
|
25
|
+
description: 'Play 3 days in a row',
|
|
26
|
+
icon: '\u{1F525}',
|
|
27
|
+
xp: 100,
|
|
28
|
+
check: (player) => player.streak.current >= 3
|
|
29
|
+
},
|
|
30
|
+
streak_7: {
|
|
31
|
+
name: 'Unstoppable',
|
|
32
|
+
description: 'Play 7 days in a row',
|
|
33
|
+
icon: '\u{1F4A5}',
|
|
34
|
+
xp: 300,
|
|
35
|
+
check: (player) => player.streak.current >= 7
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// Reward XP of the built-ins, used to read a 2.x document when the caller
|
|
40
|
+
// has no definitions of its own.
|
|
41
|
+
export const BUILTIN_REWARDS = { first_game: 50, level_5: 100, level_10: 250, streak_3: 100, streak_7: 300 };
|
|
42
|
+
|
|
43
|
+
export const rewardsOf = (achievements) => {
|
|
44
|
+
const rewards = {};
|
|
45
|
+
for (const id of Object.keys(achievements)) {
|
|
46
|
+
rewards[id] = Number.isFinite(achievements[id]?.xp) && achievements[id].xp > 0 ? achievements[id].xp : 0;
|
|
47
|
+
}
|
|
48
|
+
return rewards;
|
|
49
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const pad = (value, width = 2) => String(value).padStart(width, '0');
|
|
2
|
+
|
|
3
|
+
// The only place that reads the system time. localDate is the local calendar
|
|
4
|
+
// day, never UTC.
|
|
5
|
+
export const systemClock = {
|
|
6
|
+
now: () => Date.now(),
|
|
7
|
+
localDate(ms = Date.now()) {
|
|
8
|
+
const date = new Date(ms);
|
|
9
|
+
return `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { validate, checkDevices, hasOwn, VERSION } from './store.js';
|
|
2
|
+
import { isDay, trimDays } from './streaks.js';
|
|
3
|
+
|
|
4
|
+
// Join two maps that are `depth` levels deep, taking the larger number at the
|
|
5
|
+
// leaves. Max per key is what makes the join order independent.
|
|
6
|
+
function join(a, b, depth) {
|
|
7
|
+
const out = {};
|
|
8
|
+
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
|
9
|
+
const x = hasOwn(a, key) ? a[key] : undefined;
|
|
10
|
+
const y = hasOwn(b, key) ? b[key] : undefined;
|
|
11
|
+
if (depth > 0) out[key] = join(x || {}, y || {}, depth - 1);
|
|
12
|
+
else out[key] = x === undefined ? y : y === undefined ? x : Math.max(x, y);
|
|
13
|
+
}
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function joinAchievements(a, b) {
|
|
18
|
+
const out = {};
|
|
19
|
+
for (const id of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
|
20
|
+
const x = hasOwn(a, id) ? a[id] : undefined;
|
|
21
|
+
const y = hasOwn(b, id) ? b[id] : undefined;
|
|
22
|
+
if (!x || !y) {
|
|
23
|
+
out[id] = { ...(x || y) };
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
// The earliest unlock decides the reward; a tie takes the larger.
|
|
27
|
+
const first = x.unlockedAt < y.unlockedAt || (x.unlockedAt === y.unlockedAt && x.reward >= y.reward) ? x : y;
|
|
28
|
+
out[id] = { unlockedAt: first.unlockedAt, seen: x.seen || y.seen, reward: first.reward };
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const positive = (a, b) => (a > 0 && b > 0 ? Math.min(a, b) : Math.max(a, b));
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Join two saves. Pure: it reads no clock and no storage, and the result does
|
|
37
|
+
* not depend on argument order or grouping, or on merging twice.
|
|
38
|
+
* Throws a DopamineError when either input is invalid or the result would
|
|
39
|
+
* hold more than 20 devices.
|
|
40
|
+
*
|
|
41
|
+
* @param {*} a
|
|
42
|
+
* @param {*} b
|
|
43
|
+
* @param {{ today?: string, rewards?: Object }} [options] see validate
|
|
44
|
+
*/
|
|
45
|
+
export function merge(a, b, options) {
|
|
46
|
+
const x = validate(a, options);
|
|
47
|
+
const y = validate(b, options);
|
|
48
|
+
const later = x.lastPlayedAt !== y.lastPlayedAt ? (x.lastPlayedAt > y.lastPlayedAt ? x : y) : (x.name >= y.name ? x : y);
|
|
49
|
+
|
|
50
|
+
const doc = {
|
|
51
|
+
v: VERSION,
|
|
52
|
+
name: later.name,
|
|
53
|
+
createdAt: positive(x.createdAt, y.createdAt),
|
|
54
|
+
lastPlayedAt: Math.max(x.lastPlayedAt, y.lastPlayedAt),
|
|
55
|
+
level: Math.max(x.level, y.level),
|
|
56
|
+
longest: Math.max(x.longest, y.longest),
|
|
57
|
+
playDates: trimDays([...x.playDates, ...y.playDates], isDay(options?.today) ? options.today : undefined),
|
|
58
|
+
xpBy: join(x.xpBy, y.xpBy, 0),
|
|
59
|
+
xpSpentBy: join(x.xpSpentBy, y.xpSpentBy, 0),
|
|
60
|
+
gamesBy: join(x.gamesBy, y.gamesBy, 0),
|
|
61
|
+
playsBy: join(x.playsBy, y.playsBy, 1),
|
|
62
|
+
best: join(x.best, y.best, 0),
|
|
63
|
+
sumsBy: join(x.sumsBy, y.sumsBy, 2),
|
|
64
|
+
achievements: joinAchievements(x.achievements, y.achievements)
|
|
65
|
+
};
|
|
66
|
+
checkDevices(doc);
|
|
67
|
+
return doc;
|
|
68
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { isRecord } from './store.js';
|
|
2
|
+
|
|
3
|
+
const PHASES = ['beforeXP', 'afterXP', 'beforeRecord', 'afterRecord', 'beforeUnlock', 'afterUnlock'];
|
|
4
|
+
|
|
5
|
+
export class Middleware {
|
|
6
|
+
constructor() {
|
|
7
|
+
this._list = [];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
use(middleware) {
|
|
11
|
+
if (!isRecord(middleware) || !PHASES.some((phase) => typeof middleware[phase] === 'function')) {
|
|
12
|
+
throw new TypeError(`[DopamineJS] use expects an object with one of: ${PHASES.join(', ')}`);
|
|
13
|
+
}
|
|
14
|
+
this._list.push(middleware);
|
|
15
|
+
return () => {
|
|
16
|
+
const at = this._list.indexOf(middleware);
|
|
17
|
+
if (at >= 0) this._list.splice(at, 1);
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Run a before hook in `use` order. A hook may return a patch (merged
|
|
23
|
+
* over the context, only for keys the context has), false to reject, or
|
|
24
|
+
* nothing. A throwing hook is logged and skipped.
|
|
25
|
+
* @returns {Promise<Object|false>} the context after patches, or false
|
|
26
|
+
*/
|
|
27
|
+
async before(phase, context, accept = () => true) {
|
|
28
|
+
for (const middleware of [...this._list]) {
|
|
29
|
+
if (typeof middleware[phase] !== 'function') continue;
|
|
30
|
+
let result;
|
|
31
|
+
try {
|
|
32
|
+
result = await middleware[phase](Object.freeze({ ...context }));
|
|
33
|
+
} catch (error) {
|
|
34
|
+
console.error(`[DopamineJS] ${phase} hook threw:`, error);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (result === false) return false;
|
|
38
|
+
if (!isRecord(result)) continue;
|
|
39
|
+
const next = { ...context };
|
|
40
|
+
for (const key of Object.keys(context)) {
|
|
41
|
+
if (Object.prototype.hasOwnProperty.call(result, key)) next[key] = result[key];
|
|
42
|
+
}
|
|
43
|
+
if (accept(next)) context = next;
|
|
44
|
+
}
|
|
45
|
+
return context;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async after(phase, context) {
|
|
49
|
+
for (const middleware of [...this._list]) {
|
|
50
|
+
if (typeof middleware[phase] !== 'function') continue;
|
|
51
|
+
try {
|
|
52
|
+
await middleware[phase](Object.freeze({ ...context }));
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.error(`[DopamineJS] ${phase} hook threw:`, error);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { DopamineError } from './DopamineError.js';
|
|
2
|
+
import { BUILTIN_REWARDS } from './achievements.js';
|
|
3
|
+
import { levelFor } from './levels.js';
|
|
4
|
+
import { isDay, shiftDay, trimDays, currentStreak, longestRun, lastDayUntil } from './streaks.js';
|
|
5
|
+
|
|
6
|
+
export const VERSION = 3;
|
|
7
|
+
export const MAX_DEVICES = 20;
|
|
8
|
+
export const LEGACY = 'legacy';
|
|
9
|
+
|
|
10
|
+
// Keys that resolve to something on Object.prototype. Game names, achievement
|
|
11
|
+
// ids and device ids index plain objects, so these are never used as one.
|
|
12
|
+
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
13
|
+
|
|
14
|
+
export const isSafeKey = (key) => typeof key === 'string' && key.length > 0 && !UNSAFE_KEYS.has(key);
|
|
15
|
+
export const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
16
|
+
export const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
|
+
|
|
18
|
+
const isCount = (value) => Number.isInteger(value) && value >= 0;
|
|
19
|
+
const isAmount = (value) => Number.isFinite(value) && value >= 0;
|
|
20
|
+
const isNumber = (value) => Number.isFinite(value);
|
|
21
|
+
export const cap = (value) => Math.min(value, Number.MAX_SAFE_INTEGER);
|
|
22
|
+
const count = (value, fallback, min = 0) => (Number.isInteger(value) && value >= min ? cap(value) : fallback);
|
|
23
|
+
|
|
24
|
+
// Summed in key order, so the same document always gives the same float.
|
|
25
|
+
export const sum = (map, pick = (value) => value) => Object.keys(map).sort().reduce((total, key) => cap(total + pick(map[key])), 0);
|
|
26
|
+
|
|
27
|
+
export const emptyDoc = (now = 0) => ({
|
|
28
|
+
v: VERSION,
|
|
29
|
+
name: 'Player',
|
|
30
|
+
createdAt: now,
|
|
31
|
+
lastPlayedAt: now,
|
|
32
|
+
level: 1,
|
|
33
|
+
longest: 0,
|
|
34
|
+
playDates: [],
|
|
35
|
+
xpBy: {},
|
|
36
|
+
xpSpentBy: {},
|
|
37
|
+
gamesBy: {},
|
|
38
|
+
playsBy: {},
|
|
39
|
+
best: {},
|
|
40
|
+
sumsBy: {},
|
|
41
|
+
achievements: {}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function pickMap(source, accept) {
|
|
45
|
+
const map = {};
|
|
46
|
+
if (!isRecord(source)) return map;
|
|
47
|
+
for (const key of Object.keys(source)) {
|
|
48
|
+
if (isSafeKey(key) && accept(source[key])) map[key] = cap(source[key]);
|
|
49
|
+
}
|
|
50
|
+
return map;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function pickNested(source, accept) {
|
|
54
|
+
const map = {};
|
|
55
|
+
if (!isRecord(source)) return map;
|
|
56
|
+
for (const key of Object.keys(source)) {
|
|
57
|
+
if (isSafeKey(key)) map[key] = pickMap(source[key], accept);
|
|
58
|
+
}
|
|
59
|
+
return map;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function pickAchievements(source, now) {
|
|
63
|
+
const map = {};
|
|
64
|
+
if (!isRecord(source)) return map;
|
|
65
|
+
for (const id of Object.keys(source)) {
|
|
66
|
+
const entry = source[id];
|
|
67
|
+
if (!isSafeKey(id) || !isRecord(entry)) continue;
|
|
68
|
+
map[id] = {
|
|
69
|
+
unlockedAt: isNumber(entry.unlockedAt) ? entry.unlockedAt : now,
|
|
70
|
+
seen: entry.seen === true,
|
|
71
|
+
reward: isAmount(entry.reward) ? cap(entry.reward) : 0
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return map;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Every activity has a play map, a best and a sum map, so merge never has to
|
|
78
|
+
// ask whether one exists.
|
|
79
|
+
function finish(doc) {
|
|
80
|
+
const sums = doc.sumsBy;
|
|
81
|
+
const activities = new Set([...Object.keys(doc.playsBy), ...Object.keys(doc.best), ...Object.keys(sums)]);
|
|
82
|
+
for (const activity of activities) {
|
|
83
|
+
if (!hasOwn(doc.playsBy, activity)) doc.playsBy[activity] = {};
|
|
84
|
+
if (!hasOwn(doc.best, activity)) doc.best[activity] = 0;
|
|
85
|
+
if (!hasOwn(sums, activity)) sums[activity] = {};
|
|
86
|
+
}
|
|
87
|
+
return doc;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function read3(input, now, today) {
|
|
91
|
+
return finish({
|
|
92
|
+
v: VERSION,
|
|
93
|
+
name: typeof input.name === 'string' ? input.name : 'Player',
|
|
94
|
+
createdAt: isNumber(input.createdAt) ? input.createdAt : now,
|
|
95
|
+
lastPlayedAt: isNumber(input.lastPlayedAt) ? input.lastPlayedAt : now,
|
|
96
|
+
level: count(input.level, 1, 1),
|
|
97
|
+
longest: count(input.longest, 0),
|
|
98
|
+
playDates: trimDays(Array.isArray(input.playDates) ? input.playDates.filter(isDay) : [], today),
|
|
99
|
+
xpBy: pickMap(input.xpBy, isAmount),
|
|
100
|
+
xpSpentBy: pickMap(input.xpSpentBy, isAmount),
|
|
101
|
+
gamesBy: pickMap(input.gamesBy, isCount),
|
|
102
|
+
playsBy: pickNested(input.playsBy, isCount),
|
|
103
|
+
best: pickMap(input.best, isAmount),
|
|
104
|
+
sumsBy: nestedSums(input.sumsBy),
|
|
105
|
+
achievements: pickAchievements(input.achievements, now)
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function nestedSums(source) {
|
|
110
|
+
const map = {};
|
|
111
|
+
if (!isRecord(source)) return map;
|
|
112
|
+
for (const activity of Object.keys(source)) {
|
|
113
|
+
if (isSafeKey(activity)) map[activity] = pickNested(source[activity], isNumber);
|
|
114
|
+
}
|
|
115
|
+
return map;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// A 2.x document, moved under the fixed legacy key. Two devices that read the
|
|
119
|
+
// same save get the same entries, so they merge by max and nothing doubles.
|
|
120
|
+
function read2(input, now, rewards, today) {
|
|
121
|
+
const doc = emptyDoc(now);
|
|
122
|
+
doc.name = typeof input.name === 'string' ? input.name : 'Player';
|
|
123
|
+
doc.createdAt = isNumber(input.createdAt) ? input.createdAt : now;
|
|
124
|
+
doc.lastPlayedAt = isNumber(input.lastPlayedAt) ? input.lastPlayedAt : now;
|
|
125
|
+
doc.achievements = pickAchievements(input.achievements, now);
|
|
126
|
+
|
|
127
|
+
let granted = 0;
|
|
128
|
+
for (const id of Object.keys(doc.achievements)) {
|
|
129
|
+
const reward = hasOwn(rewards, id) && isAmount(rewards[id]) ? cap(rewards[id]) : 0;
|
|
130
|
+
doc.achievements[id].reward = reward;
|
|
131
|
+
granted += reward;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// The old xp already holds the rewards of the unlocked achievements.
|
|
135
|
+
const xp = isAmount(input.xp) ? cap(input.xp) : 0;
|
|
136
|
+
const own = Math.max(0, xp - granted);
|
|
137
|
+
if (own > 0) doc.xpBy[LEGACY] = own;
|
|
138
|
+
doc.level = Math.max(levelFor(xp), count(input.level, 1, 1));
|
|
139
|
+
const games = count(input.totalGamesPlayed, 0);
|
|
140
|
+
if (games > 0) doc.gamesBy[LEGACY] = games;
|
|
141
|
+
|
|
142
|
+
if (isRecord(input.stats)) {
|
|
143
|
+
for (const activity of Object.keys(input.stats)) {
|
|
144
|
+
const entry = input.stats[activity];
|
|
145
|
+
if (!isSafeKey(activity) || !isRecord(entry)) continue;
|
|
146
|
+
const plays = count(entry.totalPlays, 0);
|
|
147
|
+
doc.playsBy[activity] = plays > 0 ? { [LEGACY]: plays } : {};
|
|
148
|
+
doc.best[activity] = isAmount(entry.highScore) ? cap(entry.highScore) : 0;
|
|
149
|
+
doc.sumsBy[activity] = {};
|
|
150
|
+
for (const key of Object.keys(entry)) {
|
|
151
|
+
if (isSafeKey(key) && key !== 'totalPlays' && key !== 'highScore' && isNumber(entry[key])) {
|
|
152
|
+
doc.sumsBy[activity][key] = { [LEGACY]: cap(entry[key]) };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const streak = isRecord(input.streak) ? input.streak : {};
|
|
159
|
+
const current = count(streak.current, 1, 1);
|
|
160
|
+
doc.longest = Math.max(current, count(streak.longest, 0));
|
|
161
|
+
if (isDay(streak.lastPlayDate)) {
|
|
162
|
+
for (let back = 0; back < Math.min(current, 400); back++) doc.playDates.push(shiftDay(streak.lastPlayDate, -back));
|
|
163
|
+
doc.playDates = trimDays(doc.playDates, today);
|
|
164
|
+
} else {
|
|
165
|
+
doc.longest = count(streak.longest, 0);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return finish(doc);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function deviceIds(doc) {
|
|
172
|
+
const ids = new Set([...Object.keys(doc.xpBy), ...Object.keys(doc.xpSpentBy), ...Object.keys(doc.gamesBy)]);
|
|
173
|
+
for (const activity of Object.keys(doc.playsBy)) {
|
|
174
|
+
for (const id of Object.keys(doc.playsBy[activity])) ids.add(id);
|
|
175
|
+
}
|
|
176
|
+
for (const activity of Object.keys(doc.sumsBy)) {
|
|
177
|
+
for (const key of Object.keys(doc.sumsBy[activity])) {
|
|
178
|
+
for (const id of Object.keys(doc.sumsBy[activity][key])) ids.add(id);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return ids;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function checkDevices(doc) {
|
|
185
|
+
if (deviceIds(doc).size > MAX_DEVICES) {
|
|
186
|
+
throw new DopamineError('too_many_devices', `[DopamineJS] a save holds at most ${MAX_DEVICES} devices`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Clean any value into a version 3 document, or throw a DopamineError.
|
|
192
|
+
* Pure: no clock, no storage. A 2.x document (no `v`) is migrated.
|
|
193
|
+
*
|
|
194
|
+
* @param {*} input
|
|
195
|
+
* @param {{ now?: number, today?: string, rewards?: Object }} [options] `now` fills missing
|
|
196
|
+
* timestamps, `today` (a local date) sets the 400 day window for play dates, `rewards` maps achievement ids to the XP a 2.x save already
|
|
197
|
+
* holds for them.
|
|
198
|
+
*/
|
|
199
|
+
export function validate(input, options = {}) {
|
|
200
|
+
if (!isRecord(input)) {
|
|
201
|
+
throw new DopamineError('invalid_document', '[DopamineJS] a save must be an object');
|
|
202
|
+
}
|
|
203
|
+
if (input.v !== undefined && input.v !== VERSION) {
|
|
204
|
+
throw new DopamineError('unsupported_version', `[DopamineJS] save version ${String(input.v)} is not ${VERSION}`);
|
|
205
|
+
}
|
|
206
|
+
const now = isNumber(options.now) ? options.now : 0;
|
|
207
|
+
const today = isDay(options.today) ? options.today : undefined;
|
|
208
|
+
const doc = input.v === VERSION
|
|
209
|
+
? read3(input, now, today)
|
|
210
|
+
: read2(input, now, isRecord(options.rewards) ? options.rewards : BUILTIN_REWARDS, today);
|
|
211
|
+
checkDevices(doc);
|
|
212
|
+
return doc;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export const xpOf = (doc) => cap(Math.max(0, sum(doc.xpBy) + sum(doc.achievements, (entry) => entry.reward) - sum(doc.xpSpentBy)));
|
|
216
|
+
|
|
217
|
+
export const levelOf = (doc) => Math.max(doc.level, levelFor(xpOf(doc)));
|
|
218
|
+
|
|
219
|
+
/** The derived view of a document as of `today`. Not frozen. */
|
|
220
|
+
export function view(doc, today) {
|
|
221
|
+
const stats = {};
|
|
222
|
+
for (const activity of Object.keys(doc.playsBy)) {
|
|
223
|
+
const entry = { plays: sum(doc.playsBy[activity]), best: doc.best[activity] };
|
|
224
|
+
for (const key of Object.keys(doc.sumsBy[activity])) {
|
|
225
|
+
if (key !== 'plays' && key !== 'best') entry[key] = sum(doc.sumsBy[activity][key]);
|
|
226
|
+
}
|
|
227
|
+
stats[activity] = entry;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const achievements = {};
|
|
231
|
+
for (const id of Object.keys(doc.achievements)) achievements[id] = { ...doc.achievements[id] };
|
|
232
|
+
|
|
233
|
+
const streak = {
|
|
234
|
+
current: currentStreak(doc.playDates, today),
|
|
235
|
+
longest: Math.max(doc.longest, longestRun(doc.playDates))
|
|
236
|
+
};
|
|
237
|
+
const last = lastDayUntil(doc.playDates, today);
|
|
238
|
+
if (last) streak.lastPlayDate = last;
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
name: doc.name,
|
|
242
|
+
xp: xpOf(doc),
|
|
243
|
+
level: levelOf(doc),
|
|
244
|
+
totalGamesPlayed: sum(doc.gamesBy),
|
|
245
|
+
createdAt: doc.createdAt,
|
|
246
|
+
lastPlayedAt: doc.lastPlayedAt,
|
|
247
|
+
streak,
|
|
248
|
+
achievements,
|
|
249
|
+
stats
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export const clone = (value) => JSON.parse(JSON.stringify(value));
|
|
254
|
+
|
|
255
|
+
export function freeze(value) {
|
|
256
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
257
|
+
Object.freeze(value);
|
|
258
|
+
for (const key of Object.keys(value)) freeze(value[key]);
|
|
259
|
+
}
|
|
260
|
+
return value;
|
|
261
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const DAY = 864e5;
|
|
2
|
+
const SHAPE = /^\d{4}-\d{2}-\d{2}$/;
|
|
3
|
+
|
|
4
|
+
// Calendar days are plain integers, so no clock zone or daylight saving
|
|
5
|
+
// change can move them.
|
|
6
|
+
const dayNum = (text) => {
|
|
7
|
+
const date = new Date(0);
|
|
8
|
+
date.setUTCFullYear(+text.slice(0, 4), +text.slice(5, 7) - 1, +text.slice(8));
|
|
9
|
+
return date.getTime() / DAY;
|
|
10
|
+
};
|
|
11
|
+
const dayText = (num) => new Date(num * DAY).toISOString().slice(0, 10);
|
|
12
|
+
|
|
13
|
+
export const isDay = (text) => typeof text === 'string' && SHAPE.test(text) && dayText(dayNum(text)) === text;
|
|
14
|
+
|
|
15
|
+
export const shiftDay = (text, days) => dayText(dayNum(text) + days);
|
|
16
|
+
|
|
17
|
+
// Sorted and unique. With `today`, nothing older than 400 days counting today
|
|
18
|
+
// goes, and nothing more than a day ahead (a zone can put the player a day past
|
|
19
|
+
// the clock). The window comes from today, never from the newest entry, so a date in
|
|
20
|
+
// the future cannot push real history out. Without `today` nothing is dropped.
|
|
21
|
+
export function trimDays(days, today) {
|
|
22
|
+
const sorted = [...new Set(days)].sort();
|
|
23
|
+
if (!today) return sorted;
|
|
24
|
+
const floor = dayNum(today) - 399;
|
|
25
|
+
const ceiling = dayNum(today) + 1;
|
|
26
|
+
return sorted.filter((day) => dayNum(day) >= floor && dayNum(day) <= ceiling);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Run of consecutive days ending today, or ending yesterday when today has
|
|
30
|
+
// no play yet. Days after today are ignored.
|
|
31
|
+
export function currentStreak(days, today) {
|
|
32
|
+
const set = new Set(days);
|
|
33
|
+
let at = set.has(today) ? today : shiftDay(today, -1);
|
|
34
|
+
let count = 0;
|
|
35
|
+
while (set.has(at)) {
|
|
36
|
+
count++;
|
|
37
|
+
at = shiftDay(at, -1);
|
|
38
|
+
}
|
|
39
|
+
return count;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function longestRun(days) {
|
|
43
|
+
let best = 0;
|
|
44
|
+
let run = 0;
|
|
45
|
+
let previous = NaN;
|
|
46
|
+
for (const day of [...days].sort()) {
|
|
47
|
+
const num = dayNum(day);
|
|
48
|
+
run = num === previous + 1 ? run + 1 : 1;
|
|
49
|
+
previous = num;
|
|
50
|
+
if (run > best) best = run;
|
|
51
|
+
}
|
|
52
|
+
return best;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const lastDayUntil = (days, today) => days.reduce((last, day) => (day <= today && (!last || day > last) ? day : last), undefined);
|
|
@@ -3,6 +3,18 @@
|
|
|
3
3
|
* Creates satisfying visual feedback for achievements and rewards
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { prefersReducedMotion } from '../feel/motion.js';
|
|
7
|
+
|
|
8
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
9
|
+
|
|
10
|
+
const BURSTS = {
|
|
11
|
+
confetti: (ps, x, y, count) => ps.confetti(x, y, count),
|
|
12
|
+
sparkle: (ps, x, y, count, color) => ps.sparkle(x, y, count, color),
|
|
13
|
+
fire: (ps, x, y, count) => ps.fire(x, y, count),
|
|
14
|
+
stars: (ps, x, y, count) => ps.starBurst(x, y, count),
|
|
15
|
+
coins: (ps, x, y, count) => ps.coinShower(x, y, count)
|
|
16
|
+
};
|
|
17
|
+
|
|
6
18
|
export class ParticleSystem {
|
|
7
19
|
constructor(config = {}) {
|
|
8
20
|
this.container = config.container ?
|
|
@@ -19,9 +31,7 @@ export class ParticleSystem {
|
|
|
19
31
|
this.maxParticles = Number.isFinite(config.maxParticles) ? Math.max(0, Math.floor(config.maxParticles)) : 5000;
|
|
20
32
|
|
|
21
33
|
// Effects are skipped for users who asked the OS for less motion.
|
|
22
|
-
this._reducedMotion = config.respectReducedMotion !== false
|
|
23
|
-
? window.matchMedia('(prefers-reduced-motion: reduce)')
|
|
24
|
-
: null;
|
|
34
|
+
this._reducedMotion = config.respectReducedMotion !== false ? prefersReducedMotion(window) : null;
|
|
25
35
|
|
|
26
36
|
this.canvasId = config.canvasId || 'dopamine-particle-canvas';
|
|
27
37
|
|
|
@@ -124,6 +134,11 @@ export class ParticleSystem {
|
|
|
124
134
|
* Play a registered effect
|
|
125
135
|
*/
|
|
126
136
|
play(name, x, y, ...args) {
|
|
137
|
+
// play(name, { x, y }) is the part contract; play(name, x, y) still works.
|
|
138
|
+
if (x !== null && typeof x === 'object') {
|
|
139
|
+
args = y === undefined ? [] : [y, ...args];
|
|
140
|
+
({ x, y } = x);
|
|
141
|
+
}
|
|
127
142
|
const effect = this.customEffects.get(name);
|
|
128
143
|
if (effect) {
|
|
129
144
|
effect(x, y, ...args);
|
|
@@ -205,6 +220,21 @@ export class ParticleSystem {
|
|
|
205
220
|
this.pool.push(p);
|
|
206
221
|
}
|
|
207
222
|
|
|
223
|
+
/**
|
|
224
|
+
* The part contract: one call for every built-in effect. An unknown kind
|
|
225
|
+
* does nothing.
|
|
226
|
+
* @param {'confetti'|'sparkle'|'fire'|'stars'|'coins'} kind
|
|
227
|
+
* @param {{x: number, y: number}} [at] - Defaults to the middle of the canvas.
|
|
228
|
+
* @param {{count?: number, color?: string}} [opts]
|
|
229
|
+
*/
|
|
230
|
+
burst(kind, at, opts) {
|
|
231
|
+
if (typeof kind !== 'string' || !hasOwn(BURSTS, kind)) return;
|
|
232
|
+
const x = Number.isFinite(at?.x) ? at.x : this.width / 2;
|
|
233
|
+
const y = Number.isFinite(at?.y) ? at.y : this.height / 2;
|
|
234
|
+
const count = Number.isFinite(opts?.count) ? opts.count : undefined;
|
|
235
|
+
BURSTS[kind](this, x, y, count, opts?.color);
|
|
236
|
+
}
|
|
237
|
+
|
|
208
238
|
// --- Built-in Effects ---
|
|
209
239
|
|
|
210
240
|
confetti(x, y, count = 50) {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Short vibrations for hits and wins. A browser without the Vibration API
|
|
3
|
+
* (iOS Safari) or one that blocks it is silent, never an error.
|
|
4
|
+
*/
|
|
5
|
+
export function createHaptics({ nav = globalThis.navigator, enabled = true } = {}) {
|
|
6
|
+
let on = Boolean(enabled);
|
|
7
|
+
const buzz = (pattern) => {
|
|
8
|
+
if (!on) return;
|
|
9
|
+
// A missing or non-function vibrate throws here too.
|
|
10
|
+
try {
|
|
11
|
+
nav.vibrate(pattern);
|
|
12
|
+
} catch {}
|
|
13
|
+
};
|
|
14
|
+
return {
|
|
15
|
+
tap: () => buzz(10),
|
|
16
|
+
double: () => buzz([10, 40, 10]),
|
|
17
|
+
setEnabled(value) {
|
|
18
|
+
on = Boolean(value);
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const NO_PREFERENCE = Object.freeze({ matches: false });
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The reduced-motion media query, or `{ matches: false }` where there is no
|
|
5
|
+
* matchMedia (SSR, tests). The live query updates when the user changes it.
|
|
6
|
+
*/
|
|
7
|
+
export function prefersReducedMotion(win = globalThis.window) {
|
|
8
|
+
return (typeof win?.matchMedia === 'function' && win.matchMedia('(prefers-reduced-motion: reduce)')) || NO_PREFERENCE;
|
|
9
|
+
}
|