create-dreamer-app 1.0.12 → 1.0.13
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Disco Dreamer reference
|
|
2
2
|
|
|
3
|
-
A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.0.
|
|
3
|
+
A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.0.10 and TypeScript with JSX.
|
|
4
4
|
|
|
5
5
|
## How a game runs
|
|
6
6
|
|
|
@@ -100,7 +100,7 @@ setScore((previous) => previous + 1);
|
|
|
100
100
|
const [score] = gameState("$score", 0); // Reads the incremented score.
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
The first call initializes the shared slot; later calls do not reset it. Literal keys do not advance or reset ordinary-key numbering. The `$` rule is implemented in `gameState`, so helpers that call it internally also inherit it. Use ordinary keys for those helpers, especially `gameAnimation`, which
|
|
103
|
+
The first call initializes the shared slot; later calls do not reset it. Literal keys do not advance or reset ordinary-key numbering. The `$` rule is implemented in `gameState`, so helpers that call it internally also inherit it. Use ordinary keys for those helpers, especially `gameAnimation` and `gameInterval`, which each need multiple numbered slots for a single key. Hooks that resolve keys directly, such as `gameEffect`, retain normal numbering.
|
|
104
104
|
|
|
105
105
|
State that is no longer used is removed during frame cleanup. This also applies to `$` keys: sharing a slot does not make it permanent. If an entity disappears for a frame and returns later, expect its state to initialize again.
|
|
106
106
|
|
|
@@ -424,6 +424,126 @@ Returns the canvas's current CSS size as `{ width, height }`. Use this for respo
|
|
|
424
424
|
const { width, height } = gameViewport();
|
|
425
425
|
```
|
|
426
426
|
|
|
427
|
+
## Asynchronous operations
|
|
428
|
+
|
|
429
|
+
### `gameAsync(promise)`
|
|
430
|
+
|
|
431
|
+
Starts an asynchronous operation and returns a typed string ID. Pass a function returning a promise, rather than an already-started promise. The function is invoked in a microtask after the current synchronous code finishes. Both synchronous throws from that function and promise rejections are recorded as failures.
|
|
432
|
+
|
|
433
|
+
Call `gameAsync` when you want to start an operation, such as inside an input handler or an effect. Each call starts a new operation and returns a fresh ID. Store the ID across frames; starting the operation unconditionally in the root function would start it again every frame.
|
|
434
|
+
|
|
435
|
+
### `gameAsyncThen(id, handler)`, `gameAsyncCatch(id, handler)`, and `gameAsyncFinally(id, handler)`
|
|
436
|
+
|
|
437
|
+
Call these each frame to check the operation identified by the ID. They invoke handlers immediately when a matching completion is available; they do not install persistent listeners or return promises.
|
|
438
|
+
|
|
439
|
+
| Hook | Handler argument | When it runs |
|
|
440
|
+
| --- | --- | --- |
|
|
441
|
+
| `gameAsyncThen` | Resolved value, with its inferred type | Success |
|
|
442
|
+
| `gameAsyncCatch` | Rejection reason or thrown value, typed as `unknown` | Failure |
|
|
443
|
+
| `gameAsyncFinally` | None | Success or failure |
|
|
444
|
+
|
|
445
|
+
Completions are buffered and become available at the start of the next animation frame after settlement. Each completion is available for that one frame only. Every matching hook call in that frame can read it; reading does not consume it. If a matching hook is not called during that frame, it misses the completion.
|
|
446
|
+
|
|
447
|
+
Handlers run within the synchronous game frame and can use values captured from that frame, rather than the frame when the operation started. The result itself still belongs to the original operation. Watching only the current request ID lets you ignore results from superseded requests; it does not cancel those requests.
|
|
448
|
+
|
|
449
|
+
```tsx
|
|
450
|
+
function LoadedMessage() {
|
|
451
|
+
const [, setMessage, getMessage] = gameState("message.text", "Loading...");
|
|
452
|
+
const [, setRequest, getRequest] = gameState<{
|
|
453
|
+
id: ReturnType<typeof gameAsync<string>> | null;
|
|
454
|
+
}>("message.request", { id: null });
|
|
455
|
+
|
|
456
|
+
gameEffect("message.load", () => {
|
|
457
|
+
const id = gameAsync(async () => {
|
|
458
|
+
const response = await fetch("/message.txt");
|
|
459
|
+
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
|
|
460
|
+
return response.text();
|
|
461
|
+
});
|
|
462
|
+
setRequest({ id });
|
|
463
|
+
}, []);
|
|
464
|
+
|
|
465
|
+
const requestId = getRequest().id;
|
|
466
|
+
if (requestId !== null) {
|
|
467
|
+
gameAsyncThen(requestId, message => {
|
|
468
|
+
// message is inferred as string from the producer's return type.
|
|
469
|
+
setMessage(message);
|
|
470
|
+
});
|
|
471
|
+
gameAsyncCatch(requestId, error => {
|
|
472
|
+
setMessage(error instanceof Error ? error.message : "Could not load message.");
|
|
473
|
+
});
|
|
474
|
+
gameAsyncFinally(requestId, () => setRequest({ id: null }));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return <Text value={getMessage()} />;
|
|
478
|
+
}
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
The ID retains the resolved value's type for `gameAsyncThen`; widening it to plain `string` loses that connection. `AsyncId` is not a public named type export from `discodreamer`. Let IDs be inferred, or use `ReturnType<typeof gameAsync<ResultType>>` when declaring a type that stores an ID. When storing an ID in `gameState`, wrap it in an object as shown: the state's shallow `Readonly` return type then preserves the ID's string compatibility and result type. Rejection reasons remain `unknown` and should be narrowed before use. These hooks do not cancel operations or expose a pending status; native promises can also be used directly when frame-based delivery is not needed.
|
|
482
|
+
|
|
483
|
+
## Timer hooks
|
|
484
|
+
|
|
485
|
+
Timers use wall-clock milliseconds and invoke handlers synchronously when `when` is called. They do not schedule browser timer callbacks. Call the hook and its returned `when` function each frame, and call `start` only when you want to start or restart the timer. Keep each hook's key stable to preserve its state across frames. Timer state is removed by the normal state cleanup when the hook is no longer used.
|
|
486
|
+
|
|
487
|
+
### `gameTimeOut(key)`
|
|
488
|
+
|
|
489
|
+
Returns the readonly tuple `[start, when, clear, timeRemaining]`.
|
|
490
|
+
|
|
491
|
+
| Function | Behavior |
|
|
492
|
+
| --- | --- |
|
|
493
|
+
| `start(duration)` | Sets a deadline `duration` milliseconds from now, replacing any previous deadline |
|
|
494
|
+
| `when(handler, autoClear = true)` | Calls `handler()` if the deadline has been reached |
|
|
495
|
+
| `clear()` | Makes the timeout inactive |
|
|
496
|
+
| `timeRemaining()` | Returns milliseconds until the deadline, clamped to `0`, or `null` when inactive |
|
|
497
|
+
|
|
498
|
+
The timeout starts inactive. By default, `when` clears it before calling the handler, so it fires once and the handler can safely restart it. With `autoClear: false`, it stays expired and every subsequent `when` call fires until it is cleared or restarted, including repeated calls in the same frame. A later firing with `autoClear: true` also clears it.
|
|
499
|
+
|
|
500
|
+
`start`, `clear`, and `timeRemaining` use live stored state, so changes are visible to subsequent calls in the same frame. A zero or negative duration is already due on the next `when` call, which can be in that same frame. A timeout that expires between frames is handled on the first subsequent call to `when`.
|
|
501
|
+
|
|
502
|
+
```ts
|
|
503
|
+
const [startTimeout, whenTimeout, clearTimeout, timeRemaining] =
|
|
504
|
+
gameTimeOut("notice.timeout");
|
|
505
|
+
|
|
506
|
+
gameEvent("keyDown", ({ key }) => {
|
|
507
|
+
if (key === "n") startTimeout(2000);
|
|
508
|
+
if (key === "Escape") clearTimeout();
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
whenTimeout(() => sendMessage("notice.expired", null));
|
|
512
|
+
const remaining = timeRemaining(); // number | null
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
### `gameInterval(key)`
|
|
516
|
+
|
|
517
|
+
Returns the readonly tuple `[start, when, clear]`.
|
|
518
|
+
|
|
519
|
+
| Function | Behavior |
|
|
520
|
+
| --- | --- |
|
|
521
|
+
| `start(duration)` | Starts or restarts with a new duration and resets the run index to `0` |
|
|
522
|
+
| `when(handler)` | Calls `handler(run)` once for each tick due since the previous check |
|
|
523
|
+
| `clear()` | Stops the interval and resets its run count |
|
|
524
|
+
|
|
525
|
+
The interval starts inactive. Durations must be finite and greater than zero; otherwise `start` throws without replacing the current interval. The first tick is due after one full duration, with a zero-based run index: `0`, `1`, `2`, and so on.
|
|
526
|
+
|
|
527
|
+
Missed ticks are delivered together on the next `when` call. For example, an interval started with `1000` milliseconds and first checked after `3500` milliseconds calls the handler with `0`, `1`, and `2`. A second check at the same time does not repeat those ticks. Timing stays anchored to the start time rather than being reset after each check.
|
|
528
|
+
|
|
529
|
+
If a handler clears or restarts the interval, the remaining callbacks from the old batch stop. Restarting also resets numbering, including when the duration and start timestamp match the previous interval. After a long pause, catch-up can run many callbacks in one frame. Wall-clock timers continue to age while frames are suspended; they are not automatically paused with game logic.
|
|
530
|
+
|
|
531
|
+
```ts
|
|
532
|
+
const [startInterval, whenInterval, clearInterval] =
|
|
533
|
+
gameInterval("enemy.spawn.interval");
|
|
534
|
+
|
|
535
|
+
gameEffect("enemy.spawn.start", () => startInterval(1000), []);
|
|
536
|
+
|
|
537
|
+
gameEvent("keyDown", ({ key }) => {
|
|
538
|
+
if (key === "p") clearInterval();
|
|
539
|
+
if (key === "r") startInterval(1000);
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
whenInterval(run => sendMessage("enemy.spawn", { run }));
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
Use an ordinary key for `gameInterval`, not a `$` literal key: the interval stores several independent numbered state slots under that key.
|
|
546
|
+
|
|
427
547
|
## Animation and image hooks
|
|
428
548
|
|
|
429
549
|
### `gameAnimation(key, animations, config)`
|