woofjs-engine 0.2.0 → 0.3.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +16 -106
  3. package/THIRD_PARTY_NOTICES.md +7 -0
  4. package/dist/canvas.js +4 -31
  5. package/dist/collision.js +8 -5
  6. package/dist/game.js +4 -84
  7. package/dist/index-1jykaz1m.js +142 -0
  8. package/dist/index-9mz0qg9d.js +39 -0
  9. package/dist/index-b9a70qgn.js +34 -0
  10. package/dist/index-dp75gf4w.js +57 -0
  11. package/dist/index-f63yb8zf.js +85 -0
  12. package/dist/index-gypg8d50.js +31 -0
  13. package/dist/index-pw0zq53c.js +2533 -0
  14. package/dist/index.js +134 -239
  15. package/dist/input.js +4 -33
  16. package/dist/play.js +296 -0
  17. package/dist/sound.js +4 -56
  18. package/dist/store.js +4 -30
  19. package/dist/types/canvas.d.ts +20 -2
  20. package/dist/types/collision.d.ts +62 -0
  21. package/dist/types/game.d.ts +21 -1
  22. package/dist/types/global.d.ts +4 -0
  23. package/dist/types/helpers.d.ts +92 -0
  24. package/dist/types/index.d.ts +23 -12
  25. package/dist/types/input.d.ts +4 -0
  26. package/dist/types/play.d.ts +159 -0
  27. package/dist/types/sound.d.ts +10 -3
  28. package/dist/types/sprites/custom.d.ts +9 -0
  29. package/dist/types/sprites/easing.d.ts +9 -0
  30. package/dist/types/sprites/geometry.d.ts +22 -0
  31. package/dist/types/sprites/options.d.ts +98 -0
  32. package/dist/types/sprites/render.d.ts +2 -0
  33. package/dist/types/sprites/sprite.d.ts +283 -0
  34. package/dist/types/store.d.ts +4 -0
  35. package/dist/types/ui.d.ts +65 -0
  36. package/dist/types/woof.d.ts +386 -0
  37. package/dist/types/world/audio.d.ts +118 -0
  38. package/dist/types/world/globals.d.ts +3 -0
  39. package/dist/types/world/keys.d.ts +2 -0
  40. package/dist/types/world/options.d.ts +44 -0
  41. package/dist/types/world/render.d.ts +13 -0
  42. package/dist/types/world/scheduler.d.ts +65 -0
  43. package/dist/ui.js +235 -0
  44. package/dist/woof.global.js +3577 -0
  45. package/docs/api.json +5359 -0
  46. package/docs/woof-parity.md +231 -0
  47. package/package.json +25 -8
  48. package/docs/architecture.md +0 -37
  49. package/docs/planning.md +0 -33
@@ -0,0 +1,2533 @@
1
+ import {
2
+ intersects2
3
+ } from "./index-1jykaz1m.js";
4
+ var __defProp = Object.defineProperty;
5
+ var __returnValue = (v) => v;
6
+ function __exportSetter(name, newValue) {
7
+ this[name] = __returnValue.bind(null, newValue);
8
+ }
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true,
14
+ configurable: true,
15
+ set: __exportSetter.bind(all, name)
16
+ });
17
+ };
18
+
19
+ // src/helpers.ts
20
+ var exports_helpers = {};
21
+ __export(exports_helpers, {
22
+ DOWN: () => DOWN2,
23
+ LEFT: () => LEFT2,
24
+ RIGHT: () => RIGHT2,
25
+ UP: () => UP2,
26
+ abs: () => abs2,
27
+ acos: () => acos2,
28
+ arrayToString: () => arrayToString2,
29
+ asin: () => asin2,
30
+ atan: () => atan2,
31
+ between: () => between2,
32
+ ceiling: () => ceiling2,
33
+ clamp: () => clamp2,
34
+ cos: () => cos2,
35
+ dayOfMonth: () => dayOfMonth2,
36
+ dayOfWeek: () => dayOfWeek2,
37
+ distance: () => distance2,
38
+ extend: () => extend2,
39
+ floor: () => floor2,
40
+ getData: () => getData2,
41
+ hour: () => hour2,
42
+ hourMilitary: () => hourMilitary2,
43
+ importCodeURL: () => importCodeURL2,
44
+ keyCodeToString: () => keyCodeToString2,
45
+ lerp: () => lerp2,
46
+ ln: () => ln2,
47
+ log: () => log2,
48
+ minute: () => minute2,
49
+ mobile: () => mobile2,
50
+ month: () => month2,
51
+ months: () => months2,
52
+ pick: () => pick2,
53
+ pow: () => pow2,
54
+ random: () => random2,
55
+ randomColor: () => randomColor2,
56
+ randomFloat: () => randomFloat2,
57
+ range: () => range2,
58
+ remove: () => remove2,
59
+ rgb: () => rgb2,
60
+ second: () => second2,
61
+ shuffle: () => shuffle2,
62
+ sin: () => sin2,
63
+ sqrt: () => sqrt2,
64
+ tan: () => tan2,
65
+ throttle: () => throttle2,
66
+ unitsToMiliseconds: () => unitsToMiliseconds2,
67
+ year: () => year2
68
+ });
69
+ var clamp2 = (n, min, max) => Math.min(max, Math.max(min, n));
70
+ var lerp2 = (a, b, t) => a + (b - a) * t;
71
+ var distance2 = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
72
+ var between2 = (n, a, b) => n > Math.min(a, b) && n < Math.max(a, b);
73
+ function remove2(array, item) {
74
+ for (let i = array.length - 1;i >= 0; i--)
75
+ if (array[i] === item)
76
+ array.splice(i, 1);
77
+ }
78
+ var randomFloat2 = (a, b) => Math.random() * Math.abs(b - a) + Math.min(a, b);
79
+ function random2(a, b) {
80
+ const min = Math.ceil(Math.min(a, b));
81
+ const max = Math.floor(Math.max(a, b));
82
+ if (!Number.isFinite(min) || !Number.isFinite(max) || min > max)
83
+ throw new RangeError("random needs bounds containing a whole number; try random(1, 6).");
84
+ return Math.floor(Math.random() * (max - min + 1)) + min;
85
+ }
86
+ var pick2 = (array) => array[Math.floor(Math.random() * array.length)];
87
+ function shuffle2(array) {
88
+ const result = [...array];
89
+ for (let i = result.length - 1;i > 0; i--) {
90
+ const j = Math.floor(Math.random() * (i + 1));
91
+ [result[i], result[j]] = [result[j], result[i]];
92
+ }
93
+ return result;
94
+ }
95
+ function range2(start, end, increment = 1) {
96
+ if (!Number.isFinite(increment) || increment === 0)
97
+ throw new RangeError("range increment must be nonzero; try range(0, 10, 1).");
98
+ const result = [];
99
+ const step = Math.abs(increment) * (start < end ? 1 : -1);
100
+ for (let i = start;step > 0 ? i < end : i > end; i += step)
101
+ result.push(i);
102
+ return result;
103
+ }
104
+ var rgb2 = (r, g, b) => `rgb(${r}, ${g}, ${b})`;
105
+ var randomColor2 = () => rgb2(random2(0, 255), random2(0, 255), random2(0, 255));
106
+ var RIGHT2 = 0;
107
+ var LEFT2 = 180;
108
+ var UP2 = 90;
109
+ var DOWN2 = 270;
110
+ var sin2 = (a) => Math.sin(a * Math.PI / 180);
111
+ var cos2 = (a) => Math.cos(a * Math.PI / 180);
112
+ var tan2 = (a) => Math.tan(a * Math.PI / 180);
113
+ var asin2 = (a) => Math.asin(a) * 180 / Math.PI;
114
+ var acos2 = (a) => Math.acos(a) * 180 / Math.PI;
115
+ var atan2 = (a) => Math.atan(a) * 180 / Math.PI;
116
+ var sqrt2 = Math.sqrt;
117
+ var abs2 = Math.abs;
118
+ var floor2 = Math.floor;
119
+ var ceiling2 = Math.ceil;
120
+ var ln2 = Math.log;
121
+ var log2 = Math.log10;
122
+ var pow2 = Math.pow;
123
+ var hourMilitary2 = () => new Date().getHours();
124
+ var hour2 = () => hourMilitary2() % 12 || 12;
125
+ var minute2 = () => new Date().getMinutes();
126
+ var second2 = () => new Date().getSeconds();
127
+ var dayOfMonth2 = () => new Date().getDate();
128
+ var dayOfWeek2 = () => [
129
+ "Sunday",
130
+ "Monday",
131
+ "Tuesday",
132
+ "Wednesday",
133
+ "Thursday",
134
+ "Friday",
135
+ "Saturday"
136
+ ][new Date().getDay()];
137
+ var month2 = () => months2[new Date().getMonth()];
138
+ var year2 = () => new Date().getFullYear();
139
+ var mobile2 = () => typeof navigator !== "undefined" && /Android|iPhone|iPad|IEMobile/i.test(navigator.userAgent);
140
+ async function importCodeURL2(url, callback) {
141
+ if (typeof document === "undefined")
142
+ throw new Error("importCodeURL requires a document.");
143
+ for (const src of typeof url === "string" ? [url] : url)
144
+ await new Promise((resolve, reject) => {
145
+ const script = document.createElement("script");
146
+ script.src = src;
147
+ script.onload = () => resolve();
148
+ script.onerror = () => reject(new Error(`Could not load ${src}`));
149
+ document.body.appendChild(script);
150
+ });
151
+ callback?.();
152
+ }
153
+ function extend2(target, source) {
154
+ return Object.assign(target, source);
155
+ }
156
+ var months2 = [
157
+ "January",
158
+ "February",
159
+ "March",
160
+ "April",
161
+ "May",
162
+ "June",
163
+ "July",
164
+ "August",
165
+ "September",
166
+ "October",
167
+ "November",
168
+ "December"
169
+ ];
170
+ function keyCodeToString2(code) {
171
+ const names = {
172
+ 38: "UP",
173
+ 37: "LEFT",
174
+ 39: "RIGHT",
175
+ 40: "DOWN",
176
+ 9: "TAB",
177
+ 13: "ENTER",
178
+ 16: "SHIFT",
179
+ 17: "CTRL",
180
+ 18: "ALT",
181
+ 27: "ESCAPE",
182
+ 32: "SPACE",
183
+ 192: "`",
184
+ 186: ";",
185
+ 222: "'",
186
+ 189: "-",
187
+ 187: "=",
188
+ 219: "[",
189
+ 220: "\\",
190
+ 221: "]",
191
+ 191: "/",
192
+ 190: ".",
193
+ 188: ",",
194
+ 20: "CAPS LOCK",
195
+ 8: "DELETE",
196
+ 91: "COMMAND"
197
+ };
198
+ return names[code] ?? (code >= 65 && code <= 90 || code >= 48 && code <= 57 ? String.fromCharCode(code) : String(code));
199
+ }
200
+ function unitsToMiliseconds2(time, units) {
201
+ if (/^mil(?:l)?iseconds?$/.test(units))
202
+ return time;
203
+ if (/^seconds?$/.test(units))
204
+ return time * 1000;
205
+ if (/^minutes?$/.test(units))
206
+ return time * 60000;
207
+ throw new TypeError("Unknown time unit; try unitsToMiliseconds(2, 'seconds').");
208
+ }
209
+ function throttle2(callback, limit) {
210
+ if (typeof callback !== "function" || !Number.isFinite(limit) || limit < 0) {
211
+ throw new TypeError("throttle requires a callback and non-negative milliseconds; try throttle(save, 500).");
212
+ }
213
+ let last = -Infinity;
214
+ return function(...args) {
215
+ const now = Date.now();
216
+ if (now - last >= limit) {
217
+ last = now;
218
+ callback.apply(this, args);
219
+ }
220
+ };
221
+ }
222
+ async function getData2(url, callback) {
223
+ const response = await fetch(url);
224
+ if (!response.ok)
225
+ throw new Error(`Could not fetch ${url}: ${response.status}`);
226
+ const data = await response.json();
227
+ callback?.(data);
228
+ return data;
229
+ }
230
+ function arrayToString2(values) {
231
+ return `[${values.join(",")}]`;
232
+ }
233
+
234
+ // src/world/keys.ts
235
+ function normalizeKey(key) {
236
+ const map = {
237
+ ArrowLeft: "LEFT",
238
+ ArrowRight: "RIGHT",
239
+ ArrowUp: "UP",
240
+ ArrowDown: "DOWN",
241
+ Space: "SPACE",
242
+ " ": "SPACE",
243
+ ControlLeft: "CTRL",
244
+ ControlRight: "CTRL",
245
+ ShiftLeft: "SHIFT",
246
+ ShiftRight: "SHIFT",
247
+ AltLeft: "ALT",
248
+ AltRight: "ALT",
249
+ Backspace: "DELETE",
250
+ CapsLock: "CAPS LOCK",
251
+ MetaLeft: "COMMAND",
252
+ MetaRight: "COMMAND",
253
+ Backquote: "`",
254
+ Semicolon: ";",
255
+ Quote: "'",
256
+ Minus: "-",
257
+ Equal: "=",
258
+ BracketLeft: "[",
259
+ Backslash: "\\",
260
+ BracketRight: "]",
261
+ Slash: "/",
262
+ Period: ".",
263
+ Comma: ","
264
+ };
265
+ const aliases = {
266
+ "UP ARROW": "UP",
267
+ "DOWN ARROW": "DOWN",
268
+ "LEFT ARROW": "LEFT",
269
+ "RIGHT ARROW": "RIGHT",
270
+ RETURN: "ENTER",
271
+ CONTROL: "CTRL",
272
+ OPTION: "ALT",
273
+ ESC: "ESCAPE",
274
+ "SPACE BAR": "SPACE",
275
+ SPACEBAR: "SPACE",
276
+ CAPS: "CAPS LOCK",
277
+ DEL: "DELETE",
278
+ BACKSPACE: "DELETE",
279
+ CMD: "COMMAND",
280
+ WINDOWS: "COMMAND",
281
+ SEARCH: "COMMAND",
282
+ METALEFT: "COMMAND",
283
+ METARIGHT: "COMMAND"
284
+ };
285
+ const upper = key.toUpperCase();
286
+ if (aliases[upper])
287
+ return aliases[upper];
288
+ return map[key] ?? (key.startsWith("Key") ? key.slice(3).toUpperCase() : key.startsWith("Digit") ? key.slice(5) : key.toUpperCase());
289
+ }
290
+
291
+ // src/world/globals.ts
292
+ function installProjectGlobals(project, win, restoreGlobals) {
293
+ if (!win)
294
+ throw new Error("global mode requires a window; pass { window } or use a browser.");
295
+ const target = win;
296
+ const install = (name, descriptor, replace = false) => {
297
+ if (!replace && name in target)
298
+ return;
299
+ const previous = Object.getOwnPropertyDescriptor(target, name);
300
+ if (previous && !previous.configurable)
301
+ return;
302
+ Object.defineProperty(target, name, {
303
+ configurable: true,
304
+ enumerable: true,
305
+ ...descriptor
306
+ });
307
+ const installed = Object.getOwnPropertyDescriptor(target, name);
308
+ restoreGlobals.push(() => {
309
+ const current = Object.getOwnPropertyDescriptor(target, name);
310
+ if (!current || current.value !== installed?.value || current.get !== installed?.get)
311
+ return;
312
+ if (previous)
313
+ Object.defineProperty(target, name, previous);
314
+ else
315
+ delete target[name];
316
+ });
317
+ };
318
+ const value = (name, item, replace = false) => install(name, { value: item, writable: true }, replace);
319
+ const shapeTypes = {
320
+ Circle: "circle",
321
+ Rectangle: "rectangle",
322
+ Oval: "oval",
323
+ Polygon: "polygon",
324
+ Line: "line",
325
+ Text: "text",
326
+ TextPrimative: "text",
327
+ Image: "image",
328
+ Bundle: "bundle",
329
+ Sprite: "sprite"
330
+ };
331
+ for (const [name, type] of Object.entries(shapeTypes)) {
332
+ value(name, function(options = {}) {
333
+ return (options.project ?? project).createSprite(type, options);
334
+ }, name === "Image" || name === "Text");
335
+ }
336
+ value("Sound", function(options = {}) {
337
+ return project.sound(options);
338
+ });
339
+ for (const name of [
340
+ "after",
341
+ "every",
342
+ "forever",
343
+ "when",
344
+ "once",
345
+ "repeat",
346
+ "repeatUntil",
347
+ "wait",
348
+ "setBackdropColor",
349
+ "setBackdropURL",
350
+ "setBackdropSize",
351
+ "setBackdropStyle",
352
+ "setBackdropRepeat",
353
+ "random",
354
+ "randomFloat",
355
+ "randomX",
356
+ "randomY",
357
+ "customSprite",
358
+ "freeze",
359
+ "defrost",
360
+ "ready",
361
+ "translateToCanvas",
362
+ "translateToCenter",
363
+ "bounds",
364
+ "clearPen",
365
+ "timer",
366
+ "resetTimer",
367
+ "onKeyDown",
368
+ "onKeyUp",
369
+ "onMouseDown",
370
+ "onMouseUp",
371
+ "onMouseMove",
372
+ "onUpdate",
373
+ "scene",
374
+ "go",
375
+ "find",
376
+ "particles",
377
+ "save",
378
+ "load"
379
+ ])
380
+ value(name, project[name].bind(project));
381
+ for (const [name, item] of Object.entries(exports_helpers))
382
+ value(name, item);
383
+ value("pressing", { includes: (key) => project.key(key) });
384
+ value("global", true);
385
+ for (const name of [
386
+ "mouseX",
387
+ "mouseY",
388
+ "pMouseX",
389
+ "pMouseY",
390
+ "mouseXSpeed",
391
+ "mouseYSpeed",
392
+ "mouseDown",
393
+ "keysDown",
394
+ "width",
395
+ "height",
396
+ "minX",
397
+ "maxX",
398
+ "minY",
399
+ "maxY",
400
+ "sprites",
401
+ "stopped",
402
+ "backdrop"
403
+ ])
404
+ install(name, { get: () => project[name] });
405
+ }
406
+
407
+ // src/sprites/custom.ts
408
+ function createCustomSprite(project, definition) {
409
+ if (typeof definition.render !== "function")
410
+ throw new TypeError("customSprite requires a render function; try customSprite({ render(ctx) {} }).");
411
+ return function(options = {}) {
412
+ const sprite = Object.assign((options.project ?? project).sprite(options), definition);
413
+ sprite.draw = (ctx) => sprite.render(ctx);
414
+ return sprite;
415
+ };
416
+ }
417
+
418
+ // src/sprites/geometry.ts
419
+ function spriteCollider(sprite) {
420
+ if (sprite.type === "circle")
421
+ return {
422
+ kind: "circle",
423
+ x: sprite.x,
424
+ y: sprite.y,
425
+ radius: Math.abs(sprite.radius * sprite.scale)
426
+ };
427
+ if (sprite.type === "oval")
428
+ return {
429
+ kind: "ellipse",
430
+ x: sprite.x,
431
+ y: sprite.y,
432
+ radiusX: Math.abs(sprite.width * sprite.scale / 2),
433
+ radiusY: Math.abs(sprite.height * sprite.scale / 2),
434
+ angle: sprite.rotationStyle === "ROTATE" ? sprite.radians() : 0
435
+ };
436
+ let points;
437
+ if (sprite.type === "line") {
438
+ const dx = sprite.x1 - sprite.x, dy = sprite.y1 - sprite.y, d = Math.hypot(dx, dy) || 1, w = sprite.width * sprite.scale / 2;
439
+ return {
440
+ kind: "polygon",
441
+ points: [
442
+ { x: sprite.x - dy / d * w, y: sprite.y + dx / d * w },
443
+ { x: sprite.x + dy / d * w, y: sprite.y - dx / d * w },
444
+ { x: sprite.x1 + dy / d * w, y: sprite.y1 - dx / d * w },
445
+ { x: sprite.x1 - dy / d * w, y: sprite.y1 + dx / d * w }
446
+ ]
447
+ };
448
+ }
449
+ if (sprite.type === "polygon")
450
+ points = Array.from({ length: Math.max(3, Math.floor(sprite.sides)) }, (_, i) => ({
451
+ x: sprite.length * Math.cos(i * 2 * Math.PI / sprite.sides),
452
+ y: sprite.length * Math.sin(i * 2 * Math.PI / sprite.sides)
453
+ }));
454
+ else {
455
+ const w = sprite.type === "text" ? sprite.textEval().length * sprite.size * 0.6 : sprite.width, h = sprite.type === "text" ? sprite.size : sprite.height;
456
+ points = [
457
+ { x: -w / 2, y: -h / 2 },
458
+ { x: w / 2, y: -h / 2 },
459
+ { x: w / 2, y: h / 2 },
460
+ { x: -w / 2, y: h / 2 }
461
+ ];
462
+ }
463
+ const a = sprite.rotationStyle === "ROTATE" ? sprite.radians() : 0, c = Math.cos(a), s = Math.sin(a);
464
+ return {
465
+ kind: "polygon",
466
+ points: points.map((p) => ({
467
+ x: sprite.x + sprite.scale * (p.x * c - p.y * s),
468
+ y: sprite.y + sprite.scale * (p.x * s + p.y * c)
469
+ }))
470
+ };
471
+ }
472
+ function spriteBounds(sprite) {
473
+ if (sprite.type === "bundle") {
474
+ const bounds = sprite.components.map((child) => child.bounds());
475
+ if (!bounds.length)
476
+ return { left: sprite.x, right: sprite.x, top: sprite.y, bottom: sprite.y };
477
+ return {
478
+ left: Math.min(...bounds.map((b) => b.left)),
479
+ right: Math.max(...bounds.map((b) => b.right)),
480
+ top: Math.max(...bounds.map((b) => b.top)),
481
+ bottom: Math.min(...bounds.map((b) => b.bottom))
482
+ };
483
+ }
484
+ const c = sprite.collider();
485
+ if (c.kind === "circle")
486
+ return {
487
+ left: c.x - c.radius,
488
+ right: c.x + c.radius,
489
+ top: c.y + c.radius,
490
+ bottom: c.y - c.radius
491
+ };
492
+ if (c.kind === "ellipse") {
493
+ const x = Math.hypot(c.radiusX * Math.cos(c.angle), c.radiusY * Math.sin(c.angle));
494
+ const y = Math.hypot(c.radiusX * Math.sin(c.angle), c.radiusY * Math.cos(c.angle));
495
+ return { left: c.x - x, right: c.x + x, top: c.y + y, bottom: c.y - y };
496
+ }
497
+ return {
498
+ left: Math.min(...c.points.map((p) => p.x)),
499
+ right: Math.max(...c.points.map((p) => p.x)),
500
+ top: Math.max(...c.points.map((p) => p.y)),
501
+ bottom: Math.min(...c.points.map((p) => p.y))
502
+ };
503
+ }
504
+ function spritesTouching(sprite, other, precise) {
505
+ if (!sprite.showing || sprite.deleted || !other.showing || other.deleted || sprite === other) {
506
+ return false;
507
+ }
508
+ if (sprite.type === "bundle") {
509
+ return sprite.components.some((child) => child.touching(other, precise));
510
+ }
511
+ if (other.type === "bundle") {
512
+ return other.components.some((child) => sprite.touching(child, precise));
513
+ }
514
+ return intersects2(sprite.collider(), other.collider()) && (!precise || sprite.project.preciseCollision(sprite, other));
515
+ }
516
+ function spriteOverlaps(sprite, bounds) {
517
+ if (sprite.deleted || !sprite.showing)
518
+ return false;
519
+ if (sprite.type === "bundle") {
520
+ return sprite.components.some((child) => child.overlap(bounds));
521
+ }
522
+ return intersects2(sprite.collider(), {
523
+ kind: "polygon",
524
+ points: [
525
+ { x: bounds.left, y: bounds.bottom },
526
+ { x: bounds.right, y: bounds.bottom },
527
+ { x: bounds.right, y: bounds.top },
528
+ { x: bounds.left, y: bounds.top }
529
+ ]
530
+ });
531
+ }
532
+ function spriteOver(sprite, x, y) {
533
+ if (!sprite.showing || sprite.deleted)
534
+ return false;
535
+ if (sprite.type === "bundle")
536
+ return sprite.components.some((child) => child.over(x, y));
537
+ return intersects2(sprite.collider(), { kind: "circle", x, y, radius: 0 });
538
+ }
539
+
540
+ // src/sprites/render.ts
541
+ function renderSprite(sprite, ctx) {
542
+ if (!sprite.showing || sprite.deleted || sprite.type === "bundle")
543
+ return;
544
+ ctx.save();
545
+ ctx.translate(sprite.canvasX(), sprite.canvasY());
546
+ if (sprite.rotationStyle === "ROTATE" && sprite.type !== "line")
547
+ ctx.rotate(-sprite.radians());
548
+ else if (sprite.rotationStyle === "ROTATE LEFT RIGHT" && Math.cos(sprite.radians()) < 0)
549
+ ctx.scale(-1, 1);
550
+ ctx.scale(sprite.scale * (sprite.flipX ? -1 : 1), sprite.scale * (sprite.flipY ? -1 : 1));
551
+ ctx.globalAlpha = sprite.opacity * sprite.brightness / 100;
552
+ ctx.fillStyle = sprite.color;
553
+ if (sprite.type === "circle") {
554
+ ctx.beginPath();
555
+ ctx.arc(0, 0, sprite.radius, 0, Math.PI * 2);
556
+ ctx.fill();
557
+ } else if (sprite.type === "oval") {
558
+ ctx.beginPath();
559
+ ctx.ellipse(0, 0, sprite.width / 2, sprite.height / 2, 0, 0, Math.PI * 2);
560
+ ctx.fill();
561
+ } else if (sprite.type === "polygon") {
562
+ ctx.beginPath();
563
+ for (let i = 0;i < sprite.sides; i++) {
564
+ const a = -i * 2 * Math.PI / sprite.sides;
565
+ if (i === 0)
566
+ ctx.moveTo(sprite.length, 0);
567
+ else
568
+ ctx.lineTo(sprite.length * Math.cos(a), sprite.length * Math.sin(a));
569
+ }
570
+ ctx.closePath();
571
+ ctx.fill();
572
+ } else if (sprite.type === "line") {
573
+ ctx.beginPath();
574
+ ctx.moveTo(0, 0);
575
+ ctx.lineTo(sprite.x1 - sprite.x, -(sprite.y1 - sprite.y));
576
+ ctx.strokeStyle = sprite.color;
577
+ ctx.lineWidth = sprite.width;
578
+ ctx.stroke();
579
+ } else if (sprite.type === "text") {
580
+ ctx.font = `${sprite.size}px ${sprite.fontFamily}`;
581
+ ctx.textAlign = sprite.textAlign;
582
+ ctx.textBaseline = "middle";
583
+ sprite.textEval().split(`
584
+ `).forEach((line, i, all) => ctx.fillText(line, 0, (i - (all.length - 1) / 2) * sprite.size));
585
+ } else if (sprite.type === "image" && sprite.image?.complete) {
586
+ if (sprite.frames) {
587
+ const f = sprite.frames, cols = Math.max(1, Math.floor(sprite.image.width / f.width));
588
+ ctx.drawImage(sprite.image, sprite.frame % cols * f.width, Math.floor(sprite.frame / cols) * f.height, f.width, f.height, -sprite.width / 2, -sprite.height / 2, sprite.width, sprite.height);
589
+ } else
590
+ ctx.drawImage(sprite.image, -sprite.width / 2, -sprite.height / 2, sprite.width, sprite.height);
591
+ } else if (sprite.type === "sprite")
592
+ sprite.draw?.(ctx);
593
+ else
594
+ ctx.fillRect(-sprite.width / 2, -sprite.height / 2, sprite.width, sprite.height);
595
+ ctx.restore();
596
+ if (sprite.data.say !== undefined) {
597
+ ctx.save();
598
+ ctx.font = "14px sans-serif";
599
+ ctx.textAlign = "center";
600
+ ctx.fillStyle = "black";
601
+ ctx.fillText(String(sprite.data.say), sprite.canvasX(), sprite.canvasY() - sprite.height * Math.abs(sprite.scale) / 2 - 10);
602
+ ctx.restore();
603
+ }
604
+ if (sprite.showCollider) {
605
+ const shape = sprite.collider();
606
+ ctx.save();
607
+ ctx.strokeStyle = "green";
608
+ ctx.lineWidth = 1;
609
+ ctx.beginPath();
610
+ if (shape.kind === "circle")
611
+ ctx.arc(shape.x - sprite.project.cameraX + sprite.project.width / 2, sprite.project.height / 2 - (shape.y - sprite.project.cameraY), shape.radius, 0, Math.PI * 2);
612
+ else if (shape.kind === "ellipse") {
613
+ ctx.ellipse(shape.x - sprite.project.cameraX + sprite.project.width / 2, sprite.project.height / 2 - (shape.y - sprite.project.cameraY), shape.radiusX, shape.radiusY, -shape.angle, 0, Math.PI * 2);
614
+ } else
615
+ shape.points.forEach((p, i) => {
616
+ const x = p.x - sprite.project.cameraX + sprite.project.width / 2, y = sprite.project.height / 2 - (p.y - sprite.project.cameraY);
617
+ if (i === 0)
618
+ ctx.moveTo(x, y);
619
+ else
620
+ ctx.lineTo(x, y);
621
+ });
622
+ ctx.closePath();
623
+ ctx.stroke();
624
+ ctx.restore();
625
+ }
626
+ }
627
+
628
+ // src/sprites/easing.ts
629
+ var easings2 = {
630
+ linear: (t) => t,
631
+ easeIn: (t) => t * t,
632
+ easeOut: (t) => 1 - (1 - t) * (1 - t),
633
+ easeInOut: (t) => t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t)
634
+ };
635
+
636
+ // src/sprites/sprite.ts
637
+ class Sprite2 {
638
+ project;
639
+ type;
640
+ px;
641
+ py;
642
+ lastPenX = 0;
643
+ lastPenY = 0;
644
+ spriteAngle = 0;
645
+ spriteScale = 1;
646
+ rotationStyle;
647
+ spriteShowing = true;
648
+ deleted = false;
649
+ penColor;
650
+ penWidth;
651
+ penActive;
652
+ showCollider;
653
+ spriteBrightness = 100;
654
+ spriteWidth = 10;
655
+ spriteHeight = 10;
656
+ radius;
657
+ sides;
658
+ length;
659
+ x1;
660
+ y1;
661
+ color;
662
+ size;
663
+ text;
664
+ textAlign;
665
+ fontFamily;
666
+ imageUrl = "";
667
+ costumes;
668
+ costumeIndex = 0;
669
+ opacity;
670
+ vx;
671
+ vy;
672
+ gravity;
673
+ bounce;
674
+ wrap;
675
+ tags;
676
+ data;
677
+ layer;
678
+ draw;
679
+ update;
680
+ flipX;
681
+ flipY;
682
+ frames;
683
+ frame = 0;
684
+ components = [];
685
+ imageElement;
686
+ offsetX = 0;
687
+ offsetY = 0;
688
+ offsetAngle = 0;
689
+ parentBundle;
690
+ ownedTasks = new Set;
691
+ pressed = new Set;
692
+ downs = [];
693
+ ups = [];
694
+ clicks = [];
695
+ touches = [];
696
+ animation;
697
+ constructor(project, type, options = {}) {
698
+ const live = Object.entries(options).filter(([key, value]) => typeof value === "function" && !["draw", "update", "text", "project"].includes(key));
699
+ const o = { ...options };
700
+ for (const [key, value] of live)
701
+ o[key] = value();
702
+ const resolved = o;
703
+ this.project = project;
704
+ this.type = type;
705
+ this.px = resolved.x ?? 0;
706
+ this.py = resolved.y ?? 0;
707
+ this.lastPenX = this.px;
708
+ this.lastPenY = this.py;
709
+ this.angle = resolved.angle ?? 0;
710
+ this.rotationStyle = resolved.rotationStyle ?? "ROTATE";
711
+ this.showing = resolved.showing ?? true;
712
+ this.penActive = resolved.penDown ?? false;
713
+ this.penColor = resolved.penColor ?? "black";
714
+ this.penWidth = resolved.penWidth ?? 1;
715
+ this.showCollider = resolved.showCollider ?? false;
716
+ this.brightness = resolved.brightness ?? 100;
717
+ this.radius = Math.abs(resolved.radius ?? 10);
718
+ this.sides = resolved.sides ?? 3;
719
+ this.length = resolved.length ?? 100;
720
+ this.width = resolved.width ?? (type === "oval" ? 20 : type === "line" ? 1 : 10);
721
+ this.height = resolved.height ?? (type === "oval" ? 50 : 10);
722
+ this.x1 = resolved.x1 ?? 10;
723
+ this.y1 = resolved.y1 ?? 10;
724
+ this.costumes = [...resolved.costumes ?? []];
725
+ this.color = resolved.color ?? (type === "oval" ? "green" : "black");
726
+ this.size = resolved.size ?? 12;
727
+ this.text = resolved.text ?? "Text";
728
+ this.textAlign = resolved.textAlign ?? "center";
729
+ this.fontFamily = resolved.fontFamily ?? "arial";
730
+ this.imageUrl = resolved.url ?? "";
731
+ this.opacity = resolved.opacity ?? 1;
732
+ this.scale = resolved.scale ?? 1;
733
+ this.vx = resolved.vx ?? 0;
734
+ this.vy = resolved.vy ?? 0;
735
+ this.gravity = resolved.gravity ?? 0;
736
+ this.bounce = resolved.bounce ?? false;
737
+ this.wrap = resolved.wrap ?? false;
738
+ this.tags = [...resolved.tags ?? []];
739
+ this.data = { ...resolved.data };
740
+ this.layer = resolved.layer ?? 0;
741
+ this.draw = resolved.draw;
742
+ this.update = resolved.update;
743
+ this.flipX = resolved.flipX ?? false;
744
+ this.flipY = resolved.flipY ?? false;
745
+ this.frames = resolved.frames;
746
+ if (type === "image" && (this.imageUrl || this.costumes.length))
747
+ this.setImageURL(this.imageUrl || this.costumes[0]);
748
+ for (const component of resolved.components ?? [])
749
+ this.addComponent(component);
750
+ for (const [key, value] of live) {
751
+ const descriptor = Object.getOwnPropertyDescriptor(this, key) ?? Object.getOwnPropertyDescriptor(Sprite2.prototype, key);
752
+ if (!descriptor)
753
+ continue;
754
+ let stored = descriptor.value;
755
+ let source = value;
756
+ Object.defineProperty(this, key, {
757
+ configurable: true,
758
+ enumerable: true,
759
+ get: () => source ? source() : descriptor.get ? descriptor.get.call(this) : stored,
760
+ set: (next) => {
761
+ source = undefined;
762
+ if (descriptor.set)
763
+ descriptor.set.call(this, next);
764
+ else
765
+ stored = next;
766
+ }
767
+ });
768
+ }
769
+ }
770
+ get showing() {
771
+ return this.spriteShowing;
772
+ }
773
+ set showing(value) {
774
+ this.spriteShowing = value;
775
+ for (const child of this.components ?? [])
776
+ child.showing = value;
777
+ }
778
+ get brightness() {
779
+ return this.spriteBrightness;
780
+ }
781
+ set brightness(value) {
782
+ this.spriteBrightness = value;
783
+ for (const child of this.components ?? [])
784
+ child.brightness = value;
785
+ }
786
+ get angle() {
787
+ return this.spriteAngle;
788
+ }
789
+ set angle(value) {
790
+ const delta = (value - this.spriteAngle) * Math.PI / 180;
791
+ this.spriteAngle = value;
792
+ if (!delta || !this.components)
793
+ return;
794
+ const cos = Math.cos(delta), sin = Math.sin(delta);
795
+ for (const child of this.components) {
796
+ const x = child.x - this.x, y = child.y - this.y;
797
+ child.setPosition(this.x + x * cos - y * sin, this.y + x * sin + y * cos);
798
+ child.angle += delta * 180 / Math.PI;
799
+ }
800
+ }
801
+ get scale() {
802
+ return this.spriteScale;
803
+ }
804
+ set scale(value) {
805
+ const previous = this.spriteScale;
806
+ if (this.components?.length && previous === 0 && value !== previous)
807
+ throw new RangeError("Cannot rescale a bundle from zero.");
808
+ this.spriteScale = value;
809
+ if (!this.components || previous === value)
810
+ return;
811
+ if (previous === 0)
812
+ throw new RangeError("Cannot rescale a bundle from zero.");
813
+ const ratio = value / previous;
814
+ for (const child of this.components) {
815
+ child.setPosition(this.x + (child.x - this.x) * ratio, this.y + (child.y - this.y) * ratio);
816
+ child.scale *= ratio;
817
+ }
818
+ }
819
+ get image() {
820
+ return this.imageElement;
821
+ }
822
+ get costume() {
823
+ return this.costumeIndex;
824
+ }
825
+ set costume(value) {
826
+ this.switchCostume(value);
827
+ }
828
+ get lineWidth() {
829
+ return this.width;
830
+ }
831
+ set lineWidth(value) {
832
+ this.width = value;
833
+ }
834
+ toString() {
835
+ return `${this.type}@(${this.x},${this.y})`;
836
+ }
837
+ rotatedVector(x, y) {
838
+ const dx = x - this.x, dy = y - this.y + (this.type === "line" ? this.height / 2 : 0), c = Math.cos(this.radians()), s = Math.sin(this.radians());
839
+ return { x: c * dx - s * dy + this.x, y: s * dx + c * dy + this.y };
840
+ }
841
+ translatedVector(pos, v) {
842
+ return { x: v.x - pos.x, y: v.y - pos.y };
843
+ }
844
+ get url() {
845
+ return this.imageUrl;
846
+ }
847
+ set url(value) {
848
+ this.setImageURL(value);
849
+ }
850
+ get width() {
851
+ if (this.type === "circle")
852
+ return this.radius * 2;
853
+ if (this.type === "polygon")
854
+ return this.length * 2;
855
+ if (this.type === "text")
856
+ return Math.max(0, ...this.textEval().split(`
857
+ `).map((line) => line.length * this.size * 0.6));
858
+ return this.spriteWidth;
859
+ }
860
+ set width(value) {
861
+ this.spriteWidth = value;
862
+ }
863
+ get height() {
864
+ if (this.type === "circle")
865
+ return this.radius * 2;
866
+ if (this.type === "polygon")
867
+ return this.length * 2;
868
+ if (this.type === "line")
869
+ return Math.hypot(this.x1 - this.x, this.y1 - this.y);
870
+ if (this.type === "text")
871
+ return this.textEval().split(`
872
+ `).length * this.size;
873
+ return this.spriteHeight;
874
+ }
875
+ set height(value) {
876
+ this.spriteHeight = value;
877
+ }
878
+ get x() {
879
+ return this.px;
880
+ }
881
+ set x(v) {
882
+ this.setPosition(v, this.py);
883
+ }
884
+ get y() {
885
+ return this.py;
886
+ }
887
+ set y(v) {
888
+ this.setPosition(this.px, v);
889
+ }
890
+ setPosition(x, y) {
891
+ if (!Number.isFinite(x) || !Number.isFinite(y))
892
+ throw new TypeError("setPosition requires two numbers; try setPosition(10, 20).");
893
+ const dx = x - this.px, dy = y - this.py;
894
+ this.project.trackPen(this.px, this.py, x, y, this.penActive, this.penColor, this.penWidth);
895
+ this.px = x;
896
+ this.py = y;
897
+ this.lastPenX = x;
898
+ this.lastPenY = y;
899
+ for (const c of this.components)
900
+ c.changePosition(dx, dy);
901
+ return this;
902
+ }
903
+ changePosition(x, y) {
904
+ return this.setPosition(this.x + x, this.y + y);
905
+ }
906
+ move(n = 1) {
907
+ return this.changePosition(n * Math.cos(this.radians()), n * Math.sin(this.radians()));
908
+ }
909
+ radians() {
910
+ return this.angle * Math.PI / 180;
911
+ }
912
+ turnLeft(n = 1) {
913
+ this.angle = ((this.angle + n) % 360 + 360) % 360;
914
+ return this;
915
+ }
916
+ turnRight(n = 1) {
917
+ return this.turnLeft(-n);
918
+ }
919
+ pointTowards(x, y) {
920
+ const p = typeof x === "number" ? { x, y: y ?? 0 } : x;
921
+ this.angle = (Math.atan2(p.y - this.y, p.x - this.x) * 180 / Math.PI + 360) % 360;
922
+ return this;
923
+ }
924
+ distanceTo(x, y) {
925
+ const p = typeof x === "number" ? { x, y: y ?? 0 } : x;
926
+ return Math.hypot(this.x - p.x, this.y - p.y);
927
+ }
928
+ setRotationStyle(style) {
929
+ if (!["ROTATE", "NO ROTATE", "ROTATE LEFT RIGHT"].includes(style))
930
+ throw new TypeError("Use setRotationStyle('ROTATE'), 'NO ROTATE', or 'ROTATE LEFT RIGHT'.");
931
+ this.rotationStyle = style;
932
+ return this;
933
+ }
934
+ collider() {
935
+ return spriteCollider(this);
936
+ }
937
+ bounds() {
938
+ return spriteBounds(this);
939
+ }
940
+ touching(other, precise = false) {
941
+ return spritesTouching(this, other, precise);
942
+ }
943
+ overlap(b) {
944
+ return spriteOverlaps(this, b);
945
+ }
946
+ over(x, y) {
947
+ return spriteOver(this, x, y);
948
+ }
949
+ get mouseOver() {
950
+ return this.over(this.project.mouseX, this.project.mouseY);
951
+ }
952
+ get mouseDown() {
953
+ return this.mouseOver && this.project.mouseDown;
954
+ }
955
+ onMouseDown(fn) {
956
+ this.downs.push(fn);
957
+ return this;
958
+ }
959
+ onMouseUp(fn) {
960
+ this.ups.push(fn);
961
+ return this;
962
+ }
963
+ onClick(fn) {
964
+ this.clicks.push(fn);
965
+ return this;
966
+ }
967
+ onTouch(target, fn) {
968
+ this.touches.push({ target, fn, active: new Set });
969
+ return this;
970
+ }
971
+ pointer(kind, x, y, id = 0, cancelled = false) {
972
+ const over = this.over(x, y);
973
+ if (kind === "down" && over)
974
+ this.pressed.add(id);
975
+ const wasPressed = this.pressed.has(id);
976
+ if (kind === "up")
977
+ this.pressed.delete(id);
978
+ const callbacks = kind === "down" ? over ? this.downs : [] : over && !cancelled ? [...this.ups, ...wasPressed ? this.clicks : []] : [];
979
+ for (const fn of callbacks)
980
+ this.project.invoke(() => fn(x, y));
981
+ }
982
+ trackPen() {
983
+ this.project.trackPen(this.lastPenX, this.lastPenY, this.x, this.y, this.penActive, this.penColor, this.penWidth);
984
+ this.lastPenX = this.x;
985
+ this.lastPenY = this.y;
986
+ }
987
+ detachListeners() {
988
+ this.downs = [];
989
+ this.ups = [];
990
+ this.clicks = [];
991
+ this.pressed.clear();
992
+ }
993
+ arrangeComponents() {
994
+ const cosine = Math.cos(this.radians());
995
+ const sine = Math.sin(this.radians());
996
+ for (const child of this.components) {
997
+ child.setPosition(this.x + this.scale * (child.offsetX * cosine - child.offsetY * sine), this.y + this.scale * (child.offsetX * sine + child.offsetY * cosine));
998
+ child.angle = this.angle + child.offsetAngle;
999
+ }
1000
+ }
1001
+ advance(dt) {
1002
+ this.vy += this.gravity * dt;
1003
+ if (this.vx || this.vy)
1004
+ this.changePosition(this.vx * dt, this.vy * dt);
1005
+ const b = this.bounds(), p = this.project;
1006
+ if (this.bounce) {
1007
+ if (b.left < p.minX && this.vx < 0 || b.right > p.maxX && this.vx > 0)
1008
+ this.vx = -this.vx;
1009
+ if (b.bottom < p.minY && this.vy < 0 || b.top > p.maxY && this.vy > 0)
1010
+ this.vy = -this.vy;
1011
+ }
1012
+ if (this.wrap) {
1013
+ if (this.x < p.minX)
1014
+ this.x = p.maxX;
1015
+ else if (this.x > p.maxX)
1016
+ this.x = p.minX;
1017
+ if (this.y < p.minY)
1018
+ this.y = p.maxY;
1019
+ else if (this.y > p.maxY)
1020
+ this.y = p.minY;
1021
+ }
1022
+ if (this.animation && this.animation.fps > 0) {
1023
+ const a = this.animation;
1024
+ a.elapsed += dt;
1025
+ while (a.elapsed >= 1 / a.fps) {
1026
+ a.elapsed -= 1 / a.fps;
1027
+ if (a.index < a.frames.length - 1)
1028
+ a.index++;
1029
+ else if (a.loop)
1030
+ a.index = 0;
1031
+ else {
1032
+ this.animation = undefined;
1033
+ break;
1034
+ }
1035
+ this.frame = a.frames[a.index];
1036
+ }
1037
+ }
1038
+ if (this.update)
1039
+ p.invoke(() => this.update(this, dt));
1040
+ for (const t of this.touches) {
1041
+ const candidates = typeof t.target === "string" ? p.sprites.filter((s) => s.tags.includes(t.target)) : [t.target];
1042
+ const now = new Set(candidates.filter((s) => this.touching(s)));
1043
+ for (const s of now)
1044
+ if (!t.active.has(s))
1045
+ p.invoke(() => t.fn(s));
1046
+ t.active = now;
1047
+ }
1048
+ }
1049
+ render(ctx) {
1050
+ renderSprite(this, ctx);
1051
+ }
1052
+ textEval() {
1053
+ const v = typeof this.text === "function" ? this.text() : this.text;
1054
+ return String(v ?? "");
1055
+ }
1056
+ canvasX() {
1057
+ return this.x - this.project.cameraX + this.project.width / 2;
1058
+ }
1059
+ canvasY() {
1060
+ return this.project.height / 2 - (this.y - this.project.cameraY);
1061
+ }
1062
+ setImageURL(url) {
1063
+ this.imageUrl = url;
1064
+ const image = this.project.createImage();
1065
+ if (image) {
1066
+ image.src = url;
1067
+ this.imageElement = image;
1068
+ }
1069
+ return this;
1070
+ }
1071
+ addCostume(url) {
1072
+ this.costumes.push(url);
1073
+ return this;
1074
+ }
1075
+ switchCostume(costume) {
1076
+ const index = typeof costume === "number" ? costume : this.costumes.indexOf(costume);
1077
+ if (!Number.isInteger(index) || index < 0 || index >= this.costumes.length)
1078
+ throw new RangeError("Costume was not found; try switchCostume(0).");
1079
+ this.costumeIndex = index;
1080
+ return this.setImageURL(this.costumes[index]);
1081
+ }
1082
+ nextCostume() {
1083
+ if (this.costumes.length)
1084
+ this.switchCostume((this.costume + 1) % this.costumes.length);
1085
+ return this;
1086
+ }
1087
+ animate(o) {
1088
+ const frames = o.frames ?? Array.from({ length: this.frames?.count ?? 1 }, (_, i) => i);
1089
+ if (!frames.length || o.fps <= 0)
1090
+ throw new RangeError("animate requires positive fps and frames; try animate({ fps: 10 }).");
1091
+ this.animation = {
1092
+ fps: o.fps,
1093
+ frames,
1094
+ loop: o.loop ?? true,
1095
+ elapsed: 0,
1096
+ index: 0
1097
+ };
1098
+ this.frame = frames[0];
1099
+ return this;
1100
+ }
1101
+ penDown() {
1102
+ this.penActive = true;
1103
+ return this;
1104
+ }
1105
+ penUp() {
1106
+ this.penActive = false;
1107
+ return this;
1108
+ }
1109
+ show() {
1110
+ this.showing = true;
1111
+ for (const child of this.components)
1112
+ child.show();
1113
+ return this;
1114
+ }
1115
+ hide() {
1116
+ this.showing = false;
1117
+ for (const child of this.components)
1118
+ child.hide();
1119
+ return this;
1120
+ }
1121
+ sendToFront() {
1122
+ this.layer = Math.max(0, ...this.project.sprites.map((s) => s.layer)) + 1;
1123
+ for (const child of this.components)
1124
+ child.sendToFront();
1125
+ return this;
1126
+ }
1127
+ sendToBack() {
1128
+ this.layer = Math.min(0, ...this.project.sprites.map((s) => s.layer)) - 1;
1129
+ for (const child of [...this.components].reverse())
1130
+ child.sendToBack();
1131
+ return this;
1132
+ }
1133
+ delete() {
1134
+ if (!this.deleted) {
1135
+ this.deleted = true;
1136
+ this.showing = false;
1137
+ this.detachListeners();
1138
+ this.touches = [];
1139
+ this.animation = undefined;
1140
+ for (const task of this.ownedTasks)
1141
+ task.stop();
1142
+ this.ownedTasks.clear();
1143
+ this.parentBundle?.removeComponent(this);
1144
+ for (const c of [...this.components])
1145
+ c.delete();
1146
+ this.components = [];
1147
+ this.project.removeSprite(this);
1148
+ }
1149
+ return this;
1150
+ }
1151
+ remove() {
1152
+ return this.delete();
1153
+ }
1154
+ addComponent(sprite, offsetX, offsetY, offsetAngle) {
1155
+ if (sprite.deleted || this.deleted || sprite === this || sprite.project !== this.project || sprite.type === "bundle" && sprite.containsComponent(this)) {
1156
+ throw new Error("Invalid bundle component.");
1157
+ }
1158
+ if (this.components.includes(sprite))
1159
+ return this;
1160
+ if (this.scale === 0)
1161
+ throw new RangeError("Cannot add a component to a bundle with zero scale.");
1162
+ sprite.parentBundle?.removeComponent(sprite);
1163
+ sprite.parentBundle = this;
1164
+ const cosine = Math.cos(this.radians());
1165
+ const sine = Math.sin(this.radians());
1166
+ const dx = sprite.x - this.x;
1167
+ const dy = sprite.y - this.y;
1168
+ sprite.offsetX = offsetX ?? (dx * cosine + dy * sine) / this.scale;
1169
+ sprite.offsetY = offsetY ?? (dy * cosine - dx * sine) / this.scale;
1170
+ sprite.offsetAngle = offsetAngle ?? sprite.angle - this.angle;
1171
+ this.components.push(sprite);
1172
+ if (!this.showing)
1173
+ sprite.hide();
1174
+ sprite.brightness = this.brightness;
1175
+ if (offsetX !== undefined || offsetY !== undefined || offsetAngle !== undefined)
1176
+ this.arrangeComponents();
1177
+ return this;
1178
+ }
1179
+ containsComponent(sprite) {
1180
+ return this.components.some((child) => child === sprite || child.containsComponent(sprite));
1181
+ }
1182
+ removeComponent(sprite) {
1183
+ this.components = this.components.filter((s) => s !== sprite);
1184
+ if (sprite.parentBundle === this)
1185
+ sprite.parentBundle = undefined;
1186
+ return this;
1187
+ }
1188
+ set(props) {
1189
+ Object.assign(this, props);
1190
+ return this;
1191
+ }
1192
+ toJSON() {
1193
+ return {
1194
+ x: this.x,
1195
+ y: this.y,
1196
+ angle: this.angle,
1197
+ rotationStyle: this.rotationStyle,
1198
+ showing: this.showing,
1199
+ penDown: this.penActive,
1200
+ penColor: this.penColor,
1201
+ penWidth: this.penWidth,
1202
+ width: this.width,
1203
+ height: this.height,
1204
+ radius: this.radius,
1205
+ sides: this.sides,
1206
+ length: this.length,
1207
+ x1: this.x1,
1208
+ y1: this.y1,
1209
+ color: this.color,
1210
+ size: this.size,
1211
+ text: this.text,
1212
+ textAlign: this.textAlign,
1213
+ fontFamily: this.fontFamily,
1214
+ url: this.url,
1215
+ opacity: this.opacity,
1216
+ scale: this.scale,
1217
+ vx: this.vx,
1218
+ vy: this.vy,
1219
+ gravity: this.gravity,
1220
+ bounce: this.bounce,
1221
+ wrap: this.wrap,
1222
+ tags: [...this.tags],
1223
+ data: { ...this.data },
1224
+ layer: this.layer,
1225
+ draw: this.draw,
1226
+ update: this.update,
1227
+ flipX: this.flipX,
1228
+ flipY: this.flipY,
1229
+ frames: this.frames,
1230
+ costumes: [...this.costumes]
1231
+ };
1232
+ }
1233
+ clone(changes = {}) {
1234
+ const copy = this.project.createSprite(this.type, this.toJSON());
1235
+ if (this.costumes.length && this.url === this.costumes[this.costumeIndex])
1236
+ copy.switchCostume(this.costumeIndex);
1237
+ for (const child of this.components)
1238
+ copy.addComponent(child.clone());
1239
+ return copy.set(changes);
1240
+ }
1241
+ tween(props, seconds, easing = "linear") {
1242
+ const curve = typeof easing === "function" ? easing : easings2[easing];
1243
+ if (!curve)
1244
+ throw new RangeError(`Unknown easing: ${String(easing)}; try ${Object.keys(easings2).join(", ")}.`);
1245
+ const start = Object.fromEntries(Object.keys(props).map((k) => [
1246
+ k,
1247
+ this[k]
1248
+ ]));
1249
+ let elapsed = 0;
1250
+ return new Promise((resolve) => {
1251
+ if (seconds <= 0) {
1252
+ Object.assign(this, props);
1253
+ resolve();
1254
+ return;
1255
+ }
1256
+ const h = this.project.onUpdate((dt) => {
1257
+ elapsed += dt;
1258
+ const t = curve(Math.min(1, elapsed / seconds));
1259
+ for (const [k, v] of Object.entries(props))
1260
+ this[k] = start[k] + (v - start[k]) * t;
1261
+ if (elapsed >= seconds) {
1262
+ task.stop();
1263
+ }
1264
+ });
1265
+ const task = {
1266
+ stop: () => {
1267
+ h.stop();
1268
+ this.ownedTasks.delete(task);
1269
+ resolve();
1270
+ }
1271
+ };
1272
+ this.ownedTasks.add(task);
1273
+ });
1274
+ }
1275
+ glideTo(x, y, seconds) {
1276
+ return this.tween({ x, y }, seconds);
1277
+ }
1278
+ say(text, seconds) {
1279
+ this.data.say = text;
1280
+ if (seconds !== undefined) {
1281
+ const task = this.project.after(seconds, () => {
1282
+ this.ownedTasks.delete(task);
1283
+ if (this.data.say === text)
1284
+ delete this.data.say;
1285
+ });
1286
+ this.ownedTasks.add(task);
1287
+ }
1288
+ return this;
1289
+ }
1290
+ }
1291
+
1292
+ // src/world/render.ts
1293
+ function renderOne(sprite, context) {
1294
+ if (sprite.type === "sprite" && sprite.render !== Sprite2.prototype.render) {
1295
+ renderSprite(sprite, context);
1296
+ } else {
1297
+ sprite.render(context);
1298
+ }
1299
+ }
1300
+ function renderWorld(project, pen, shake) {
1301
+ const context = project.context;
1302
+ if (typeof context.clearRect !== "function")
1303
+ return;
1304
+ context.clearRect(0, 0, project.width, project.height);
1305
+ if (shake !== undefined) {
1306
+ context.save();
1307
+ context.translate(project.randomFloat(-shake, shake), project.randomFloat(-shake, shake));
1308
+ }
1309
+ for (const segment of pen) {
1310
+ context.beginPath();
1311
+ context.moveTo(segment.x1 - project.cameraX + project.width / 2, project.height / 2 - (segment.y1 - project.cameraY));
1312
+ context.lineTo(segment.x2 - project.cameraX + project.width / 2, project.height / 2 - (segment.y2 - project.cameraY));
1313
+ context.strokeStyle = segment.color;
1314
+ context.lineWidth = segment.width;
1315
+ context.lineCap = "round";
1316
+ context.stroke();
1317
+ }
1318
+ for (const sprite of [...project.sprites].sort((a, b) => a.layer - b.layer)) {
1319
+ project.invoke(() => renderOne(sprite, context));
1320
+ }
1321
+ if (shake !== undefined)
1322
+ context.restore();
1323
+ }
1324
+ function preciseCollision(project, document2, a, b) {
1325
+ const canvas = document2.createElement("canvas");
1326
+ canvas.width = project.width;
1327
+ canvas.height = project.height;
1328
+ const context = canvas.getContext("2d");
1329
+ if (!context || typeof context.getImageData !== "function") {
1330
+ throw new Error("Precise collision requires readable canvas pixels.");
1331
+ }
1332
+ try {
1333
+ renderOne(a, context);
1334
+ context.globalCompositeOperation = "source-in";
1335
+ renderOne(b, context);
1336
+ const pixels = context.getImageData(0, 0, project.width, project.height).data;
1337
+ for (let i = 3;i < pixels.length; i += 4) {
1338
+ if (pixels[i])
1339
+ return true;
1340
+ }
1341
+ return false;
1342
+ } catch (error) {
1343
+ throw new Error("Precise collision could not read canvas pixels; an image may be cross-origin or tainted.", { cause: error });
1344
+ }
1345
+ }
1346
+
1347
+ // src/world/audio.ts
1348
+ var volumes = { mute: 0, low: 0.5, normal: 1 };
1349
+ var speeds = { slow: 0.5, normal: 1, fast: 2 };
1350
+
1351
+ class ProjectSound2 {
1352
+ context;
1353
+ destination;
1354
+ fetcher;
1355
+ onUpdate;
1356
+ maxGain;
1357
+ limiter;
1358
+ loopValue = false;
1359
+ urlValue;
1360
+ baseVolume;
1361
+ rate;
1362
+ multiplier = 1;
1363
+ source;
1364
+ gain;
1365
+ panNode;
1366
+ buffer;
1367
+ loading;
1368
+ offset = 0;
1369
+ startedAt = 0;
1370
+ played = false;
1371
+ generation = 0;
1372
+ panValue = 0;
1373
+ fade;
1374
+ audioSettings = { speed: { ...speeds }, volume: { ...volumes } };
1375
+ get audio() {
1376
+ return this.source;
1377
+ }
1378
+ isPlaying = false;
1379
+ constructor(context, destination, fetcher, options = {}, onUpdate) {
1380
+ this.context = context;
1381
+ this.destination = destination;
1382
+ this.fetcher = fetcher;
1383
+ this.onUpdate = onUpdate;
1384
+ this.urlValue = options.url;
1385
+ this.buffer = options.buffer;
1386
+ this.loop = options.loop ?? false;
1387
+ this.maxGain = options.maxGain ?? 4;
1388
+ this.limiter = options.limiter ?? true;
1389
+ if (!Number.isFinite(this.maxGain) || this.maxGain < 0)
1390
+ throw new RangeError("maxGain must be non-negative; try maxGain: 4.");
1391
+ this.baseVolume = 1;
1392
+ this.rate = 1;
1393
+ this.volume = options.volume ?? 1;
1394
+ this.speed = options.speed ?? 1;
1395
+ }
1396
+ get loop() {
1397
+ return this.loopValue;
1398
+ }
1399
+ set loop(value) {
1400
+ if (typeof value !== "boolean")
1401
+ throw new TypeError("loop must be true or false; try sound.loop = true.");
1402
+ this.loopValue = value;
1403
+ if (this.source)
1404
+ this.source.loop = value;
1405
+ }
1406
+ get url() {
1407
+ return this.urlValue;
1408
+ }
1409
+ set url(value) {
1410
+ if (value !== undefined && typeof value !== "string")
1411
+ throw new TypeError("url must be a string; try sound.url = 'bell.wav'.");
1412
+ if (value === this.urlValue)
1413
+ return;
1414
+ this.stopPlaying();
1415
+ this.urlValue = value;
1416
+ this.buffer = undefined;
1417
+ this.loading = undefined;
1418
+ this.played = false;
1419
+ }
1420
+ get volume() {
1421
+ return this.baseVolume;
1422
+ }
1423
+ set volume(v) {
1424
+ const n = typeof v === "string" ? volumes[v] : v;
1425
+ if (!Number.isFinite(n) || n < 0 || n > 1)
1426
+ throw new RangeError("volume must be between 0 and 1; try volume: 0.5.");
1427
+ this.baseVolume = n;
1428
+ this.applyGain();
1429
+ }
1430
+ get speed() {
1431
+ return this.rate;
1432
+ }
1433
+ set speed(v) {
1434
+ const n = typeof v === "string" ? speeds[v] : v;
1435
+ if (!Number.isFinite(n) || n <= 0)
1436
+ throw new RangeError("speed must be positive; try speed: 1.");
1437
+ if (this.isPlaying) {
1438
+ this.offset = this.currentTime;
1439
+ this.startedAt = this.context().currentTime;
1440
+ }
1441
+ this.rate = n;
1442
+ if (this.source)
1443
+ this.source.playbackRate.value = n;
1444
+ }
1445
+ get duration() {
1446
+ return this.buffer?.duration ?? 0;
1447
+ }
1448
+ get currentTime() {
1449
+ const t = this.offset + (this.isPlaying ? (this.context().currentTime - this.startedAt) * this.rate : 0);
1450
+ return this.loop && this.duration ? t % this.duration : Math.min(this.duration || t, t);
1451
+ }
1452
+ set currentTime(v) {
1453
+ if (!Number.isFinite(v) || v < 0 || this.duration && v > this.duration)
1454
+ throw new RangeError("currentTime must be within the sound duration.");
1455
+ const playing = this.isPlaying;
1456
+ if (playing)
1457
+ this.pausePlaying();
1458
+ this.offset = v;
1459
+ if (playing)
1460
+ this.startPlaying();
1461
+ }
1462
+ neverPlayed() {
1463
+ return !this.played;
1464
+ }
1465
+ applyGain() {
1466
+ if (this.gain)
1467
+ this.gain.gain.value = this.multiplier === "max" ? this.maxGain : Math.min(this.maxGain, Math.max(0, this.baseVolume * this.multiplier));
1468
+ }
1469
+ amplify(n) {
1470
+ if (n !== "max" && (!Number.isFinite(n) || n < 0))
1471
+ throw new RangeError("amplify requires a non-negative number or 'max'.");
1472
+ this.multiplier = n;
1473
+ this.applyGain();
1474
+ return this;
1475
+ }
1476
+ load() {
1477
+ if (this.buffer)
1478
+ return Promise.resolve(this.buffer);
1479
+ if (!this.url)
1480
+ return Promise.reject(new Error("sound requires a url or buffer."));
1481
+ if (this.loading)
1482
+ return this.loading;
1483
+ const url = this.url;
1484
+ const loading = this.fetcher(url).then((response) => {
1485
+ if (!response.ok)
1486
+ throw new Error(`Could not load sound: ${url}`);
1487
+ return response.arrayBuffer();
1488
+ }).then((data) => this.context().decodeAudioData(data)).then((buffer) => {
1489
+ if (this.loading === loading)
1490
+ this.buffer = buffer;
1491
+ return buffer;
1492
+ }).catch((error) => {
1493
+ if (this.loading === loading)
1494
+ this.loading = undefined;
1495
+ throw error;
1496
+ });
1497
+ this.loading = loading;
1498
+ return loading;
1499
+ }
1500
+ startPlaying() {
1501
+ if (this.isPlaying)
1502
+ return this;
1503
+ this.isPlaying = true;
1504
+ this.played = true;
1505
+ const generation = ++this.generation;
1506
+ const start = (buffer) => {
1507
+ if (!this.isPlaying || generation !== this.generation)
1508
+ return;
1509
+ const ctx = this.context(), source = ctx.createBufferSource(), gain = ctx.createGain();
1510
+ this.source = source;
1511
+ this.gain = gain;
1512
+ source.buffer = buffer;
1513
+ source.loop = this.loop;
1514
+ source.playbackRate.value = this.rate;
1515
+ source.connect(gain);
1516
+ let node = gain;
1517
+ if (typeof ctx.createStereoPanner === "function") {
1518
+ this.panNode = ctx.createStereoPanner();
1519
+ this.panNode.pan.value = this.panValue;
1520
+ node.connect(this.panNode);
1521
+ node = this.panNode;
1522
+ }
1523
+ if (this.limiter && typeof ctx.createDynamicsCompressor === "function") {
1524
+ const compressor = ctx.createDynamicsCompressor();
1525
+ node.connect(compressor);
1526
+ node = compressor;
1527
+ }
1528
+ node.connect(this.destination(ctx));
1529
+ this.applyGain();
1530
+ this.beginFade();
1531
+ this.startedAt = ctx.currentTime;
1532
+ source.onended = () => {
1533
+ if (this.source === source) {
1534
+ this.isPlaying = false;
1535
+ this.offset = 0;
1536
+ this.source = undefined;
1537
+ }
1538
+ };
1539
+ source.start(0, this.offset);
1540
+ };
1541
+ if (this.buffer)
1542
+ start(this.buffer);
1543
+ else
1544
+ this.load().then(start).catch((error) => {
1545
+ if (generation === this.generation)
1546
+ this.isPlaying = false;
1547
+ console.error(error);
1548
+ });
1549
+ return this;
1550
+ }
1551
+ pausePlaying() {
1552
+ this.cancelFade();
1553
+ if (this.isPlaying) {
1554
+ if (this.source)
1555
+ this.offset = this.currentTime;
1556
+ this.isPlaying = false;
1557
+ this.generation++;
1558
+ const s = this.source;
1559
+ this.source = undefined;
1560
+ s?.stop();
1561
+ }
1562
+ return this;
1563
+ }
1564
+ stopPlaying() {
1565
+ this.pausePlaying();
1566
+ this.offset = 0;
1567
+ return this;
1568
+ }
1569
+ pan(value) {
1570
+ if (!Number.isFinite(value))
1571
+ throw new TypeError("pan requires a number; try pan(-1).");
1572
+ this.panValue = Math.max(-1, Math.min(1, value));
1573
+ if (this.panNode)
1574
+ this.panNode.pan.value = this.panValue;
1575
+ return this;
1576
+ }
1577
+ cancelFade() {
1578
+ this.fade?.task?.stop();
1579
+ this.fade = undefined;
1580
+ }
1581
+ beginFade() {
1582
+ const fade = this.fade;
1583
+ if (!fade || !this.gain || fade.task)
1584
+ return;
1585
+ const gain = this.gain.gain;
1586
+ const target = this.multiplier === "max" ? this.maxGain : Math.min(this.maxGain, this.baseVolume * this.multiplier);
1587
+ const start = fade.direction === "in" ? 0 : gain.value;
1588
+ const end = fade.direction === "in" ? target : 0;
1589
+ gain.value = start;
1590
+ const complete = () => {
1591
+ gain.value = end;
1592
+ this.cancelFade();
1593
+ if (fade.direction === "out")
1594
+ this.stopPlaying();
1595
+ };
1596
+ if (fade.seconds <= 0) {
1597
+ complete();
1598
+ return;
1599
+ }
1600
+ if (!this.onUpdate)
1601
+ return;
1602
+ let elapsed = 0;
1603
+ fade.task = this.onUpdate((dt) => {
1604
+ elapsed += dt;
1605
+ gain.value = start + (end - start) * Math.min(1, elapsed / fade.seconds);
1606
+ if (elapsed >= fade.seconds)
1607
+ complete();
1608
+ });
1609
+ }
1610
+ fadeIn(seconds) {
1611
+ if (!Number.isFinite(seconds) || seconds < 0)
1612
+ throw new RangeError("Fade duration must be non-negative.");
1613
+ this.cancelFade();
1614
+ this.fade = { direction: "in", seconds };
1615
+ this.startPlaying();
1616
+ this.beginFade();
1617
+ return this;
1618
+ }
1619
+ fadeOut(seconds) {
1620
+ if (!Number.isFinite(seconds) || seconds < 0)
1621
+ throw new RangeError("Fade duration must be non-negative.");
1622
+ this.cancelFade();
1623
+ if (this.isPlaying) {
1624
+ this.fade = { direction: "out", seconds };
1625
+ this.beginFade();
1626
+ }
1627
+ return this;
1628
+ }
1629
+ }
1630
+
1631
+ // src/world/scheduler.ts
1632
+ function duration(value, units = "seconds") {
1633
+ const resolved = typeof value === "function" ? value() : value;
1634
+ let amount;
1635
+ let unit = units;
1636
+ if (typeof resolved === "string") {
1637
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|milliseconds?|seconds?|s|minutes?|m)\s*$/i.exec(resolved);
1638
+ if (!match)
1639
+ throw new TypeError("Invalid duration; try '250ms' or 2 seconds.");
1640
+ amount = Number(match[1]);
1641
+ unit = match[2].toLowerCase();
1642
+ } else
1643
+ amount = resolved;
1644
+ if (!Number.isFinite(amount) || amount < 0)
1645
+ throw new RangeError("Duration must be non-negative; try 2 seconds.");
1646
+ if (/^(ms|milliseconds?|miliseconds?)$/.test(unit))
1647
+ return amount / 1000;
1648
+ if (/^(m|minutes?)$/.test(unit))
1649
+ return amount * 60;
1650
+ if (/^(s|seconds?)$/.test(unit))
1651
+ return amount;
1652
+ throw new TypeError("Unknown time unit; try 'seconds'.");
1653
+ }
1654
+
1655
+ class Scheduler {
1656
+ onError;
1657
+ tasks = new Set;
1658
+ constructor(onError = console.error) {
1659
+ this.onError = onError;
1660
+ }
1661
+ add(tick) {
1662
+ const task = {
1663
+ active: true,
1664
+ stop: () => {
1665
+ task.active = false;
1666
+ this.tasks.delete(task);
1667
+ },
1668
+ tick: (dt) => tick(dt, task)
1669
+ };
1670
+ this.tasks.add(task);
1671
+ return task;
1672
+ }
1673
+ call(fn) {
1674
+ try {
1675
+ fn();
1676
+ } catch (error) {
1677
+ this.onError(error);
1678
+ }
1679
+ }
1680
+ after(time, fn) {
1681
+ let remaining = duration(time);
1682
+ return this.add((dt, task) => {
1683
+ remaining -= dt;
1684
+ if (remaining <= 0) {
1685
+ task.stop();
1686
+ this.call(fn);
1687
+ }
1688
+ });
1689
+ }
1690
+ every(time, fn) {
1691
+ let remaining = duration(time);
1692
+ if (remaining <= 0)
1693
+ throw new RangeError("every interval must be positive; try every(1, fn).");
1694
+ this.call(fn);
1695
+ return this.add((dt, task) => {
1696
+ remaining -= dt;
1697
+ while (task.active && remaining <= 0) {
1698
+ this.call(fn);
1699
+ if (!task.active)
1700
+ break;
1701
+ const next = duration(time);
1702
+ if (next <= 0) {
1703
+ this.onError(new RangeError("every interval must be positive"));
1704
+ break;
1705
+ }
1706
+ remaining += next;
1707
+ }
1708
+ });
1709
+ }
1710
+ forever(fn) {
1711
+ return this.add(() => this.call(fn));
1712
+ }
1713
+ when(condition, fn) {
1714
+ return this.add(() => this.call(() => {
1715
+ if (condition())
1716
+ fn();
1717
+ }));
1718
+ }
1719
+ once(condition, fn) {
1720
+ return this.add((_dt, task) => this.call(() => {
1721
+ if (condition()) {
1722
+ task.stop();
1723
+ fn();
1724
+ }
1725
+ }));
1726
+ }
1727
+ step(dt) {
1728
+ for (const task of [...this.tasks])
1729
+ if (task.active)
1730
+ this.call(() => task.tick(dt));
1731
+ }
1732
+ clear() {
1733
+ for (const task of [...this.tasks])
1734
+ task.stop();
1735
+ }
1736
+ }
1737
+
1738
+ class Repeat2 {
1739
+ after;
1740
+ curTimes = 0;
1741
+ done = false;
1742
+ times;
1743
+ func;
1744
+ constructor(times, func, after) {
1745
+ this.after = after;
1746
+ this.times = Math.floor(times);
1747
+ this.func = func;
1748
+ }
1749
+ next() {
1750
+ if (this.done)
1751
+ return;
1752
+ if (this.curTimes >= this.times) {
1753
+ this.done = true;
1754
+ this.after?.(this.curTimes);
1755
+ return;
1756
+ }
1757
+ this.func(++this.curTimes);
1758
+ }
1759
+ }
1760
+
1761
+ class RepeatUntil2 {
1762
+ after;
1763
+ curTimes = 0;
1764
+ done = false;
1765
+ condition;
1766
+ func;
1767
+ constructor(condition, func, after) {
1768
+ this.after = after;
1769
+ this.condition = condition;
1770
+ this.func = func;
1771
+ }
1772
+ next() {
1773
+ if (this.done)
1774
+ return;
1775
+ if (this.condition()) {
1776
+ this.done = true;
1777
+ this.after?.(this.curTimes);
1778
+ return;
1779
+ }
1780
+ this.func(++this.curTimes);
1781
+ }
1782
+ }
1783
+
1784
+ // src/woof.ts
1785
+ class Project2 {
1786
+ canvas;
1787
+ context;
1788
+ helpers = exports_helpers;
1789
+ randomColor = randomColor2;
1790
+ range = range2;
1791
+ between = between2;
1792
+ remove = remove2;
1793
+ rgb = rgb2;
1794
+ pick = pick2;
1795
+ shuffle = shuffle2;
1796
+ clamp = clamp2;
1797
+ lerp = lerp2;
1798
+ distance = distance2;
1799
+ RIGHT = RIGHT2;
1800
+ LEFT = LEFT2;
1801
+ UP = UP2;
1802
+ DOWN = DOWN2;
1803
+ sin = sin2;
1804
+ cos = cos2;
1805
+ tan = tan2;
1806
+ asin = asin2;
1807
+ acos = acos2;
1808
+ atan = atan2;
1809
+ sqrt = sqrt2;
1810
+ abs = abs2;
1811
+ floor = floor2;
1812
+ ceiling = ceiling2;
1813
+ ln = ln2;
1814
+ log = log2;
1815
+ pow = pow2;
1816
+ hour = hour2;
1817
+ hourMilitary = hourMilitary2;
1818
+ minute = minute2;
1819
+ second = second2;
1820
+ dayOfMonth = dayOfMonth2;
1821
+ dayOfWeek = dayOfWeek2;
1822
+ month = month2;
1823
+ year = year2;
1824
+ mobile = mobile2;
1825
+ importCodeURL = importCodeURL2;
1826
+ Repeat = Repeat2;
1827
+ RepeatUntil = RepeatUntil2;
1828
+ keyCodeToString = keyCodeToString2;
1829
+ unitsToMiliseconds = unitsToMiliseconds2;
1830
+ months = months2;
1831
+ throttle = throttle2;
1832
+ getData = getData2;
1833
+ extend = extend2;
1834
+ width;
1835
+ height;
1836
+ fullScreen;
1837
+ global;
1838
+ restoreGlobals = [];
1839
+ backdrop = {
1840
+ color: null,
1841
+ type: null,
1842
+ url: null,
1843
+ size: "100% 100%",
1844
+ repeat: "no-repeat"
1845
+ };
1846
+ cameraX = 0;
1847
+ cameraY = 0;
1848
+ sprites = [];
1849
+ mouseX = 0;
1850
+ mouseY = 0;
1851
+ pMouseX = 0;
1852
+ pMouseY = 0;
1853
+ mouseSpeedX = 0;
1854
+ mouseSpeedY = 0;
1855
+ mouseDown = false;
1856
+ keysDown = Object.assign(new Set, {
1857
+ includes: (key) => this.key(key)
1858
+ });
1859
+ pendingKeys = new Set;
1860
+ frameKeys = new Set;
1861
+ listeners = [];
1862
+ keyDownHandlers = new Set;
1863
+ keyUpHandlers = new Set;
1864
+ pointerDownHandlers = new Set;
1865
+ pointerUpHandlers = new Set;
1866
+ pointerMoveHandlers = new Set;
1867
+ pen = [];
1868
+ doc;
1869
+ win;
1870
+ reportError;
1871
+ scheduler;
1872
+ requestFrame;
1873
+ cancelFrame;
1874
+ maxDeltaMs;
1875
+ frame;
1876
+ previous;
1877
+ elapsed = 0;
1878
+ timerEpoch = Date.now();
1879
+ running = false;
1880
+ frozen = false;
1881
+ freezePending = false;
1882
+ destroyed = false;
1883
+ scenes = new Map;
1884
+ sounds = new Set;
1885
+ audio;
1886
+ master;
1887
+ volume = 1;
1888
+ muted = false;
1889
+ audioFactory;
1890
+ fetcher;
1891
+ storage;
1892
+ randomState;
1893
+ following;
1894
+ shakeTime = 0;
1895
+ shakeStrength = 0;
1896
+ camera = {
1897
+ follow: (sprite, smoothing = 1) => {
1898
+ this.following = { sprite, smoothing };
1899
+ return this.camera;
1900
+ },
1901
+ shake: (strength, seconds) => {
1902
+ this.shakeStrength = strength;
1903
+ this.shakeTime = seconds;
1904
+ return this.camera;
1905
+ }
1906
+ };
1907
+ constructor(options = {}) {
1908
+ const doc = options.document ?? globalThis.document;
1909
+ if (!doc)
1910
+ throw new Error("woof() requires a document; pass { document } in tests.");
1911
+ const win = options.window ?? doc.defaultView ?? undefined;
1912
+ this.audioFactory = options.audioContext;
1913
+ this.fetcher = options.fetch ?? globalThis.fetch;
1914
+ this.storage = options.storage;
1915
+ this.randomState = options.seed;
1916
+ this.doc = doc;
1917
+ this.win = win;
1918
+ this.reportError = options.onError ?? ((error) => console.error(error));
1919
+ this.fullScreen = options.fullScreen ?? false;
1920
+ this.global = options.global ?? false;
1921
+ this.width = this.fullScreen ? win?.innerWidth ?? options.width ?? 350 : options.width ?? 350;
1922
+ this.height = this.fullScreen ? win?.innerHeight ?? options.height ?? 500 : options.height ?? 500;
1923
+ const parent = typeof options.parent === "string" ? doc.querySelector(options.parent) : options.parent ?? doc.body;
1924
+ if (!parent)
1925
+ throw new Error('Parent element was not found; try woof({ parent: "#game" }).');
1926
+ this.canvas = doc.createElement("canvas");
1927
+ this.canvas.width = this.width;
1928
+ this.canvas.height = this.height;
1929
+ this.canvas.style.backgroundSize = this.backdrop.size;
1930
+ this.canvas.style.backgroundRepeat = this.backdrop.repeat;
1931
+ const context = this.canvas.getContext("2d");
1932
+ if (!context)
1933
+ throw new Error("A 2D canvas context is required.");
1934
+ this.context = context;
1935
+ parent.appendChild(this.canvas);
1936
+ if (options.backdrop) {
1937
+ if (/^(?:https?:|data:|blob:|\/|\.\.?\/)|\.(?:png|jpe?g|gif|webp|svg)(?:[?#]|$)/i.test(options.backdrop))
1938
+ this.setBackdropURL(options.backdrop);
1939
+ else
1940
+ this.setBackdropColor(options.backdrop);
1941
+ }
1942
+ this.scheduler = new Scheduler(options.onError);
1943
+ this.requestFrame = options.requestFrame ?? win?.requestAnimationFrame?.bind(win);
1944
+ this.cancelFrame = options.cancelFrame ?? win?.cancelAnimationFrame?.bind(win);
1945
+ this.maxDeltaMs = options.maxDeltaMs ?? 100;
1946
+ this.installInput();
1947
+ if (this.global)
1948
+ installProjectGlobals(this, this.win, this.restoreGlobals);
1949
+ if (options.autoStart !== false)
1950
+ this.start();
1951
+ }
1952
+ get minX() {
1953
+ return this.cameraX - this.width / 2;
1954
+ }
1955
+ get maxX() {
1956
+ return this.cameraX + this.width / 2;
1957
+ }
1958
+ get minY() {
1959
+ return this.cameraY - this.height / 2;
1960
+ }
1961
+ get maxY() {
1962
+ return this.cameraY + this.height / 2;
1963
+ }
1964
+ bounds() {
1965
+ return {
1966
+ left: this.minX,
1967
+ right: this.maxX,
1968
+ top: this.maxY,
1969
+ bottom: this.minY
1970
+ };
1971
+ }
1972
+ randomFloat(a, b) {
1973
+ let r;
1974
+ if (this.randomState === undefined)
1975
+ r = Math.random();
1976
+ else {
1977
+ this.randomState = Math.imul(this.randomState, 1664525) + 1013904223 >>> 0;
1978
+ r = this.randomState / 4294967296;
1979
+ }
1980
+ return Math.min(a, b) + r * Math.abs(b - a);
1981
+ }
1982
+ random(a, b) {
1983
+ const min = Math.ceil(Math.min(a, b)), max = Math.floor(Math.max(a, b));
1984
+ if (!Number.isFinite(min) || !Number.isFinite(max) || min > max)
1985
+ throw new RangeError("random needs bounds containing a whole number; try random(1, 6).");
1986
+ return min + Math.floor(this.randomFloat(0, max - min + 1));
1987
+ }
1988
+ randomX() {
1989
+ return this.random(this.minX, this.maxX);
1990
+ }
1991
+ randomY() {
1992
+ return this.random(this.minY, this.maxY);
1993
+ }
1994
+ get freezing() {
1995
+ return this.freezePending;
1996
+ }
1997
+ get woofEpoch() {
1998
+ return new Date(this.timerEpoch);
1999
+ }
2000
+ get renderInterval() {
2001
+ return this.frame;
2002
+ }
2003
+ get stopped() {
2004
+ return !this.running || this.frozen;
2005
+ }
2006
+ ready(fn) {
2007
+ if (typeof fn !== "function")
2008
+ throw new TypeError("ready requires a callback; try ready(() => {}).");
2009
+ this.invoke(fn);
2010
+ }
2011
+ translateToCanvas(x, y) {
2012
+ return [
2013
+ x - this.cameraX + this.width / 2,
2014
+ this.height / 2 - (y - this.cameraY)
2015
+ ];
2016
+ }
2017
+ translateToCenter(x, y) {
2018
+ return [
2019
+ x - this.width / 2 + this.cameraX,
2020
+ this.height / 2 - y + this.cameraY
2021
+ ];
2022
+ }
2023
+ collider() {
2024
+ const b = this.bounds();
2025
+ return {
2026
+ kind: "polygon",
2027
+ points: [
2028
+ { x: b.left, y: b.top },
2029
+ { x: b.left, y: b.bottom },
2030
+ { x: b.right, y: b.bottom },
2031
+ { x: b.right, y: b.top }
2032
+ ]
2033
+ };
2034
+ }
2035
+ setBackdropColor(color) {
2036
+ this.backdrop.color = color;
2037
+ this.backdrop.type = "color";
2038
+ this.canvas.style.backgroundImage = "none";
2039
+ this.canvas.style.backgroundColor = color;
2040
+ return this;
2041
+ }
2042
+ setBackdropURL(url) {
2043
+ this.backdrop.url = url;
2044
+ this.backdrop.type = "url";
2045
+ this.canvas.style.backgroundColor = "";
2046
+ this.canvas.style.backgroundImage = `url(${JSON.stringify(url)})`;
2047
+ return this;
2048
+ }
2049
+ setBackdropSize(width, height) {
2050
+ if (typeof width === "number" && typeof height === "number") {
2051
+ this.width = width;
2052
+ this.height = height;
2053
+ this.canvas.width = width;
2054
+ this.canvas.height = height;
2055
+ } else {
2056
+ this.backdrop.size = height === undefined ? String(width) : `${width} ${height}`;
2057
+ this.canvas.style.backgroundSize = this.backdrop.size;
2058
+ }
2059
+ return this;
2060
+ }
2061
+ setBackdropStyle(style) {
2062
+ this.backdrop.size = style;
2063
+ this.canvas.style.backgroundSize = style;
2064
+ return this;
2065
+ }
2066
+ setBackdropRepeat(repeat) {
2067
+ this.backdrop.repeat = repeat;
2068
+ this.canvas.style.backgroundRepeat = repeat;
2069
+ return this;
2070
+ }
2071
+ scene(name, setup) {
2072
+ this.scenes.set(name, setup);
2073
+ return this;
2074
+ }
2075
+ go(name, data) {
2076
+ const setup = this.scenes.get(name);
2077
+ if (!setup)
2078
+ throw new Error(`Unknown scene: ${name}`);
2079
+ this.scheduler.clear();
2080
+ for (const sound of this.sounds)
2081
+ sound.stopPlaying();
2082
+ this.sounds.clear();
2083
+ for (const s of [...this.sprites])
2084
+ s.delete();
2085
+ this.keyDownHandlers.clear();
2086
+ this.keyUpHandlers.clear();
2087
+ this.pointerDownHandlers.clear();
2088
+ this.pointerUpHandlers.clear();
2089
+ this.pointerMoveHandlers.clear();
2090
+ this.following = undefined;
2091
+ this.clearPen();
2092
+ this.invoke(() => setup(data));
2093
+ return this;
2094
+ }
2095
+ save(key, value) {
2096
+ try {
2097
+ (this.storage ?? this.win?.localStorage)?.setItem(`woof:${key}`, JSON.stringify(value));
2098
+ } catch {}
2099
+ return this;
2100
+ }
2101
+ load(key, fallback) {
2102
+ try {
2103
+ const v = (this.storage ?? this.win?.localStorage)?.getItem(`woof:${key}`);
2104
+ return v == null ? fallback : JSON.parse(v);
2105
+ } catch {
2106
+ return fallback;
2107
+ }
2108
+ }
2109
+ audioContext() {
2110
+ if (!this.audio) {
2111
+ const factory = this.audioFactory;
2112
+ if (factory)
2113
+ this.audio = typeof factory === "function" ? factory() : factory;
2114
+ else {
2115
+ const Ctor = this.win?.AudioContext ?? globalThis.AudioContext;
2116
+ if (!Ctor)
2117
+ throw new Error("AudioContext is unavailable.");
2118
+ this.audio = new Ctor;
2119
+ }
2120
+ }
2121
+ return this.audio;
2122
+ }
2123
+ audioDestination(ctx) {
2124
+ if (!this.master) {
2125
+ this.master = ctx.createGain();
2126
+ this.master.gain.value = this.muted ? 0 : this.volume;
2127
+ this.master.connect(ctx.destination);
2128
+ }
2129
+ return this.master;
2130
+ }
2131
+ get masterVolume() {
2132
+ return this.volume;
2133
+ }
2134
+ set masterVolume(value) {
2135
+ if (!Number.isFinite(value) || value < 0)
2136
+ throw new RangeError("masterVolume must be non-negative.");
2137
+ this.volume = value;
2138
+ if (this.master)
2139
+ this.master.gain.value = this.muted ? 0 : value;
2140
+ }
2141
+ mute() {
2142
+ this.muted = true;
2143
+ if (this.master)
2144
+ this.master.gain.value = 0;
2145
+ return this;
2146
+ }
2147
+ unmute() {
2148
+ this.muted = false;
2149
+ if (this.master)
2150
+ this.master.gain.value = this.volume;
2151
+ return this;
2152
+ }
2153
+ sound(options = {}) {
2154
+ const sound = new ProjectSound2(() => this.audioContext(), (ctx) => this.audioDestination(ctx), this.fetcher, options, (fn) => this.onUpdate(fn));
2155
+ this.sounds.add(sound);
2156
+ return sound;
2157
+ }
2158
+ tone(freq, seconds) {
2159
+ const ctx = this.audioContext(), osc = ctx.createOscillator();
2160
+ osc.frequency.value = freq;
2161
+ osc.connect(this.audioDestination(ctx));
2162
+ osc.start();
2163
+ osc.stop(ctx.currentTime + seconds);
2164
+ return this;
2165
+ }
2166
+ beep() {
2167
+ return this.tone(440, 0.1);
2168
+ }
2169
+ repeat(times, fn, after) {
2170
+ let count = 0, completed = false;
2171
+ const callbacks = after ? [after] : [];
2172
+ const task = this.forever(() => {
2173
+ if (count < Math.floor(times))
2174
+ fn(++count);
2175
+ else {
2176
+ task.stop();
2177
+ completed = true;
2178
+ for (const callback of callbacks.splice(0))
2179
+ this.invoke(() => callback(count));
2180
+ }
2181
+ });
2182
+ const handle = {
2183
+ stop: () => task.stop(),
2184
+ then: (callback) => {
2185
+ if (completed)
2186
+ this.invoke(() => callback(count));
2187
+ else
2188
+ callbacks.push(callback);
2189
+ return handle;
2190
+ }
2191
+ };
2192
+ return handle;
2193
+ }
2194
+ repeatUntil(condition, fn, after) {
2195
+ let count = 0;
2196
+ const h = this.forever(() => {
2197
+ if (condition()) {
2198
+ h.stop();
2199
+ after?.(count);
2200
+ } else
2201
+ fn(++count);
2202
+ });
2203
+ return h;
2204
+ }
2205
+ particles(options = {}) {
2206
+ const out = [];
2207
+ for (let i = 0;i < (options.count ?? 10); i++) {
2208
+ const angle = this.randomFloat(0, Math.PI * 2), speed = options.speed ?? 50;
2209
+ const s = this.circle({
2210
+ x: options.x,
2211
+ y: options.y,
2212
+ radius: options.radius ?? 2,
2213
+ color: options.color,
2214
+ vx: Math.cos(angle) * speed,
2215
+ vy: Math.sin(angle) * speed
2216
+ });
2217
+ out.push(s);
2218
+ this.after(options.life ?? 1, () => s.delete());
2219
+ }
2220
+ return out;
2221
+ }
2222
+ timer() {
2223
+ return this.elapsed;
2224
+ }
2225
+ resetTimer() {
2226
+ this.elapsed = 0;
2227
+ this.timerEpoch = Date.now();
2228
+ return this;
2229
+ }
2230
+ after(time, unitsOrFn, fn) {
2231
+ return this.scheduler.after(typeof unitsOrFn === "string" ? () => duration(time, unitsOrFn) : time, typeof unitsOrFn === "function" ? unitsOrFn : fn);
2232
+ }
2233
+ every(time, unitsOrFn, fn) {
2234
+ return this.scheduler.every(typeof unitsOrFn === "string" ? () => duration(time, unitsOrFn) : time, typeof unitsOrFn === "function" ? unitsOrFn : fn);
2235
+ }
2236
+ forever(fn) {
2237
+ return this.scheduler.forever(fn);
2238
+ }
2239
+ when(condition, fn) {
2240
+ return this.scheduler.when(condition, fn);
2241
+ }
2242
+ once(condition, fn) {
2243
+ return this.scheduler.once(condition, fn);
2244
+ }
2245
+ wait(seconds) {
2246
+ return new Promise((resolve) => {
2247
+ this.after(seconds, resolve);
2248
+ });
2249
+ }
2250
+ freeze() {
2251
+ if (!this.frozen) {
2252
+ this.freezePending = true;
2253
+ try {
2254
+ this.frozen = true;
2255
+ } finally {
2256
+ this.freezePending = false;
2257
+ }
2258
+ }
2259
+ return this;
2260
+ }
2261
+ defrost() {
2262
+ this.frozen = false;
2263
+ this.previous = undefined;
2264
+ return this;
2265
+ }
2266
+ step(ms) {
2267
+ if (!Number.isFinite(ms) || ms < 0)
2268
+ throw new RangeError("step requires non-negative milliseconds; try step(16).");
2269
+ this.elapsed += ms / 1000;
2270
+ this.frameKeys = this.pendingKeys;
2271
+ this.pendingKeys = new Set;
2272
+ this.mouseSpeedX = this.mouseX - this.pMouseX;
2273
+ this.mouseSpeedY = this.mouseY - this.pMouseY;
2274
+ this.scheduler.step(ms / 1000);
2275
+ if (this.following && !this.following.sprite.deleted) {
2276
+ const { sprite, smoothing } = this.following;
2277
+ const t = Math.max(0, Math.min(1, smoothing));
2278
+ this.cameraX += (sprite.x - this.cameraX) * t;
2279
+ this.cameraY += (sprite.y - this.cameraY) * t;
2280
+ }
2281
+ if (this.shakeTime > 0)
2282
+ this.shakeTime = Math.max(0, this.shakeTime - ms / 1000);
2283
+ for (const sprite of [...this.sprites])
2284
+ if (!sprite.deleted)
2285
+ sprite.advance(ms / 1000);
2286
+ this.render();
2287
+ this.pMouseX = this.mouseX;
2288
+ this.pMouseY = this.mouseY;
2289
+ this.frameKeys.clear();
2290
+ return this;
2291
+ }
2292
+ tick = (timestamp) => {
2293
+ if (!this.running)
2294
+ return;
2295
+ const delta = this.previous === undefined ? 0 : Math.min(this.maxDeltaMs, Math.max(0, timestamp - this.previous));
2296
+ this.previous = timestamp;
2297
+ if (!this.frozen)
2298
+ this.step(delta);
2299
+ if (this.running)
2300
+ this.frame = this.requestFrame?.(this.tick);
2301
+ };
2302
+ start() {
2303
+ if (this.destroyed)
2304
+ throw new Error("Cannot start a destroyed project.");
2305
+ if (!this.running) {
2306
+ if (!this.requestFrame)
2307
+ throw new Error("requestAnimationFrame is unavailable; provide requestFrame or autoStart: false.");
2308
+ this.running = true;
2309
+ this.previous = undefined;
2310
+ this.frame = this.requestFrame(this.tick);
2311
+ }
2312
+ return this;
2313
+ }
2314
+ stop() {
2315
+ this.running = false;
2316
+ if (this.frame !== undefined)
2317
+ this.cancelFrame?.(this.frame);
2318
+ this.frame = undefined;
2319
+ this.previous = undefined;
2320
+ return this;
2321
+ }
2322
+ invoke(fn) {
2323
+ try {
2324
+ fn();
2325
+ } catch (error) {
2326
+ this.reportError(error);
2327
+ }
2328
+ }
2329
+ createImage() {
2330
+ return this.doc.createElement("img");
2331
+ }
2332
+ createSprite(type, options = {}) {
2333
+ if (this.destroyed)
2334
+ throw new Error("Cannot create a sprite in a destroyed project.");
2335
+ const s = new Sprite2(this, type, options);
2336
+ this.sprites.push(s);
2337
+ return s;
2338
+ }
2339
+ customSprite(definition) {
2340
+ return createCustomSprite(this, definition);
2341
+ }
2342
+ circle(o = {}) {
2343
+ return this.createSprite("circle", o);
2344
+ }
2345
+ rectangle(o = {}) {
2346
+ return this.createSprite("rectangle", o);
2347
+ }
2348
+ oval(o = {}) {
2349
+ return this.createSprite("oval", o);
2350
+ }
2351
+ polygon(o = {}) {
2352
+ return this.createSprite("polygon", o);
2353
+ }
2354
+ line(o = {}) {
2355
+ return this.createSprite("line", o);
2356
+ }
2357
+ text(o = {}) {
2358
+ return this.createSprite("text", o);
2359
+ }
2360
+ image(o = {}) {
2361
+ return this.createSprite("image", o);
2362
+ }
2363
+ bundle(o = {}) {
2364
+ return this.createSprite("bundle", o);
2365
+ }
2366
+ sprite(o = {}) {
2367
+ return this.createSprite("sprite", o);
2368
+ }
2369
+ removeSprite(sprite) {
2370
+ const i = this.sprites.indexOf(sprite);
2371
+ if (i >= 0)
2372
+ this.sprites.splice(i, 1);
2373
+ }
2374
+ find(tag) {
2375
+ return this.sprites.filter((s) => s.tags.includes(tag));
2376
+ }
2377
+ onUpdate(fn) {
2378
+ let previous = this.elapsed;
2379
+ return this.forever(() => {
2380
+ const dt = this.elapsed - previous;
2381
+ previous = this.elapsed;
2382
+ fn(dt);
2383
+ });
2384
+ }
2385
+ preciseCollision(a, b) {
2386
+ return preciseCollision(this, this.doc, a, b);
2387
+ }
2388
+ trackPen(x1, y1, x2, y2, active, color, width) {
2389
+ if (active && (x1 !== x2 || y1 !== y2))
2390
+ this.pen.push({ x1, y1, x2, y2, color, width });
2391
+ }
2392
+ clearPen() {
2393
+ this.pen = [];
2394
+ return this;
2395
+ }
2396
+ render() {
2397
+ renderWorld(this, this.pen, this.shakeTime > 0 ? this.shakeStrength : undefined);
2398
+ }
2399
+ key(key) {
2400
+ return this.keysDown.has(normalizeKey(key));
2401
+ }
2402
+ keyPressed(key) {
2403
+ const k = normalizeKey(key);
2404
+ return this.frameKeys.has(k) || this.pendingKeys.has(k);
2405
+ }
2406
+ onKeyDown(fn) {
2407
+ this.keyDownHandlers.add(fn);
2408
+ return () => this.keyDownHandlers.delete(fn);
2409
+ }
2410
+ onKeyUp(fn) {
2411
+ this.keyUpHandlers.add(fn);
2412
+ return () => this.keyUpHandlers.delete(fn);
2413
+ }
2414
+ onMouseDown(fn) {
2415
+ this.pointerDownHandlers.add(fn);
2416
+ return () => this.pointerDownHandlers.delete(fn);
2417
+ }
2418
+ onMouseUp(fn) {
2419
+ this.pointerUpHandlers.add(fn);
2420
+ return () => this.pointerUpHandlers.delete(fn);
2421
+ }
2422
+ onMouseMove(fn) {
2423
+ this.pointerMoveHandlers.add(fn);
2424
+ return () => this.pointerMoveHandlers.delete(fn);
2425
+ }
2426
+ get mouseXSpeed() {
2427
+ return this.mouseSpeedX;
2428
+ }
2429
+ get mouseYSpeed() {
2430
+ return this.mouseSpeedY;
2431
+ }
2432
+ gamepad(index = 0) {
2433
+ return this.win?.navigator?.getGamepads?.()[index] ?? null;
2434
+ }
2435
+ installInput() {
2436
+ const listen = (target, type, fn) => {
2437
+ if (!target?.addEventListener)
2438
+ return;
2439
+ target.addEventListener(type, fn);
2440
+ this.listeners.push(() => target.removeEventListener(type, fn));
2441
+ };
2442
+ listen(this.win, "keydown", (event) => {
2443
+ const k = normalizeKey(event.code || event.key);
2444
+ if (!this.keysDown.has(k)) {
2445
+ this.keysDown.add(k);
2446
+ this.pendingKeys.add(k);
2447
+ for (const fn of this.keyDownHandlers)
2448
+ this.invoke(() => fn(k));
2449
+ }
2450
+ });
2451
+ listen(this.win, "keyup", (event) => {
2452
+ const k = normalizeKey(event.code || event.key);
2453
+ this.keysDown.delete(k);
2454
+ for (const fn of this.keyUpHandlers)
2455
+ this.invoke(() => fn(k));
2456
+ });
2457
+ listen(this.win, "blur", () => {
2458
+ this.keysDown.clear();
2459
+ this.pendingKeys.clear();
2460
+ this.frameKeys.clear();
2461
+ this.mouseDown = false;
2462
+ });
2463
+ const activePointers = new Set;
2464
+ const pointer = (kind) => (event) => {
2465
+ const id = event.pointerId ?? 0;
2466
+ if ((kind === "up" || kind === "cancel") && !activePointers.has(id))
2467
+ return;
2468
+ const rect = this.canvas.getBoundingClientRect();
2469
+ if (!rect.width || !rect.height)
2470
+ return;
2471
+ this.mouseX = (event.clientX - rect.left) * this.width / rect.width - this.width / 2 + this.cameraX;
2472
+ this.mouseY = this.height / 2 - (event.clientY - rect.top) * this.height / rect.height + this.cameraY;
2473
+ if (kind === "down") {
2474
+ activePointers.add(id);
2475
+ this.canvas.setPointerCapture?.(id);
2476
+ }
2477
+ if (kind === "up" || kind === "cancel")
2478
+ activePointers.delete(id);
2479
+ this.mouseDown = activePointers.size > 0;
2480
+ const handlers = kind === "down" ? this.pointerDownHandlers : kind === "move" ? this.pointerMoveHandlers : this.pointerUpHandlers;
2481
+ for (const fn of handlers)
2482
+ this.invoke(() => fn(this.mouseX, this.mouseY));
2483
+ if (kind !== "move")
2484
+ for (const sprite of [...this.sprites])
2485
+ sprite.pointer(kind === "down" ? "down" : "up", this.mouseX, this.mouseY, id, kind === "cancel");
2486
+ };
2487
+ listen(this.canvas, "pointerdown", pointer("down"));
2488
+ listen(this.canvas, "pointermove", pointer("move"));
2489
+ listen(this.win ?? this.canvas, "pointerup", pointer("up"));
2490
+ listen(this.win ?? this.canvas, "pointercancel", pointer("cancel"));
2491
+ if (this.win) {
2492
+ listen(this.canvas, "pointerup", pointer("up"));
2493
+ listen(this.canvas, "pointercancel", pointer("cancel"));
2494
+ }
2495
+ }
2496
+ destroy() {
2497
+ if (this.destroyed)
2498
+ return;
2499
+ this.stop();
2500
+ for (const sound of this.sounds)
2501
+ sound.stopPlaying();
2502
+ this.sounds.clear();
2503
+ this.audio?.close();
2504
+ this.scheduler.clear();
2505
+ for (const off of this.listeners)
2506
+ off();
2507
+ this.listeners = [];
2508
+ for (const sprite of [...this.sprites])
2509
+ sprite.delete();
2510
+ this.keysDown.clear();
2511
+ this.pendingKeys.clear();
2512
+ this.frameKeys.clear();
2513
+ this.mouseDown = false;
2514
+ this.keyDownHandlers.clear();
2515
+ this.keyUpHandlers.clear();
2516
+ this.pointerDownHandlers.clear();
2517
+ this.pointerUpHandlers.clear();
2518
+ this.pointerMoveHandlers.clear();
2519
+ this.scenes.clear();
2520
+ this.following = undefined;
2521
+ this.clearPen();
2522
+ this.canvas.remove();
2523
+ for (const restore of this.restoreGlobals.reverse())
2524
+ restore();
2525
+ this.restoreGlobals = [];
2526
+ this.destroyed = true;
2527
+ }
2528
+ }
2529
+ function woof2(options = {}) {
2530
+ return new Project2(options);
2531
+ }
2532
+
2533
+ export { clamp2, lerp2, distance2, between2, remove2, randomFloat2, random2, pick2, shuffle2, range2, rgb2, randomColor2, RIGHT2, LEFT2, UP2, DOWN2, sin2, cos2, tan2, asin2, acos2, atan2, sqrt2, abs2, floor2, ceiling2, ln2, log2, pow2, hourMilitary2, hour2, minute2, second2, dayOfMonth2, dayOfWeek2, month2, year2, mobile2, importCodeURL2, extend2, months2, keyCodeToString2, unitsToMiliseconds2, throttle2, getData2, arrayToString2, easings2, Sprite2, ProjectSound2, Repeat2, RepeatUntil2, Project2, woof2 };