@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/dist/sim/ai.js ADDED
@@ -0,0 +1,181 @@
1
+ // Opponent AI: trajectory planning, shot choice and serving (mockup match.js:85-95, 394-478).
2
+ import { makeActor, normDist, startSwing, tryJump, updateActor } from "./actor.js";
3
+ import { launchServe, lob, serveSwing } from "./shots.js";
4
+ import { clamp, COURT_R, DIFF, FLOOR, G, JUMP_APEX_TIME, JUMP_SMASH_BAND, NET_TOP, NET_X, SHORT_SERVICE } from "./world.js";
5
+ /** Extra reaction delay when the incoming shot was hit cross-court. */
6
+ export const CROSS_REACT_DELAY = 0.12;
7
+ export const AI_HOME_X = 1380;
8
+ /**
9
+ * Easing for the first tournaments, so a new player can win the opening matches (the 10 -> 8 feedback). Later tiers
10
+ * keep the mockup's curve.
11
+ */
12
+ export const EARLY_EASE = { 1: -0.07, 2: -0.07 };
13
+ /**
14
+ * Extra easing for the boss of the first tournaments, tuned so the perfect-timing test bot wins the best-of-3 boss match
15
+ * about 3 times in 5 (128 matches: Phuong boss 61%, Quan boss 57%). Results swing hard around these values.
16
+ */
17
+ export const EARLY_BOSS_EASE = { 1: 0.001, 2: -0.058 };
18
+ /** Chance of a whiff per unit of negative boost: only eased matches whiff, capped at MAX_WHIFF. */
19
+ export const WHIFF_K = 1.2;
20
+ export const MAX_WHIFF = 0.25;
21
+ /** Tournament tier adds 0.05 per tier above the first and a boss match 0.06; the first tiers are eased (EARLY_EASE). */
22
+ export const difficultyBoost = (tier, boss) => (tier - 1) * 0.05 + (boss ? 0.06 + (EARLY_BOSS_EASE[tier] ?? 0) : 0) + (EARLY_EASE[tier] ?? 0);
23
+ export function makeBrain(difficulty, tier, boss, aggr) {
24
+ const dfx = DIFF[difficulty] ?? DIFF.vua;
25
+ const boost = difficultyBoost(tier, boss);
26
+ return {
27
+ skill: clamp(dfx.skill + boost, 0.3, 0.95),
28
+ err: clamp(dfx.err - boost * 0.4, 0.02, 0.3),
29
+ aggr: clamp(aggr * dfx.aggr + 0.1, 0, 0.9),
30
+ reactDelay: dfx.react * (1 - boost),
31
+ whiff: clamp(-boost * WHIFF_K, 0, MAX_WHIFF),
32
+ teach: 0,
33
+ plan: null,
34
+ react: 0,
35
+ jumped: false,
36
+ serveTimer: 0,
37
+ home: AI_HOME_X,
38
+ };
39
+ }
40
+ export function makeOpponent(o, difficulty, tier, boss) {
41
+ const ai = makeActor('ai', o.stats, makeBrain(difficulty, tier, boss, o.aggr));
42
+ ai.speedMul = (DIFF[difficulty] ?? DIFF.vua).speed;
43
+ return ai;
44
+ }
45
+ function brainOf(a) {
46
+ if (!a.brain)
47
+ throw new Error(`AI routine called on an actor without a brain (side ${a.side})`);
48
+ return a.brain;
49
+ }
50
+ export function toward(a, x, dead) {
51
+ const d = x - a.x;
52
+ return Math.abs(d) < dead ? 0 : Math.sign(d);
53
+ }
54
+ /** Simulates the incoming shuttle to pick an intercept point, a possible jump smash, or leaving it out. */
55
+ export function aiPlan(s, rng, a) {
56
+ const sh = s.shuttle;
57
+ const B = brainOf(a);
58
+ let x = sh.x;
59
+ let y = sh.y;
60
+ let vy = sh.vy;
61
+ let t = 0;
62
+ const vx = sh.vx;
63
+ const step = 1 / 120;
64
+ const cy = FLOOR - 210;
65
+ let hit = null;
66
+ let smashPt = null;
67
+ let landX = null;
68
+ for (let i = 0; i < 480; i++) {
69
+ vy += G * step;
70
+ x += vx * step;
71
+ y += vy * step;
72
+ t += step;
73
+ if (x > NET_X + 20) {
74
+ if (!smashPt && vy > 0 && y > JUMP_SMASH_BAND[0] && y < JUMP_SMASH_BAND[1])
75
+ smashPt = { x, t };
76
+ if (!hit && vy > 0 && y >= cy - 40)
77
+ hit = { x, t };
78
+ }
79
+ if (y >= FLOOR - 6) {
80
+ landX = x;
81
+ if (!hit)
82
+ hit = { x, t };
83
+ break;
84
+ }
85
+ }
86
+ if (!hit)
87
+ hit = { x: B.home, t: 1 };
88
+ const plan = { x: hit.x, t: hit.t, err: (rng.next() * 2 - 1) * (1 - B.skill) * 90, leave: false, smash: false, whiff: false };
89
+ // Drawn only for eased matches, so the random stream (and every result) of the others stays as it was.
90
+ if (B.whiff > 0)
91
+ plan.whiff = rng.next() < B.whiff;
92
+ if (landX != null && landX > COURT_R + 10 && rng.next() < B.skill)
93
+ plan.leave = true;
94
+ if (landX != null && landX < NET_X)
95
+ plan.leave = true;
96
+ // A serve that falls short of the service line is a fault: a good player lets it drop.
97
+ if (landX != null && s.rally === 1 && landX < NET_X + SHORT_SERVICE && rng.next() < B.skill)
98
+ plan.leave = true;
99
+ if (smashPt && (B.teach > 0 || rng.next() < B.aggr)) {
100
+ plan.smash = true;
101
+ plan.x = smashPt.x;
102
+ plan.t = smashPt.t;
103
+ }
104
+ return plan;
105
+ }
106
+ export function aiChoose(s, rng, a) {
107
+ const B = brainOf(a);
108
+ const sh = s.shuttle;
109
+ const p = s.p;
110
+ const q = rng.next() < B.err ? rng.next() * 0.3 : 0.62 + rng.next() * 0.33 * B.skill + 0.05;
111
+ let type;
112
+ if (sh.y < NET_TOP - 60 && ((B.plan?.smash && B.teach > 0) || rng.next() < B.aggr * (B.plan && B.plan.smash ? 1 : 0.5)))
113
+ type = 'smash';
114
+ else if (p.x < 520 && rng.next() < 0.45)
115
+ type = 'drop';
116
+ else if (p.x > 760 && rng.next() < 0.6)
117
+ type = 'clear';
118
+ else
119
+ type = rng.next() < 0.3 ? 'drop' : 'clear';
120
+ const power = 0.45 + rng.next() * 0.5;
121
+ const cross = rng.next() < 0.2;
122
+ return { type, power, q, cross };
123
+ }
124
+ export function aiServe(ctx, a) {
125
+ const { rng } = ctx;
126
+ const sh = ctx.s.shuttle;
127
+ const short = rng.next() < 0.35;
128
+ const type = short ? 'drop' : 'clear';
129
+ serveSwing(a, type, 0.1, 0.7);
130
+ // A short serve misses the short service line as often as the AI errs; the receiver may let it fall for the point.
131
+ const fault = short && rng.next() < brainOf(a).err;
132
+ const depth = fault ? rng.range(SHORT_SERVICE - 90, SHORT_SERVICE - 20) : rng.range(SHORT_SERVICE + 20, SHORT_SERVICE + 80);
133
+ const v = short ? lob(sh.x, sh.y, NET_X - depth, NET_TOP - 90, true) : lob(sh.x, sh.y, NET_X - rng.range(520, 680), 220, true);
134
+ launchServe(ctx, a, type, v);
135
+ }
136
+ export function aiUpdate(ctx, a, dt) {
137
+ const { s, rng } = ctx;
138
+ const sh = s.shuttle;
139
+ const B = brainOf(a);
140
+ let dir = 0;
141
+ if (s.phase === 'serve') {
142
+ if (s.server === 'ai' && sh.heldBy === 'ai') {
143
+ if ((B.serveTimer -= dt) <= 0)
144
+ aiServe(ctx, a);
145
+ }
146
+ }
147
+ else if (s.phase === 'rally') {
148
+ const incoming = sh.live && sh.lastHitter === 'p' && !sh.netted;
149
+ if (incoming) {
150
+ if (!B.plan) {
151
+ B.plan = aiPlan(s, rng, a);
152
+ B.react = B.reactDelay * rng.range(0.7, 1.3) + (sh.cross ? CROSS_REACT_DELAY : 0);
153
+ B.jumped = false;
154
+ }
155
+ const plan = B.plan;
156
+ plan.t -= dt;
157
+ if ((B.react -= dt) <= 0 && !plan.leave) {
158
+ dir = toward(a, plan.x + 58 + plan.err, 14);
159
+ if (plan.smash && a.onGround && !B.jumped && plan.t <= JUMP_APEX_TIME + 0.02) {
160
+ tryJump(ctx.out, a);
161
+ B.jumped = true;
162
+ }
163
+ }
164
+ if (!a.swing && !plan.leave && sh.x > NET_X && normDist(a, sh) < 0.95) {
165
+ const shot = aiChoose(s, rng, a);
166
+ const swing = startSwing(ctx.out, a, shot.type, shot.power, { q: shot.q, cross: shot.cross });
167
+ if (swing && shot.type === 'smash' && plan.smash && B.teach > 0)
168
+ B.teach--;
169
+ if (plan.whiff && swing) {
170
+ // A whiff: the racket goes through the motion but never meets the shuttle, and the AI gives up on it.
171
+ swing.done = true;
172
+ plan.leave = true;
173
+ }
174
+ }
175
+ }
176
+ else {
177
+ dir = toward(a, B.home, 20);
178
+ }
179
+ }
180
+ updateActor(ctx, a, dt, dir);
181
+ }
@@ -0,0 +1,170 @@
1
+ import type { ShotKind, Side, TrainingId } from './types.ts';
2
+ export type SwingType = 'clear' | 'drop' | 'smash';
3
+ /** Why a point ended; 'fault' is a serve that did not reach the receiver's short service line. */
4
+ export type PointReason = 'net' | 'out' | 'in' | 'fault';
5
+ /** Visual tone of a floating text, mirroring the mockup pop-text classes. */
6
+ export type PopTone = 'perfect' | 'small' | 'save' | 'smash' | 'speed';
7
+ export interface MatchStats {
8
+ smashes: number;
9
+ errors: number;
10
+ shots: number;
11
+ errorRate: number;
12
+ longest: number;
13
+ }
14
+ export interface MatchResult {
15
+ won: boolean;
16
+ forfeit: boolean;
17
+ games: {
18
+ p: number;
19
+ ai: number;
20
+ };
21
+ /** Final score of each finished game, as [player, opponent]. */
22
+ gameScores: Array<[number, number]>;
23
+ stats: MatchStats;
24
+ }
25
+ export type TrainingResult = {
26
+ training: true;
27
+ kind: TrainingId;
28
+ score: number;
29
+ } | {
30
+ training: true;
31
+ aborted: true;
32
+ };
33
+ export type TextVars = Readonly<Record<string, string | number>>;
34
+ export type SimEvent = {
35
+ type: 'swingStart';
36
+ side: Side;
37
+ kind: SwingType;
38
+ }
39
+ /**
40
+ * A racket or the feeder machine touched the shuttle. In training, side 'ai' is the machine.
41
+ * `power` is the impact strength 0..1 (mockup audio.hit input); a smash always reports 1.
42
+ */
43
+ | {
44
+ type: 'hit';
45
+ side: Side;
46
+ kind: ShotKind;
47
+ power: number;
48
+ x: number;
49
+ y: number;
50
+ kmh?: number;
51
+ perfect?: boolean;
52
+ rescue?: boolean;
53
+ } | {
54
+ type: 'jump';
55
+ side: Side;
56
+ } | {
57
+ type: 'land';
58
+ side: Side;
59
+ } | {
60
+ type: 'squeak';
61
+ side: Side;
62
+ x: number;
63
+ }
64
+ /** The shuttle hit the floor. `kind` is the last shot kind (a smash landing shakes the camera). */
65
+ | {
66
+ type: 'floor';
67
+ x: number;
68
+ kind: ShotKind;
69
+ } | {
70
+ type: 'net';
71
+ x: number;
72
+ y: number;
73
+ } | {
74
+ type: 'point';
75
+ winner: Side;
76
+ reason: PointReason;
77
+ } | {
78
+ type: 'gameWon';
79
+ side: Side;
80
+ game: number;
81
+ } | {
82
+ type: 'matchEnd';
83
+ result: MatchResult;
84
+ }
85
+ /** Show a banner. `sub` is an optional second-line key sharing `vars`. Duration 0 keeps it until hidden. */
86
+ | {
87
+ type: 'banner';
88
+ key: string;
89
+ sub?: string;
90
+ vars: TextVars;
91
+ side: Side;
92
+ duration: number;
93
+ } | {
94
+ type: 'bannerHide';
95
+ } | {
96
+ type: 'pop';
97
+ key: string;
98
+ vars: TextVars;
99
+ x: number;
100
+ y: number;
101
+ tone: PopTone;
102
+ }
103
+ /** Slow motion started (factor < 1) or ended (factor 1, duration 0). Duration is in real seconds. */
104
+ | {
105
+ type: 'slowmo';
106
+ factor: number;
107
+ duration: number;
108
+ }
109
+ /** Raise crowd excitement to at least `amount` (0..1); the view decays it. */
110
+ | {
111
+ type: 'excite';
112
+ amount: number;
113
+ } | {
114
+ type: 'serveReady';
115
+ side: Side;
116
+ } | {
117
+ type: 'trainingScore';
118
+ value: number;
119
+ } | {
120
+ type: 'trainingEnd';
121
+ result: TrainingResult;
122
+ };
123
+ export type SimEventType = SimEvent['type'];
124
+ /** The second banner line for the player's serve needs the HUD to add `{clear}` and `{drop}` key labels. */
125
+ export declare const BANNER_KEYS: {
126
+ readonly training: "banner.training";
127
+ readonly trainingRule: {
128
+ readonly feeder: "banner.trainingRule.feeder";
129
+ readonly target: "banner.trainingRule.target";
130
+ readonly smash: "banner.trainingRule.smash";
131
+ };
132
+ readonly yourServe: "banner.yourServe";
133
+ readonly yourServeHint: "banner.yourServeHint";
134
+ readonly oppServe: "banner.oppServe";
135
+ readonly oppServeHint: "banner.oppServeHint";
136
+ readonly pointWon: "banner.pointWon";
137
+ readonly pointLost: "banner.pointLost";
138
+ readonly pointReason: {
139
+ readonly net: "banner.pointReason.net";
140
+ readonly out: "banner.pointReason.out";
141
+ readonly in: "banner.pointReason.in";
142
+ readonly fault: "banner.pointReason.fault";
143
+ };
144
+ readonly matchWon: "banner.matchWon";
145
+ readonly matchLost: "banner.matchLost";
146
+ readonly gamesScore: "banner.gamesScore";
147
+ readonly gameWon: "banner.gameWon";
148
+ readonly gameLost: "banner.gameLost";
149
+ readonly nextGame: "banner.nextGame";
150
+ readonly trainingDone: "banner.trainingDone";
151
+ readonly trainingDoneHint: "banner.trainingDoneHint";
152
+ };
153
+ export declare const POP_KEYS: {
154
+ readonly perfect: "pop.perfect";
155
+ readonly cross: "pop.cross";
156
+ readonly rescue: "pop.rescue";
157
+ readonly smash: "pop.smash";
158
+ readonly jumpSmash: "pop.jumpSmash";
159
+ readonly smashSave: "pop.smashSave";
160
+ readonly kmh: "pop.kmh";
161
+ readonly net: "pop.net";
162
+ readonly plusOne: "pop.plusOne";
163
+ readonly targetHit: "pop.targetHit";
164
+ readonly targetMiss: "pop.targetMiss";
165
+ readonly notSmash: "pop.notSmash";
166
+ readonly out: "pop.out";
167
+ readonly missed: "pop.missed";
168
+ };
169
+ /** Every text key the simulation can emit. Locales must define each of them in vi and en. */
170
+ export declare const SIM_TEXT_KEYS: readonly string[];
@@ -0,0 +1,54 @@
1
+ /** The second banner line for the player's serve needs the HUD to add `{clear}` and `{drop}` key labels. */
2
+ export const BANNER_KEYS = {
3
+ training: 'banner.training',
4
+ trainingRule: {
5
+ feeder: 'banner.trainingRule.feeder',
6
+ target: 'banner.trainingRule.target',
7
+ smash: 'banner.trainingRule.smash',
8
+ },
9
+ yourServe: 'banner.yourServe',
10
+ yourServeHint: 'banner.yourServeHint',
11
+ oppServe: 'banner.oppServe',
12
+ oppServeHint: 'banner.oppServeHint',
13
+ pointWon: 'banner.pointWon',
14
+ pointLost: 'banner.pointLost',
15
+ pointReason: {
16
+ net: 'banner.pointReason.net',
17
+ out: 'banner.pointReason.out',
18
+ in: 'banner.pointReason.in',
19
+ fault: 'banner.pointReason.fault',
20
+ },
21
+ matchWon: 'banner.matchWon',
22
+ matchLost: 'banner.matchLost',
23
+ gamesScore: 'banner.gamesScore',
24
+ gameWon: 'banner.gameWon',
25
+ gameLost: 'banner.gameLost',
26
+ nextGame: 'banner.nextGame',
27
+ trainingDone: 'banner.trainingDone',
28
+ trainingDoneHint: 'banner.trainingDoneHint',
29
+ };
30
+ export const POP_KEYS = {
31
+ perfect: 'pop.perfect',
32
+ cross: 'pop.cross',
33
+ rescue: 'pop.rescue',
34
+ smash: 'pop.smash',
35
+ jumpSmash: 'pop.jumpSmash',
36
+ smashSave: 'pop.smashSave',
37
+ kmh: 'pop.kmh',
38
+ net: 'pop.net',
39
+ plusOne: 'pop.plusOne',
40
+ targetHit: 'pop.targetHit',
41
+ targetMiss: 'pop.targetMiss',
42
+ notSmash: 'pop.notSmash',
43
+ out: 'pop.out',
44
+ missed: 'pop.missed',
45
+ };
46
+ function leaves(node) {
47
+ if (typeof node === 'string')
48
+ return [node];
49
+ if (node && typeof node === 'object')
50
+ return Object.values(node).flatMap(leaves);
51
+ return [];
52
+ }
53
+ /** Every text key the simulation can emit. Locales must define each of them in vi and en. */
54
+ export const SIM_TEXT_KEYS = Object.freeze([...leaves(BANNER_KEYS), ...leaves(POP_KEYS)]);
@@ -0,0 +1,18 @@
1
+ export type { ActionId, Difficulty, ShotKind, Side, Stats, TrainingId } from './types.ts';
2
+ export type { Rng } from './rng.ts';
3
+ export { createRng } from './rng.ts';
4
+ export * from './world.ts';
5
+ export type { MatchResult, MatchStats, PointReason, PopTone, SimEvent, SimEventType, SwingType, TextVars, TrainingResult, } from './events.ts';
6
+ export { BANNER_KEYS, POP_KEYS, SIM_TEXT_KEYS } from './events.ts';
7
+ export type { Actor, AiPlan, Brain, Charge, MatchPhase, MatchState, Mood, Score, Shuttle, Swing, TrainState } from './state.ts';
8
+ export type { AnimKey } from './pose-state.ts';
9
+ export { actorPose, ANIM_KEYS } from './pose-state.ts';
10
+ export { hitCenter, normDist, reach, runSpeed } from './actor.ts';
11
+ export { smashSpeed, toKmh } from './shots.ts';
12
+ export type { OpponentSpec } from './ai.ts';
13
+ export { difficultyBoost, makeBrain } from './ai.ts';
14
+ export { gameWinner, gamesNeeded, isGamePoint, matchWinner } from './rules.ts';
15
+ export type { SlowMo } from './slowmo.ts';
16
+ export { createSlowMo } from './slowmo.ts';
17
+ export type { Match, MatchConfig, PvpInputs, PvpMatch, SimInput } from './match.ts';
18
+ export { createMatch, createPvpMatch } from './match.ts';
@@ -0,0 +1,10 @@
1
+ export { createRng } from "./rng.js";
2
+ export * from "./world.js";
3
+ export { BANNER_KEYS, POP_KEYS, SIM_TEXT_KEYS } from "./events.js";
4
+ export { actorPose, ANIM_KEYS } from "./pose-state.js";
5
+ export { hitCenter, normDist, reach, runSpeed } from "./actor.js";
6
+ export { smashSpeed, toKmh } from "./shots.js";
7
+ export { difficultyBoost, makeBrain } from "./ai.js";
8
+ export { gameWinner, gamesNeeded, isGamePoint, matchWinner } from "./rules.js";
9
+ export { createSlowMo } from "./slowmo.js";
10
+ export { createMatch, createPvpMatch } from "./match.js";
@@ -0,0 +1,66 @@
1
+ import type { OpponentSpec } from './ai.ts';
2
+ import type { SimEvent } from './events.ts';
3
+ import type { Rng } from './rng.ts';
4
+ import type { MatchState, SimCtx } from './state.ts';
5
+ import type { ActionId, Difficulty, Side, Stats, TrainingId } from './types.ts';
6
+ export interface MatchConfig {
7
+ mode: 'match' | 'training';
8
+ /** Player attributes; equipment never changes them. */
9
+ player: Stats;
10
+ /** Ignored in training. */
11
+ opponent: OpponentSpec;
12
+ difficulty: Difficulty;
13
+ /** Tournament tier, 1-based. */
14
+ tier: number;
15
+ boss: boolean;
16
+ /** Odd number of games; ignored in training. */
17
+ bestOf: number;
18
+ /** Required in training mode. */
19
+ trainingId?: TrainingId;
20
+ /** Jump smashes the AI goes for at every chance first, to show a new player what to return (learning match). */
21
+ teachSmashes?: number;
22
+ /** Free hand of each side's serve pose (see SERVE_HAND), so a held shuttle sits in the drawn hand. */
23
+ serveHand?: Partial<Record<Side, Readonly<{
24
+ x: number;
25
+ y: number;
26
+ }>>>;
27
+ }
28
+ /** Input gathered since the previous step. `held` is the state after this frame's presses and releases. */
29
+ export interface SimInput {
30
+ held: ReadonlySet<ActionId>;
31
+ pressed: readonly ActionId[];
32
+ released: readonly ActionId[];
33
+ }
34
+ export interface Match {
35
+ /** Live simulation state. Views read it; only the simulation mutates it. */
36
+ readonly state: Readonly<MatchState>;
37
+ /**
38
+ * Advances by dt simulated seconds. The caller scales real time by `state.timeScale`,
39
+ * so dt / timeScale is the real time used for real-time timers and the slow-motion span.
40
+ */
41
+ step(dt: number, input: SimInput): SimEvent[];
42
+ /** Ends the session now: a lost forfeit in a match, an aborted drill in training. */
43
+ forfeit(): SimEvent[];
44
+ /** Drops a charging shot without firing it (pause, focus loss). */
45
+ cancelCharge(): void;
46
+ }
47
+ /** Inputs for the two human-controlled sides of an online match. */
48
+ export interface PvpInputs {
49
+ p: SimInput;
50
+ ai: SimInput;
51
+ }
52
+ export interface PvpMatch {
53
+ readonly state: Readonly<MatchState>;
54
+ stepPvp(dt: number, inputs: PvpInputs): SimEvent[];
55
+ forfeit(): SimEvent[];
56
+ cancelCharge(): void;
57
+ }
58
+ /** Moves the shuttle: carried by the server, or in flight with net collision and floor landing. */
59
+ export declare function updateShuttle(ctx: SimCtx, dt: number): void;
60
+ export declare function createMatch(cfg: MatchConfig, rng: Rng): Match;
61
+ /**
62
+ * The deterministic two-player counterpart to `createMatch`. It deliberately shares the same court, scoring and
63
+ * shot code as the solo game; the only difference is that both actors receive a browser's input instead of asking
64
+ * `aiUpdate` to choose one. The RTC room host owns this simulation and sends snapshots to both browsers.
65
+ */
66
+ export declare function createPvpMatch(rng: Rng, bestOf?: number): PvpMatch;