@maco-online/shuttle-blitz-rules 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 maco-online contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ import type { RoomGameDefinition } from '@maco-online/online-core';
2
+ import type { InputFrame, SnapshotMessage } from './net/wire.ts';
3
+ import { z } from 'zod';
4
+ import { ShuttleRoomMatch } from './room-match.ts';
5
+ /** A quick match has nothing to choose before it starts. */
6
+ declare const settingsSchema: z.ZodObject<{}, z.core.$strict>;
7
+ /** Both sides play with the same stats and look, so a player sends nothing about themselves. */
8
+ declare const profileSchema: z.ZodObject<{}, z.core.$strict>;
9
+ export type ShuttleSettings = z.infer<typeof settingsSchema>;
10
+ export type ShuttleProfile = z.infer<typeof profileSchema>;
11
+ export type ShuttleBlitzDefinition = RoomGameDefinition<InputFrame, ShuttleSettings, ShuttleProfile, SnapshotMessage, ShuttleRoomMatch>;
12
+ /**
13
+ * Shuttle Blitz online: a public quick match of two players. The room starts it a moment after the second player
14
+ * arrives and closes once it is over, so there is no host and no rematch. Every member gets the same snapshot; each
15
+ * browser words the banners for its own side.
16
+ */
17
+ export declare const shuttleBlitzDefinition: ShuttleBlitzDefinition;
18
+ export {};
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { ACTION_MASK, mergeFrames, ONLINE_PROTOCOL, ONLINE_TICK_RATE, SNAPSHOT_EVERY } from "./net/wire.js";
3
+ import { ShuttleRoomMatch } from "./room-match.js";
4
+ const actionMask = z.int().min(0).max(ACTION_MASK);
5
+ const inputSchema = z.strictObject({ held: actionMask, pressed: actionMask, released: actionMask });
6
+ /** A quick match has nothing to choose before it starts. */
7
+ const settingsSchema = z.strictObject({});
8
+ /** Both sides play with the same stats and look, so a player sends nothing about themselves. */
9
+ const profileSchema = z.strictObject({});
10
+ /**
11
+ * Shuttle Blitz online: a public quick match of two players. The room starts it a moment after the second player
12
+ * arrives and closes once it is over, so there is no host and no rematch. Every member gets the same snapshot; each
13
+ * browser words the banners for its own side.
14
+ */
15
+ export const shuttleBlitzDefinition = {
16
+ id: 'shuttle-blitz',
17
+ protocolVersion: ONLINE_PROTOCOL,
18
+ visibility: 'public',
19
+ maxMembers: 2,
20
+ tickRate: ONLINE_TICK_RATE,
21
+ stateEvery: SNAPSHOT_EVERY,
22
+ // The client counts it down as "MATCH STARTS IN 3".
23
+ autoStart: { countdownMs: 3000 },
24
+ afterMatch: 'close',
25
+ idleInput: { held: 0, pressed: 0, released: 0 },
26
+ // Several frames in one tick keep every press and release, and the newest held keys.
27
+ mergeInput: (pending, next) => mergeFrames([pending, next]),
28
+ // A quiet connection keeps holding its keys, but never presses or releases one twice.
29
+ holdInput: latest => ({ held: latest.held, pressed: 0, released: 0 }),
30
+ inputSchema,
31
+ settingsSchema,
32
+ profileSchema,
33
+ defaultSettings: () => ({}),
34
+ defaultProfile: () => ({}),
35
+ createMatch: (_, members) => new ShuttleRoomMatch(members)
36
+ };
@@ -0,0 +1,3 @@
1
+ export type { ShuttleBlitzDefinition, ShuttleProfile, ShuttleSettings } from './definition.ts';
2
+ export { shuttleBlitzDefinition } from './definition.ts';
3
+ export { ShuttleRoomMatch } from './room-match.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { shuttleBlitzDefinition } from "./definition.js";
2
+ export { ShuttleRoomMatch } from "./room-match.js";
@@ -0,0 +1,65 @@
1
+ import type { SimEvent } from '../sim/events.ts';
2
+ import type { SimInput } from '../sim/match.ts';
3
+ import type { MatchState } from '../sim/state.ts';
4
+ import type { ActionId, Side } from '../sim/types.ts';
5
+ /** Bump when a client and a room can no longer talk to each other; the room refuses a client that sends another one. */
6
+ export declare const ONLINE_PROTOCOL = 1;
7
+ /** The room's name on the Colyseus server. */
8
+ export declare const ONLINE_ROOM = "shuttle-blitz";
9
+ /** Simulation and input rate in Hz: one input frame advances the match exactly one step. */
10
+ export declare const ONLINE_TICK_RATE = 120;
11
+ export declare const ONLINE_STEP: number;
12
+ /** The room sends a snapshot every this many steps (30 Hz). */
13
+ export declare const SNAPSHOT_EVERY = 4;
14
+ export declare const SNAPSHOT_INTERVAL_MS: number;
15
+ /** Message names of the room. */
16
+ export declare const MSG_SNAPSHOT = "snap";
17
+ export declare const MSG_END = "end";
18
+ export type OnlinePhase = 'waiting' | 'countdown' | 'playing' | 'over';
19
+ export type EndReason = 'finished' | 'forfeit';
20
+ export declare const ACTION_BITS: Readonly<Record<ActionId, number>>;
21
+ export declare const ACTION_MASK = 127;
22
+ /** One input step as it travels: three bitmasks of `ACTION_BITS`. */
23
+ export interface InputFrame {
24
+ held: number;
25
+ pressed: number;
26
+ released: number;
27
+ }
28
+ export declare function encodeActions(actions: Iterable<ActionId>): number;
29
+ export declare function decodeActions(mask: number): ActionId[];
30
+ export declare function frameOf(input: SimInput): InputFrame;
31
+ export declare function simInputOf(frame: InputFrame): SimInput;
32
+ /** Folds several steps into one without losing an edge: the newest `held`, every press and release. */
33
+ export declare function mergeFrames(frames: readonly InputFrame[]): InputFrame;
34
+ /** A simulation event and the room tick it happened on, so a client can play it when its picture reaches that tick. */
35
+ export interface TimedEvent {
36
+ tick: number;
37
+ event: SimEvent;
38
+ }
39
+ /** What the room broadcasts: the whole simulation state, stamped with the tick it belongs to, and the events since. */
40
+ export interface SnapshotMessage {
41
+ tick: number;
42
+ state: MatchState;
43
+ events?: TimedEvent[];
44
+ }
45
+ export interface EndMessage {
46
+ winner: Side;
47
+ reason: EndReason;
48
+ score: {
49
+ p: number;
50
+ ai: number;
51
+ };
52
+ games: {
53
+ p: number;
54
+ ai: number;
55
+ };
56
+ }
57
+ /** A snapshot message for `state`: a copy without the solo-only parts (AI brain, training) and with trimmed floats. */
58
+ export declare function snapshotOf(state: Readonly<MatchState>, tick: number, events?: readonly TimedEvent[]): SnapshotMessage;
59
+ /**
60
+ * The simulation words its banners from the left player's point of view ("YOUR SERVE", "POINT!"). For the right
61
+ * player the wording and the side colour flip, so each browser reads its own match. Other events are unchanged.
62
+ */
63
+ export declare function eventForViewer(event: SimEvent, viewer: Side): SimEvent;
64
+ /** True when `value` has the shape the renderer reads; a malformed message never reaches Phaser. */
65
+ export declare function isSnapshot(value: unknown): value is SnapshotMessage;
@@ -0,0 +1,108 @@
1
+ /** Bump when a client and a room can no longer talk to each other; the room refuses a client that sends another one. */
2
+ export const ONLINE_PROTOCOL = 1;
3
+ /** The room's name on the Colyseus server. */
4
+ export const ONLINE_ROOM = 'shuttle-blitz';
5
+ /** Simulation and input rate in Hz: one input frame advances the match exactly one step. */
6
+ export const ONLINE_TICK_RATE = 120;
7
+ export const ONLINE_STEP = 1 / ONLINE_TICK_RATE;
8
+ /** The room sends a snapshot every this many steps (30 Hz). */
9
+ export const SNAPSHOT_EVERY = 4;
10
+ export const SNAPSHOT_INTERVAL_MS = (1000 * SNAPSHOT_EVERY) / ONLINE_TICK_RATE;
11
+ /** Message names of the room. */
12
+ export const MSG_SNAPSHOT = 'snap';
13
+ export const MSG_END = 'end';
14
+ export const ACTION_BITS = {
15
+ left: 1,
16
+ right: 2,
17
+ jump: 4,
18
+ clear: 8,
19
+ drop: 16,
20
+ smash: 32,
21
+ cross: 64,
22
+ };
23
+ export const ACTION_MASK = 127;
24
+ const ACTION_LIST = Object.keys(ACTION_BITS);
25
+ export function encodeActions(actions) {
26
+ let mask = 0;
27
+ for (const action of actions)
28
+ mask |= ACTION_BITS[action] ?? 0;
29
+ return mask;
30
+ }
31
+ export function decodeActions(mask) {
32
+ return ACTION_LIST.filter(action => (mask & ACTION_BITS[action]) !== 0);
33
+ }
34
+ export function frameOf(input) {
35
+ return { held: encodeActions(input.held), pressed: encodeActions(input.pressed), released: encodeActions(input.released) };
36
+ }
37
+ export function simInputOf(frame) {
38
+ return { held: new Set(decodeActions(frame.held)), pressed: decodeActions(frame.pressed), released: decodeActions(frame.released) };
39
+ }
40
+ /** Folds several steps into one without losing an edge: the newest `held`, every press and release. */
41
+ export function mergeFrames(frames) {
42
+ const merged = { held: 0, pressed: 0, released: 0 };
43
+ for (const frame of frames) {
44
+ merged.held = frame.held;
45
+ merged.pressed |= frame.pressed;
46
+ merged.released |= frame.released;
47
+ }
48
+ return merged;
49
+ }
50
+ const round = (value) => Math.round(value * 1000) / 1000;
51
+ function compact(value) {
52
+ if (typeof value === 'number')
53
+ return Number.isInteger(value) ? value : round(value);
54
+ if (Array.isArray(value))
55
+ return value.map(compact);
56
+ if (value && typeof value === 'object') {
57
+ const out = {};
58
+ for (const [key, item] of Object.entries(value))
59
+ out[key] = compact(item);
60
+ return out;
61
+ }
62
+ return value;
63
+ }
64
+ /** A snapshot message for `state`: a copy without the solo-only parts (AI brain, training) and with trimmed floats. */
65
+ export function snapshotOf(state, tick, events = []) {
66
+ const { train: _train, ...rest } = state;
67
+ const copy = compact(rest);
68
+ copy.p.brain = null;
69
+ if (copy.ai)
70
+ copy.ai.brain = null;
71
+ return { tick, state: { ...copy, train: null }, ...(events.length ? { events: compact(events) } : {}) };
72
+ }
73
+ const PERSPECTIVE_SWAP = {
74
+ 'banner.yourServe': 'banner.oppServe',
75
+ 'banner.oppServe': 'banner.yourServe',
76
+ 'banner.yourServeHint': 'banner.oppServeHint',
77
+ 'banner.oppServeHint': 'banner.yourServeHint',
78
+ 'banner.pointWon': 'banner.pointLost',
79
+ 'banner.pointLost': 'banner.pointWon',
80
+ 'banner.matchWon': 'banner.matchLost',
81
+ 'banner.matchLost': 'banner.matchWon',
82
+ 'banner.gameWon': 'banner.gameLost',
83
+ 'banner.gameLost': 'banner.gameWon',
84
+ };
85
+ /**
86
+ * The simulation words its banners from the left player's point of view ("YOUR SERVE", "POINT!"). For the right
87
+ * player the wording and the side colour flip, so each browser reads its own match. Other events are unchanged.
88
+ */
89
+ export function eventForViewer(event, viewer) {
90
+ if (viewer === 'p' || event.type !== 'banner')
91
+ return event;
92
+ return {
93
+ ...event,
94
+ key: PERSPECTIVE_SWAP[event.key] ?? event.key,
95
+ sub: event.sub === undefined ? undefined : (PERSPECTIVE_SWAP[event.sub] ?? event.sub),
96
+ side: event.side === 'p' ? 'ai' : 'p',
97
+ };
98
+ }
99
+ /** True when `value` has the shape the renderer reads; a malformed message never reaches Phaser. */
100
+ export function isSnapshot(value) {
101
+ if (!value || typeof value !== 'object')
102
+ return false;
103
+ const message = value;
104
+ const state = message.state;
105
+ return typeof message.tick === 'number' && !!state && typeof state === 'object'
106
+ && !!state.p && !!state.ai && !!state.shuttle && !!state.score && typeof state.phase === 'string'
107
+ && (message.events === undefined || Array.isArray(message.events));
108
+ }
@@ -0,0 +1,26 @@
1
+ import type { RoomMatch, RoomMatchMember } from '@maco-online/online-core';
2
+ import type { EndMessage, InputFrame, SnapshotMessage } from './net/wire.ts';
3
+ /**
4
+ * One online Shuttle Blitz match, run by the room one tick at a time. Slot 0 plays the left side (`p`) and slot 1
5
+ * the right side (`ai`). Each tick is one step of real time; the simulation's own slow motion scales it, as the solo
6
+ * game does, so a decisive moment plays slower on both screens.
7
+ */
8
+ export declare class ShuttleRoomMatch implements RoomMatch<InputFrame, SnapshotMessage> {
9
+ private readonly match;
10
+ private tick;
11
+ /** Events since the previous state, stamped with the tick they happened on. */
12
+ private events;
13
+ private outcome;
14
+ constructor(members: readonly RoomMatchMember<unknown>[], seed?: number);
15
+ get over(): boolean;
16
+ step(inputs: ReadonlyMap<number, InputFrame>): void;
17
+ state(): SnapshotMessage;
18
+ /**
19
+ * The player in `slot` left for good, and the other side wins by forfeit. The simulation's own `forfeit` is not
20
+ * used: it is the solo game's, where only the left side can give up.
21
+ */
22
+ leave(slot: number): void;
23
+ result(): EndMessage | null;
24
+ /** The match was played to the end; `result.won` is from the left side's point of view. */
25
+ private finish;
26
+ }
@@ -0,0 +1,86 @@
1
+ import { ONLINE_STEP, simInputOf, snapshotOf } from "./net/wire.js";
2
+ import { createPvpMatch } from "./sim/match.js";
3
+ import { createRng } from "./sim/rng.js";
4
+ /** Games in an online match: the first to win two. */
5
+ const ONLINE_BEST_OF = 3;
6
+ /** What a slot without an input this tick does: hold no key. */
7
+ const NO_KEYS = { held: 0, pressed: 0, released: 0 };
8
+ /** A fresh seed for each match, from the platform's cryptographic source. */
9
+ function randomSeed() {
10
+ return crypto.getRandomValues(new Uint32Array(1))[0];
11
+ }
12
+ /**
13
+ * One online Shuttle Blitz match, run by the room one tick at a time. Slot 0 plays the left side (`p`) and slot 1
14
+ * the right side (`ai`). Each tick is one step of real time; the simulation's own slow motion scales it, as the solo
15
+ * game does, so a decisive moment plays slower on both screens.
16
+ */
17
+ export class ShuttleRoomMatch {
18
+ match;
19
+ tick = 0;
20
+ /** Events since the previous state, stamped with the tick they happened on. */
21
+ events = [];
22
+ outcome = null;
23
+ constructor(members, seed = randomSeed()) {
24
+ for (const member of members) {
25
+ if (member.slot !== 0 && member.slot !== 1) {
26
+ throw new RangeError(`ShuttleRoomMatch: a match has slots 0 and 1, got ${member.slot}`);
27
+ }
28
+ }
29
+ this.match = createPvpMatch(createRng(seed), ONLINE_BEST_OF);
30
+ }
31
+ get over() {
32
+ return this.outcome !== null;
33
+ }
34
+ step(inputs) {
35
+ if (this.outcome) {
36
+ return;
37
+ }
38
+ // The simulation takes simulated seconds: real time scaled by its current slow-motion factor.
39
+ const dt = ONLINE_STEP * this.match.state.timeScale;
40
+ const events = this.match.stepPvp(dt, {
41
+ p: simInputOf(inputs.get(0) ?? NO_KEYS),
42
+ ai: simInputOf(inputs.get(1) ?? NO_KEYS)
43
+ });
44
+ this.tick++;
45
+ for (const event of events) {
46
+ this.events.push({ tick: this.tick, event });
47
+ if (event.type === 'matchEnd') {
48
+ this.finish(event.result);
49
+ }
50
+ }
51
+ }
52
+ state() {
53
+ const snapshot = snapshotOf(this.match.state, this.tick, this.events);
54
+ this.events = [];
55
+ return snapshot;
56
+ }
57
+ /**
58
+ * The player in `slot` left for good, and the other side wins by forfeit. The simulation's own `forfeit` is not
59
+ * used: it is the solo game's, where only the left side can give up.
60
+ */
61
+ leave(slot) {
62
+ if (this.outcome) {
63
+ return;
64
+ }
65
+ const { score, games } = this.match.state;
66
+ this.outcome = {
67
+ winner: slot === 0 ? 'ai' : 'p',
68
+ reason: 'forfeit',
69
+ score: { p: score.p, ai: score.ai },
70
+ games: { p: games.p, ai: games.ai }
71
+ };
72
+ }
73
+ result() {
74
+ return this.outcome;
75
+ }
76
+ /** The match was played to the end; `result.won` is from the left side's point of view. */
77
+ finish(result) {
78
+ const { score } = this.match.state;
79
+ this.outcome = {
80
+ winner: result.won ? 'p' : 'ai',
81
+ reason: 'finished',
82
+ score: { p: score.p, ai: score.ai },
83
+ games: { p: result.games.p, ai: result.games.ai }
84
+ };
85
+ }
86
+ }
@@ -0,0 +1,39 @@
1
+ import type { SimEvent, SwingType } from './events.ts';
2
+ import type { Actor, Brain, Shuttle, SimCtx, Swing } from './state.ts';
3
+ import type { Side, Stats } from './types.ts';
4
+ /** Stamina cost of each swing type, before the drain multiplier. */
5
+ export declare const SWING_COST: Readonly<Record<SwingType, number>>;
6
+ export declare const JUMP_COST = 7;
7
+ /** Minimum stamina needed to jump. */
8
+ export declare const JUMP_MIN_STAMINA = 6;
9
+ export declare const RUN_DRAIN = 5;
10
+ export declare const RECOVER_RATE = 10;
11
+ export declare function makeActor(side: Side, stats: Readonly<Stats>, brain?: Brain | null): Actor;
12
+ /**
13
+ * The AI's stand-in for a player's charge: the last AI_WIND_UP seconds before the contact it planned. Shorter than a
14
+ * full charge, so its bar visibly drains in long rallies without tiring it more than the difficulty curve allows.
15
+ */
16
+ export declare const AI_WIND_UP = 0.4;
17
+ /** Ground speed in px/s, before tiredness and swing slowdown. */
18
+ export declare const runSpeed: (a: Actor) => number;
19
+ export declare const hitCenter: (a: Actor) => {
20
+ x: number;
21
+ y: number;
22
+ };
23
+ export declare const reach: (a: Actor) => number;
24
+ /** Distance from the hit center in reach units, on an ellipse 1.3x taller than wide. 1 is the edge. */
25
+ export declare function normDist(a: Actor, sh: Pick<Shuttle, 'x' | 'y'>): number;
26
+ export declare function tryJump(out: SimEvent[], a: Actor): void;
27
+ export interface SwingOptions {
28
+ perfect?: boolean;
29
+ cross?: boolean;
30
+ q?: number;
31
+ }
32
+ /** Starts a swing and returns it, or null while one is already going. */
33
+ export declare function startSwing(out: SimEvent[], a: Actor, type: SwingType, power: number, o: SwingOptions): Swing | null;
34
+ /** True while a live shuttle from the other side is coming at `a` but is not yet in reach. */
35
+ export declare function shuttleOnTheWay(sh: Readonly<Shuttle>, a: Actor): boolean;
36
+ /** Starts a swing now, or, while the incoming shuttle is still out of reach, holds it back up to `wait` seconds. */
37
+ export declare function swingWithAssist(ctx: SimCtx, a: Actor, type: SwingType, power: number, o: SwingOptions, wait: number): void;
38
+ /** Advances one actor by dt with horizontal intent dir (-1, 0, 1). */
39
+ export declare function updateActor(ctx: SimCtx, a: Actor, dt: number, dir: number): void;
@@ -0,0 +1,146 @@
1
+ import { tryHit } from "./shots.js";
2
+ import { ACTOR_G, clamp, COURT_L, COURT_R, FLOOR, JUMP_V, NET_X, SERVE_HAND, SWING_ACTIVE, SWING_DUR, SWING_GROUND_SPEED, TIRED_AT, TIRED_SPEED, } from "./world.js";
3
+ /** Stamina cost of each swing type, before the drain multiplier. */
4
+ export const SWING_COST = { smash: 10, clear: 4, drop: 3 };
5
+ export const JUMP_COST = 7;
6
+ /** Minimum stamina needed to jump. */
7
+ export const JUMP_MIN_STAMINA = 6;
8
+ export const RUN_DRAIN = 5;
9
+ export const RECOVER_RATE = 10;
10
+ export function makeActor(side, stats, brain = null) {
11
+ const isP = side === 'p';
12
+ return {
13
+ side,
14
+ stats,
15
+ x: isP ? 600 : 1320,
16
+ y: FLOOR,
17
+ vx: 0,
18
+ vy: 0,
19
+ facing: isP ? 1 : -1,
20
+ onGround: true,
21
+ minX: isP ? COURT_L - 60 : NET_X + 70,
22
+ maxX: isP ? NET_X - 70 : COURT_R + 60,
23
+ stamina: 100,
24
+ drain: 1.35 - stats.sta * 0.07,
25
+ speedMul: 1,
26
+ swing: null,
27
+ pending: null,
28
+ charge: null,
29
+ mood: null,
30
+ lastDir: 0,
31
+ holding: false,
32
+ pose: 'idle',
33
+ stateT: 0,
34
+ swingP: 0,
35
+ brain,
36
+ serveHand: SERVE_HAND,
37
+ };
38
+ }
39
+ /**
40
+ * The AI's stand-in for a player's charge: the last AI_WIND_UP seconds before the contact it planned. Shorter than a
41
+ * full charge, so its bar visibly drains in long rallies without tiring it more than the difficulty curve allows.
42
+ */
43
+ export const AI_WIND_UP = 0.4;
44
+ const aiWindingUp = (a) => {
45
+ const plan = a.brain?.plan;
46
+ return !!plan && !plan.leave && plan.t <= AI_WIND_UP;
47
+ };
48
+ /** Ground speed in px/s, before tiredness and swing slowdown. */
49
+ export const runSpeed = (a) => (460 + a.stats.spd * 45) * a.speedMul;
50
+ export const hitCenter = (a) => ({ x: a.x + a.facing * 58, y: a.y - 210 });
51
+ export const reach = (a) => 120 + a.stats.tec * 7;
52
+ /** Distance from the hit center in reach units, on an ellipse 1.3x taller than wide. 1 is the edge. */
53
+ export function normDist(a, sh) {
54
+ const c = hitCenter(a);
55
+ const R = reach(a);
56
+ return Math.hypot((sh.x - c.x) / R, (sh.y - c.y) / (R * 1.3));
57
+ }
58
+ export function tryJump(out, a) {
59
+ if (!a.onGround || a.stamina < JUMP_MIN_STAMINA)
60
+ return;
61
+ a.vy = -JUMP_V;
62
+ a.onGround = false;
63
+ a.stamina -= JUMP_COST * a.drain;
64
+ out.push({ type: 'jump', side: a.side });
65
+ }
66
+ /** Starts a swing and returns it, or null while one is already going. */
67
+ export function startSwing(out, a, type, power, o) {
68
+ if (a.swing)
69
+ return null;
70
+ const swing = { type, t: 0, power, perfect: !!o.perfect, cross: !!o.cross, q: o.q, done: false };
71
+ a.swing = swing;
72
+ a.swingP = 0;
73
+ a.pose = type;
74
+ a.stateT = 0;
75
+ a.stamina = Math.max(0, a.stamina - SWING_COST[type] * a.drain);
76
+ out.push({ type: 'swingStart', side: a.side, kind: type });
77
+ return swing;
78
+ }
79
+ /** True while a live shuttle from the other side is coming at `a` but is not yet in reach. */
80
+ export function shuttleOnTheWay(sh, a) {
81
+ if (!sh.live || sh.heldBy || sh.netted || sh.lastHitter === a.side)
82
+ return false;
83
+ const coming = a.side === 'p' ? sh.x < NET_X || sh.vx < 0 : sh.x > NET_X || sh.vx > 0;
84
+ return coming && normDist(a, sh) > 0.95;
85
+ }
86
+ /** Starts a swing now, or, while the incoming shuttle is still out of reach, holds it back up to `wait` seconds. */
87
+ export function swingWithAssist(ctx, a, type, power, o, wait) {
88
+ if (a.swing || a.pending)
89
+ return;
90
+ if (wait > 0 && shuttleOnTheWay(ctx.s.shuttle, a)) {
91
+ a.pending = { type, power, perfect: !!o.perfect, cross: !!o.cross, left: wait };
92
+ return;
93
+ }
94
+ startSwing(ctx.out, a, type, power, o);
95
+ }
96
+ /** Advances one actor by dt with horizontal intent dir (-1, 0, 1). */
97
+ export function updateActor(ctx, a, dt, dir) {
98
+ if (a.pending) {
99
+ const w = a.pending;
100
+ w.left -= dt;
101
+ if (w.left <= 0 || !shuttleOnTheWay(ctx.s.shuttle, a)) {
102
+ a.pending = null;
103
+ startSwing(ctx.out, a, w.type, w.power, { perfect: w.perfect, cross: w.cross });
104
+ }
105
+ }
106
+ const tired = a.stamina < TIRED_AT;
107
+ const spd = runSpeed(a) * (tired ? TIRED_SPEED : 1) * (a.swing && a.onGround ? SWING_GROUND_SPEED : 1);
108
+ if (dir !== 0 && a.lastDir !== 0 && dir !== a.lastDir && a.onGround) {
109
+ ctx.out.push({ type: 'squeak', side: a.side, x: a.x });
110
+ }
111
+ if (dir !== 0)
112
+ a.lastDir = dir;
113
+ a.vx = dir * spd;
114
+ a.x = clamp(a.x + a.vx * dt, a.minX, a.maxX);
115
+ if (!a.onGround) {
116
+ a.vy += ACTOR_G * dt;
117
+ a.y += a.vy * dt;
118
+ if (a.y >= FLOOR) {
119
+ a.y = FLOOR;
120
+ a.vy = 0;
121
+ a.onGround = true;
122
+ ctx.out.push({ type: 'land', side: a.side });
123
+ }
124
+ }
125
+ if (dir !== 0)
126
+ a.stamina -= RUN_DRAIN * a.drain * dt;
127
+ // Holding a charge stops recovery. The AI never charges, so its last CHARGE_FULL seconds before contact count as one.
128
+ else if (!a.charge && !a.swing && !aiWindingUp(a))
129
+ a.stamina += RECOVER_RATE * dt;
130
+ a.stamina = clamp(a.stamina, 0, 100);
131
+ if (a.charge)
132
+ a.charge.t += dt;
133
+ if (a.swing) {
134
+ const sw = a.swing;
135
+ if (!sw.done && sw.t <= SWING_ACTIVE)
136
+ tryHit(ctx, a);
137
+ sw.t += dt;
138
+ a.swingP = Math.min(1, sw.t / SWING_DUR);
139
+ if (sw.t >= SWING_DUR) {
140
+ a.swing = null;
141
+ a.swingP = 1;
142
+ }
143
+ }
144
+ if (a.mood && (a.mood.t -= dt) <= 0 && !a.mood.hold)
145
+ a.mood = null;
146
+ }
@@ -0,0 +1,41 @@
1
+ import type { SwingType } from './events.ts';
2
+ import type { Rng } from './rng.ts';
3
+ import type { Actor, AiPlan, Brain, MatchState, SimCtx } from './state.ts';
4
+ import type { Difficulty, Stats } from './types.ts';
5
+ /** Extra reaction delay when the incoming shot was hit cross-court. */
6
+ export declare const CROSS_REACT_DELAY = 0.12;
7
+ export declare const AI_HOME_X = 1380;
8
+ export interface OpponentSpec {
9
+ stats: Readonly<Stats>;
10
+ /** Opponent aggression 0..1 from tournament data. */
11
+ aggr: number;
12
+ }
13
+ /**
14
+ * Easing for the first tournaments, so a new player can win the opening matches (the 10 -> 8 feedback). Later tiers
15
+ * keep the mockup's curve.
16
+ */
17
+ export declare const EARLY_EASE: Readonly<Record<number, number>>;
18
+ /**
19
+ * Extra easing for the boss of the first tournaments, tuned so the perfect-timing test bot wins the best-of-3 boss match
20
+ * about 3 times in 5 (128 matches: Phuong boss 61%, Quan boss 57%). Results swing hard around these values.
21
+ */
22
+ export declare const EARLY_BOSS_EASE: Readonly<Record<number, number>>;
23
+ /** Chance of a whiff per unit of negative boost: only eased matches whiff, capped at MAX_WHIFF. */
24
+ export declare const WHIFF_K = 1.2;
25
+ export declare const MAX_WHIFF = 0.25;
26
+ /** Tournament tier adds 0.05 per tier above the first and a boss match 0.06; the first tiers are eased (EARLY_EASE). */
27
+ export declare const difficultyBoost: (tier: number, boss: boolean) => number;
28
+ export declare function makeBrain(difficulty: Difficulty, tier: number, boss: boolean, aggr: number): Brain;
29
+ export declare function makeOpponent(o: OpponentSpec, difficulty: Difficulty, tier: number, boss: boolean): Actor;
30
+ export declare function toward(a: Actor, x: number, dead: number): number;
31
+ /** Simulates the incoming shuttle to pick an intercept point, a possible jump smash, or leaving it out. */
32
+ export declare function aiPlan(s: MatchState, rng: Rng, a: Actor): AiPlan;
33
+ export interface AiShot {
34
+ type: SwingType;
35
+ power: number;
36
+ q: number;
37
+ cross: boolean;
38
+ }
39
+ export declare function aiChoose(s: MatchState, rng: Rng, a: Actor): AiShot;
40
+ export declare function aiServe(ctx: SimCtx, a: Actor): void;
41
+ export declare function aiUpdate(ctx: SimCtx, a: Actor, dt: number): void;