@maco-online/head-clash-rules 0.0.0 → 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 +21 -0
- package/README.md +162 -1
- package/dist/definition.d.ts +16 -0
- package/dist/definition.js +42 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +2 -0
- package/dist/net/predicted-sim.d.ts +21 -0
- package/dist/net/predicted-sim.js +66 -0
- package/dist/net/wire.d.ts +52 -0
- package/dist/net/wire.js +266 -0
- package/dist/room-match.d.ts +35 -0
- package/dist/room-match.js +71 -0
- package/dist/sim/anim.d.ts +7 -0
- package/dist/sim/anim.js +44 -0
- package/dist/sim/ball.d.ts +9 -0
- package/dist/sim/ball.js +464 -0
- package/dist/sim/bot.d.ts +5 -0
- package/dist/sim/bot.js +130 -0
- package/dist/sim/characters.d.ts +22 -0
- package/dist/sim/characters.js +42 -0
- package/dist/sim/constants.d.ts +156 -0
- package/dist/sim/constants.js +166 -0
- package/dist/sim/debug.d.ts +14 -0
- package/dist/sim/debug.js +34 -0
- package/dist/sim/events.d.ts +79 -0
- package/dist/sim/events.js +12 -0
- package/dist/sim/geometry.d.ts +33 -0
- package/dist/sim/geometry.js +58 -0
- package/dist/sim/index.d.ts +18 -0
- package/dist/sim/index.js +13 -0
- package/dist/sim/input.d.ts +12 -0
- package/dist/sim/input.js +25 -0
- package/dist/sim/match.d.ts +17 -0
- package/dist/sim/match.js +208 -0
- package/dist/sim/player.d.ts +16 -0
- package/dist/sim/player.js +207 -0
- package/dist/sim/powerups.d.ts +33 -0
- package/dist/sim/powerups.js +189 -0
- package/dist/sim/rng.d.ts +12 -0
- package/dist/sim/rng.js +21 -0
- package/dist/sim/specials.d.ts +21 -0
- package/dist/sim/specials.js +114 -0
- package/dist/sim/state.d.ts +125 -0
- package/dist/sim/state.js +1 -0
- package/dist/sim/types.d.ts +31 -0
- package/dist/sim/types.js +30 -0
- package/dist/sim/walls.d.ts +60 -0
- package/dist/sim/walls.js +215 -0
- package/package.json +51 -3
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,164 @@
|
|
|
1
1
|
# @maco-online/head-clash-rules
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The pure rules of Head Clash, an original 1v1 big-head football game: a deterministic 60 Hz simulation (players,
|
|
4
|
+
ball, goals, 15 power-ups, 6 character specials, energy, animation states, events), the computer opponent, QA hooks,
|
|
5
|
+
the online wire format and the room definition the Maco online server runs. Nothing here imports Phaser or touches
|
|
6
|
+
the DOM, so the browser (offline against the bot) and the server (online) step exactly the same code.
|
|
7
|
+
|
|
8
|
+
## Entries
|
|
9
|
+
|
|
10
|
+
| Import | What it gives you |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `@maco-online/head-clash-rules/sim` | The simulation: `createMatch`, `stepMatch`, `botInput`, constants, types, debug hooks |
|
|
13
|
+
| `@maco-online/head-clash-rules/sim/<module>` | One simulation module, such as `sim/constants` or `sim/bot` |
|
|
14
|
+
| `@maco-online/head-clash-rules/net/wire` | Online messages: `readSnapshot`, `WireInput`, `mergeInputs`, `ONLINE_ROOM`, `ONLINE_PROTOCOL` |
|
|
15
|
+
| `@maco-online/head-clash-rules/net/predicted-sim` | `HeadClashPredictedSim`, a browser's predicted copy of the online match for `ReplayPredictor` |
|
|
16
|
+
| `@maco-online/head-clash-rules` | The room side: `headClashDefinition`, `HeadClashRoomMatch`, `HeadClashResult` |
|
|
17
|
+
|
|
18
|
+
## Playing offline against the bot
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { botInput, createMatch, createRng, stepMatch, TICK_RATE } from '@maco-online/head-clash-rules/sim'
|
|
22
|
+
import type { InputFrame, MatchState, SimEvent } from '@maco-online/head-clash-rules/sim'
|
|
23
|
+
|
|
24
|
+
const seed = 12345
|
|
25
|
+
const match: MatchState = createMatch({ seed, characters: ['tuan', 'bao'] }) // matchSeconds: 90, powerUps: true
|
|
26
|
+
const botRng = createRng(seed ^ 0x5bd1e995)
|
|
27
|
+
|
|
28
|
+
// Call once per fixed 1/60 s tick (accumulate real time and step as many ticks as are due).
|
|
29
|
+
function tick(player: InputFrame): SimEvent[] {
|
|
30
|
+
const events = stepMatch(match, [player, botInput(match, 1, 3, botRng)])
|
|
31
|
+
// Draw from `match`; play sounds and effects from `events`.
|
|
32
|
+
return events
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`stepMatch(state, [input0, input1])` changes `state` in place and returns the tick's events. The same seed and the
|
|
37
|
+
same inputs always give the same match. `cloneMatch(state)` copies a state (plain JSON data).
|
|
38
|
+
|
|
39
|
+
## Input
|
|
40
|
+
|
|
41
|
+
`InputFrame = { left, right, jump, kick, special }`, all booleans, one per player per tick. Hold the keys as they are
|
|
42
|
+
held: kicks and specials fire on the press (the simulation compares with the previous tick), a held jump jumps again
|
|
43
|
+
on landing. Player 0 starts left, defends the left goal and always faces right; player 1 the opposite.
|
|
44
|
+
|
|
45
|
+
## State the renderer reads
|
|
46
|
+
|
|
47
|
+
All in world units (1600 x 900, y down, ground at `GROUND_Y` = 780). See `src/sim/state.ts` for every field.
|
|
48
|
+
|
|
49
|
+
- `match.phase`: `kickoff` (1.2 s wait, ball hanging at the centre), `play`, `goal` (1.5 s celebration), `over`.
|
|
50
|
+
- `match.score`, `match.clockTicks` (regular time left; `clockSeconds(match)` for the display), `match.goldenGoal`,
|
|
51
|
+
`match.winner` (set when over; `null` with `phase === 'over'` is a draw).
|
|
52
|
+
- `match.players[i]`: `x, y` (between the feet), `vx, vy`, `facing` (1 or -1), `character`, `energy` (0 to 100),
|
|
53
|
+
`specialArmed`, `headScale`, `frozen` (draw the ice overlay on `idle`), `stunTicks`, and the animation:
|
|
54
|
+
`anim` is one of `idle | run | jump | kick | header | special | celebrate | sad`, and `animTime(player)` is the
|
|
55
|
+
seconds spent in it (`animTicks / TICK_RATE`), which restarts whenever `anim` changes.
|
|
56
|
+
- Colliders, for debug drawing or placing sprites: `headCircle(p)`, `chestCircle(p)`, `bodyCircle(p)`, `footCircle(p)`.
|
|
57
|
+
Each character's head sits where its art draws it: `CHARACTER_HEADS[id]` gives the skull centre (`head`) and neck
|
|
58
|
+
point (`neck`) above the feet, and a scaled head is centred at `neck + (head - neck) * headScale` with radius
|
|
59
|
+
`HEAD_RADIUS * headScale`. The chest circle (radius `CHEST_RADIUS`) sits on the neck point.
|
|
60
|
+
- `match.ball`: `x, y, vx, vy, r`, `lastToucher`, and `mode`: `none | fire | curve | ice | ghost | thunderUp |
|
|
61
|
+
thunderDown` (draw a ghost ball at low alpha, a fire or ice trail, a thunder glow).
|
|
62
|
+
- `match.goals[0 | 1]`: `crossbarY` (top of the bar), `depth` (the mouth runs from the side wall to `depth`) and
|
|
63
|
+
`shield`; `crossbarRect(goal, side)` and `shieldRect(goal, side)` give their rectangles.
|
|
64
|
+
- `match.items`: power-ups on the field (`kind, x, y, landed`), `match.effects`: power-ups at work
|
|
65
|
+
(`kind, owner, target, ticks`). `hasEffect(match, kind, player)` answers for one player.
|
|
66
|
+
|
|
67
|
+
## Goal frames
|
|
68
|
+
|
|
69
|
+
Crossbars and shields are thin solids the ball never crosses: every move of the ball (each flight sub-step, and the
|
|
70
|
+
push when players touch it) is swept against them as the segment its centre travels, against each wall grown by the
|
|
71
|
+
ball's radius (`src/sim/walls.ts`). At the first contact it stops, bounces and slides on along the surface. While a
|
|
72
|
+
shield stands, the bar reaches across to it, so a ball rolls over both. A goal frame that changes shape (a shield going
|
|
73
|
+
up, a goal growing or shrinking, the ball resizing) never scores by itself: the ball goes to the field side of a shield,
|
|
74
|
+
rides a bar that moved through it, or goes to just in front of a goal line that grew past it. Nothing acts on players or
|
|
75
|
+
earns energy during a goal pause or a kickoff. A ball on the top of a bar or a shield rolls off toward the field.
|
|
76
|
+
|
|
77
|
+
`tests/sim/goal-frames.test.ts` runs seeded goal-mouth scrambles (`tests/sim/frame-fuzz.ts`: every character, ball
|
|
78
|
+
size and goal size, the bouncy ball, shots, shields on either goal, push-heavy attackers, frames changing mid-play;
|
|
79
|
+
1200 in the suite, `FRAME_FUZZ_RUNS=20000` for a long run) and counts, failing on any:
|
|
80
|
+
- a goal into a goal whose shield stood before the tick;
|
|
81
|
+
- in play, a tick with the ball's centre behind a standing shield (on its goal side, below its top);
|
|
82
|
+
- any tick with the ball in the grass;
|
|
83
|
+
- in play and in a goal pause, a tick ending with the ball overlapping a crossbar or a standing shield;
|
|
84
|
+
- a tick on which the ball's centre crossed a crossbar's middle line within the bar's length (a tick on which that
|
|
85
|
+
bar's height changed is skipped);
|
|
86
|
+
- in play, with no player near the ball before and after and no frame changed that tick, a tick on which it moved
|
|
87
|
+
further than its speed carries it;
|
|
88
|
+
- in a goal pause or a kickoff, a kick, header, special, pickup or player bounce, or a change in either player's energy.
|
|
89
|
+
- any tick with a non-finite ball position or speed.
|
|
90
|
+
|
|
91
|
+
It also replays the saved states in `tests/fixtures/` (pushes that once went through a shield, and a squeeze that once
|
|
92
|
+
left the ball inside one).
|
|
93
|
+
|
|
94
|
+
The simulation uses only arithmetic every JavaScript engine rounds the same way: of `Math`, only `abs`, `ceil`,
|
|
95
|
+
`floor`, `imul`, `max`, `min`, `round`, `sign`, `sqrt` and `trunc`, and no `**` (`tests/sim/purity.test.ts` checks),
|
|
96
|
+
so a browser's prediction steps exactly as the room does.
|
|
97
|
+
|
|
98
|
+
## Events
|
|
99
|
+
|
|
100
|
+
`SimEvent` (`src/sim/events.ts`): `kick`, `header` (also the titan charge's smash), `bounce` (`surface`: ground, wall,
|
|
101
|
+
ceiling, player, shield; `thunder: true` on a thunder slam), `post`, `goal` (`scorer`, `points`, `ownGoal`, `score`,
|
|
102
|
+
`golden`), `powerupSpawn`, `powerupPick` (`byBall` when the ball collected it), `effectEnd`, `special` (`kind`), and
|
|
103
|
+
`whistle` (`kickoff`, `goldenGoal`, `end`).
|
|
104
|
+
|
|
105
|
+
## Characters, specials and power-ups
|
|
106
|
+
|
|
107
|
+
`CHARACTER_IDS`, `CHARACTER_SPECIALS`, `STARTER_CHARACTERS`, `CHARACTER_UNLOCK_AFTER`, `specialOf(id)`.
|
|
108
|
+
|
|
109
|
+
| Special | Behaviour |
|
|
110
|
+
|---|---|
|
|
111
|
+
| `fireShot` | Flat fireball at 1700, no gravity for 0.75 s; knocks back an opponent it reaches |
|
|
112
|
+
| `windCurve` | Shot whose height swings in an S for 1.2 s, without gravity |
|
|
113
|
+
| `iceShot` | Shot that freezes the opponent it reaches for 2 s |
|
|
114
|
+
| `ghostBall` | Shot that is nearly invisible (`mode: 'ghost'`) for 1.2 s |
|
|
115
|
+
| `thunderDrop` | High lob that peaks in front of the opponent's goal and slams straight down, stunning opponents near it |
|
|
116
|
+
| `titanCharge` | 0.5 s dash with a giant head (scale 2); smashes the ball forward and knocks the opponent back |
|
|
117
|
+
|
|
118
|
+
A special needs a full meter (`energyFull(p)`). Pressed with the ball within `SPECIAL_REACH` it fires at once;
|
|
119
|
+
otherwise it waits armed (`specialArmed`) and fires on the player's next touch. The titan charge always fires at once.
|
|
120
|
+
Energy comes from time, touches, kicks and headers.
|
|
121
|
+
|
|
122
|
+
Power-ups (`POWERUP_KINDS`, 7 s unless noted): `bigHead`, `shrinkFoe`, `bigGoalFoe`, `smallGoalSelf`, `bigBall`,
|
|
123
|
+
`smallBall`, `freezeFoe` (2 s), `speedBoost`, `fireShot` (the next kick is a fireball), `shield` (6 s), `magnet`,
|
|
124
|
+
`bouncyBall`, `reverseFoe` (5 s), `doubleGoal` (next goal counts 2, until scored or 15 s), `wind`. One drops every 6 to
|
|
125
|
+
9 s at a random x in [300, 1300], at most two on the field; a player or the ball (for its last toucher) collects it.
|
|
126
|
+
`effectTarget(kind, owner)` and `effectDuration(kind)` describe each one.
|
|
127
|
+
|
|
128
|
+
## Bot
|
|
129
|
+
|
|
130
|
+
`botInput(state, player, difficulty, rng)` returns the bot's `InputFrame` for this tick. `difficulty` is 1 (a beginner
|
|
131
|
+
can beat it) to 5 (strong: reads the ball's flight, jumps for headers, kicks, uses its special, fetches power-ups).
|
|
132
|
+
From level 2 up it hangs back on its own goal's side while the opponent has the ball, further at higher levels, so a
|
|
133
|
+
match between two level-3 bots ends with about 4 to 8 goals (5.3 on average over 40 seeds).
|
|
134
|
+
Give it its own `createRng(seed)`; it draws from it every tick, so it plays the same way for the same seed.
|
|
135
|
+
|
|
136
|
+
## Debug hooks
|
|
137
|
+
|
|
138
|
+
For a QA menu and tests only; never call them on an online match.
|
|
139
|
+
|
|
140
|
+
- `debugSpawnPowerUp(state, kind, x, y?)`: drops an item of `kind` at `x` (from the sky, or at height `y`).
|
|
141
|
+
- `debugFillEnergy(state, player)`: fills the meter.
|
|
142
|
+
- `debugSetMatchTime(state, seconds)`: sets the regular time left (0 ends it on the next tick of play).
|
|
143
|
+
|
|
144
|
+
## Online
|
|
145
|
+
|
|
146
|
+
The room is `head-clash` (`ONLINE_ROOM`), protocol `ONLINE_PROTOCOL` = 1, a public quick match of two that starts 3 s
|
|
147
|
+
after the second player joins and closes after the match. It runs at 60 Hz and sends a snapshot every 2 ticks.
|
|
148
|
+
|
|
149
|
+
- Input: one `WireInput` per tick, `encodeInput(frame)` from `sim` (a bitmask of `INPUT_BITS`); send one every tick.
|
|
150
|
+
- Profile: `{ character }`, one of `CHARACTER_IDS`; send it with `setProfile` before the countdown ends.
|
|
151
|
+
- State: `readSnapshot(message)` gives `{ tick, state, events }` with the full `MatchState` (null when malformed).
|
|
152
|
+
Slot 0 plays player 0. Events carry the room tick they happened on.
|
|
153
|
+
- End: `HeadClashResult = { winner: 0 | 1 | null, reason: 'finished' | 'forfeit', score }`.
|
|
154
|
+
- Prediction: wrap `new HeadClashPredictedSim(mySlot)` in `ReplayPredictor` from `@maco-online/online-core`;
|
|
155
|
+
`takeOwnEvents()` returns the player's own kicks, headers and specials as soon as they are predicted.
|
|
156
|
+
|
|
157
|
+
## Development
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
pnpm --filter @maco-online/head-clash-rules typecheck
|
|
161
|
+
pnpm --filter @maco-online/head-clash-rules test
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Any change under `src` bumps both `version` and `maco.protocolVersion` in `package.json` (see the repository README).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { RoomGameDefinition } from '@maco-online/online-core';
|
|
2
|
+
import type { SnapshotMessage, WireInput } from './net/wire.ts';
|
|
3
|
+
import type { HeadClashProfile } from './room-match.ts';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { HeadClashRoomMatch } from './room-match.ts';
|
|
6
|
+
/** A quick match has nothing to choose before it starts. */
|
|
7
|
+
declare const settingsSchema: z.ZodObject<{}, z.core.$strict>;
|
|
8
|
+
export type HeadClashSettings = z.infer<typeof settingsSchema>;
|
|
9
|
+
export type HeadClashDefinition = RoomGameDefinition<WireInput, HeadClashSettings, HeadClashProfile, SnapshotMessage, HeadClashRoomMatch>;
|
|
10
|
+
/**
|
|
11
|
+
* Head Clash online: a public quick match of two players. The room starts it a moment after the second player arrives
|
|
12
|
+
* and closes once it is over, so there is no host and no rematch. Every member gets the same snapshot; each browser
|
|
13
|
+
* knows its side from its slot.
|
|
14
|
+
*/
|
|
15
|
+
export declare const headClashDefinition: HeadClashDefinition;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { IDLE_INPUT, mergeInputs, ONLINE_PROTOCOL, ONLINE_ROOM, ONLINE_TICK_RATE, SNAPSHOT_EVERY } from "./net/wire.js";
|
|
3
|
+
import { INPUT_MASK } from "./sim/input.js";
|
|
4
|
+
import { CHARACTER_IDS } from "./sim/types.js";
|
|
5
|
+
import { DEFAULT_CHARACTER, HeadClashRoomMatch } from "./room-match.js";
|
|
6
|
+
const inputSchema = z.int().min(0).max(INPUT_MASK);
|
|
7
|
+
/** A quick match has nothing to choose before it starts. */
|
|
8
|
+
const settingsSchema = z.strictObject({});
|
|
9
|
+
/**
|
|
10
|
+
* Each player picks the character they play, any of the six. Unlocking characters is the client's tournament
|
|
11
|
+
* progression, which the server cannot see or enforce; it does not need to, since characters differ only in head height
|
|
12
|
+
* and special, not in strength.
|
|
13
|
+
*/
|
|
14
|
+
const profileSchema = z.strictObject({ character: z.enum(CHARACTER_IDS) });
|
|
15
|
+
/**
|
|
16
|
+
* Head Clash online: a public quick match of two players. The room starts it a moment after the second player arrives
|
|
17
|
+
* and closes once it is over, so there is no host and no rematch. Every member gets the same snapshot; each browser
|
|
18
|
+
* knows its side from its slot.
|
|
19
|
+
*/
|
|
20
|
+
export const headClashDefinition = {
|
|
21
|
+
id: ONLINE_ROOM,
|
|
22
|
+
protocolVersion: ONLINE_PROTOCOL,
|
|
23
|
+
visibility: 'public',
|
|
24
|
+
maxMembers: 2,
|
|
25
|
+
tickRate: ONLINE_TICK_RATE,
|
|
26
|
+
stateEvery: SNAPSHOT_EVERY,
|
|
27
|
+
// The client counts it down as "KICKOFF IN 3"; a player may still change their character meanwhile.
|
|
28
|
+
autoStart: { countdownMs: 3000 },
|
|
29
|
+
afterMatch: 'close',
|
|
30
|
+
idleInput: IDLE_INPUT,
|
|
31
|
+
// Two inputs in one tick keep the newest direction and every kick, special and jump.
|
|
32
|
+
mergeInput: mergeInputs,
|
|
33
|
+
// Each browser sends one input per tick and predicts its own player from the acknowledged one; six ticks at 60 Hz are
|
|
34
|
+
// the same 100 ms cap as Shuttle Blitz's twelve at 120 Hz.
|
|
35
|
+
inputPlayout: { maxTicks: 6, steady: true },
|
|
36
|
+
inputSchema,
|
|
37
|
+
settingsSchema,
|
|
38
|
+
profileSchema,
|
|
39
|
+
defaultSettings: () => ({}),
|
|
40
|
+
defaultProfile: () => ({ character: DEFAULT_CHARACTER }),
|
|
41
|
+
createMatch: (_, members) => new HeadClashRoomMatch(members)
|
|
42
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { HeadClashDefinition, HeadClashSettings } from './definition.ts';
|
|
2
|
+
export { headClashDefinition } from './definition.ts';
|
|
3
|
+
export type { HeadClashProfile, HeadClashRoomMatchOptions } from './room-match.ts';
|
|
4
|
+
export { DEFAULT_CHARACTER, HeadClashRoomMatch } from './room-match.ts';
|
|
5
|
+
export type { EndMessage as HeadClashResult } from './net/wire.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { PredictedSim } from '@maco-online/online-core';
|
|
2
|
+
import type { MatchState } from '../sim/state.ts';
|
|
3
|
+
import type { Side } from '../sim/types.ts';
|
|
4
|
+
import type { SnapshotMessage, TimedEvent, WireInput } from './wire.ts';
|
|
5
|
+
export declare class HeadClashPredictedSim implements PredictedSim<SnapshotMessage, WireInput> {
|
|
6
|
+
readonly side: Side;
|
|
7
|
+
private match;
|
|
8
|
+
private baseTick;
|
|
9
|
+
private steps;
|
|
10
|
+
private own;
|
|
11
|
+
constructor(side: Side);
|
|
12
|
+
/** The predicted match, or null before the first snapshot. */
|
|
13
|
+
get state(): Readonly<MatchState> | null;
|
|
14
|
+
/** The room tick the prediction has reached: the restored snapshot's tick plus the ticks stepped since. */
|
|
15
|
+
get tick(): number;
|
|
16
|
+
/** Replaces the prediction with the room's match. Throws a RangeError on a malformed snapshot. */
|
|
17
|
+
restore(snapshot: SnapshotMessage): void;
|
|
18
|
+
step(input: WireInput, replaying: boolean): void;
|
|
19
|
+
/** This player's own events predicted since the last call, stamped with their tick; each is handed out once. */
|
|
20
|
+
takeOwnEvents(): TimedEvent[];
|
|
21
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { decodeInput } from "../sim/input.js";
|
|
2
|
+
import { stepMatch } from "../sim/match.js";
|
|
3
|
+
import { other } from "../sim/types.js";
|
|
4
|
+
import { decodeState } from "./wire.js";
|
|
5
|
+
/** Events a player's own actions cause, which their browser plays as soon as it predicts them. */
|
|
6
|
+
function isOwnEvent(event, side) {
|
|
7
|
+
switch (event.type) {
|
|
8
|
+
case 'kick':
|
|
9
|
+
case 'header':
|
|
10
|
+
case 'special':
|
|
11
|
+
return event.player === side;
|
|
12
|
+
default:
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export class HeadClashPredictedSim {
|
|
17
|
+
side;
|
|
18
|
+
match = null;
|
|
19
|
+
baseTick = 0;
|
|
20
|
+
steps = 0;
|
|
21
|
+
own = [];
|
|
22
|
+
constructor(side) {
|
|
23
|
+
this.side = side;
|
|
24
|
+
}
|
|
25
|
+
/** The predicted match, or null before the first snapshot. */
|
|
26
|
+
get state() {
|
|
27
|
+
return this.match;
|
|
28
|
+
}
|
|
29
|
+
/** The room tick the prediction has reached: the restored snapshot's tick plus the ticks stepped since. */
|
|
30
|
+
get tick() {
|
|
31
|
+
return this.baseTick + this.steps;
|
|
32
|
+
}
|
|
33
|
+
/** Replaces the prediction with the room's match. Throws a RangeError on a malformed snapshot. */
|
|
34
|
+
restore(snapshot) {
|
|
35
|
+
// Forget the old match first: if this snapshot cannot be rebuilt, nothing goes on predicting from a stale one.
|
|
36
|
+
this.match = null;
|
|
37
|
+
this.match = decodeState(snapshot.state);
|
|
38
|
+
this.baseTick = snapshot.tick;
|
|
39
|
+
this.steps = 0;
|
|
40
|
+
}
|
|
41
|
+
step(input, replaying) {
|
|
42
|
+
const match = this.match;
|
|
43
|
+
if (!match) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// The opponent keeps the keys they held, as the room does for a member who sent nothing new.
|
|
47
|
+
const mine = decodeInput(input);
|
|
48
|
+
const theirs = decodeInput(match.players[other(this.side)].input);
|
|
49
|
+
const inputs = this.side === 0 ? [mine, theirs] : [theirs, mine];
|
|
50
|
+
const events = stepMatch(match, inputs);
|
|
51
|
+
this.steps++;
|
|
52
|
+
if (!replaying) {
|
|
53
|
+
for (const event of events) {
|
|
54
|
+
if (isOwnEvent(event, this.side)) {
|
|
55
|
+
this.own.push({ tick: this.tick, event });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** This player's own events predicted since the last call, stamped with their tick; each is handed out once. */
|
|
61
|
+
takeOwnEvents() {
|
|
62
|
+
const out = this.own;
|
|
63
|
+
this.own = [];
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { SimEvent } from '../sim/events.ts';
|
|
2
|
+
import type { MatchState } from '../sim/state.ts';
|
|
3
|
+
import type { Side } from '../sim/types.ts';
|
|
4
|
+
/** Bump when a client and a room can no longer talk to each other; the room refuses a client that sends another one. */
|
|
5
|
+
export declare const ONLINE_PROTOCOL = 1;
|
|
6
|
+
/** The room's name on the Colyseus server, the ticket's `game` and the Maco game key. */
|
|
7
|
+
export declare const ONLINE_ROOM = "head-clash";
|
|
8
|
+
/** Simulation and input rate in Hz: one input advances the match exactly one tick. */
|
|
9
|
+
export declare const ONLINE_TICK_RATE = 60;
|
|
10
|
+
export declare const ONLINE_STEP: number;
|
|
11
|
+
/** The room sends a snapshot every this many ticks (30 Hz). */
|
|
12
|
+
export declare const SNAPSHOT_EVERY = 2;
|
|
13
|
+
export declare const SNAPSHOT_INTERVAL_MS: number;
|
|
14
|
+
/** One tick of controls as it travels: a mask of INPUT_BITS. */
|
|
15
|
+
export type WireInput = number;
|
|
16
|
+
export declare const IDLE_INPUT: WireInput;
|
|
17
|
+
/** Folds two inputs that reached the room in one tick: the newest direction, and every action either one held. */
|
|
18
|
+
export declare function mergeInputs(pending: WireInput, next: WireInput): WireInput;
|
|
19
|
+
/** A simulation event and the room tick it happened on, so a client plays it when its picture reaches that tick. */
|
|
20
|
+
export interface TimedEvent {
|
|
21
|
+
tick: number;
|
|
22
|
+
event: SimEvent;
|
|
23
|
+
}
|
|
24
|
+
export type EndReason = 'finished' | 'forfeit';
|
|
25
|
+
/** The outcome every member is sent as `end`. `winner` null is a draw (golden goal ran out). */
|
|
26
|
+
export interface EndMessage {
|
|
27
|
+
winner: Side | null;
|
|
28
|
+
reason: EndReason;
|
|
29
|
+
score: [number, number];
|
|
30
|
+
}
|
|
31
|
+
/** What the room broadcasts: the match encoded by `encodeState`, the room tick it belongs to, and the events since. */
|
|
32
|
+
export interface SnapshotMessage {
|
|
33
|
+
tick: number;
|
|
34
|
+
state: number[];
|
|
35
|
+
events?: TimedEvent[];
|
|
36
|
+
}
|
|
37
|
+
/** A snapshot read back: the full match state. */
|
|
38
|
+
export interface DecodedSnapshot {
|
|
39
|
+
tick: number;
|
|
40
|
+
state: MatchState;
|
|
41
|
+
events: TimedEvent[];
|
|
42
|
+
}
|
|
43
|
+
/** The match as a flat list of numbers. */
|
|
44
|
+
export declare function encodeState(state: Readonly<MatchState>): number[];
|
|
45
|
+
/** The match `encodeState` wrote. Throws a RangeError on anything malformed. */
|
|
46
|
+
export declare function decodeState(data: readonly unknown[]): MatchState;
|
|
47
|
+
/** The snapshot message for `state` at room tick `tick`, with the events since the previous one. */
|
|
48
|
+
export declare function snapshotOf(state: Readonly<MatchState>, tick: number, events: readonly TimedEvent[]): SnapshotMessage;
|
|
49
|
+
/** True when `value` has the outer shape of a snapshot; `readSnapshot` checks the state itself. */
|
|
50
|
+
export declare function isSnapshot(value: unknown): value is SnapshotMessage;
|
|
51
|
+
/** The match and events of a snapshot message, or null if it is malformed, so nothing broken reaches a renderer. */
|
|
52
|
+
export declare function readSnapshot(value: unknown): DecodedSnapshot | null;
|
package/dist/net/wire.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { TICK_RATE } from "../sim/constants.js";
|
|
2
|
+
import { INPUT_BITS } from "../sim/input.js";
|
|
3
|
+
import { ANIM_STATES, BALL_MODES, CHARACTER_IDS, PHASES, POWERUP_KINDS } from "../sim/types.js";
|
|
4
|
+
/** Bump when a client and a room can no longer talk to each other; the room refuses a client that sends another one. */
|
|
5
|
+
export const ONLINE_PROTOCOL = 1;
|
|
6
|
+
/** The room's name on the Colyseus server, the ticket's `game` and the Maco game key. */
|
|
7
|
+
export const ONLINE_ROOM = 'head-clash';
|
|
8
|
+
/** Simulation and input rate in Hz: one input advances the match exactly one tick. */
|
|
9
|
+
export const ONLINE_TICK_RATE = TICK_RATE;
|
|
10
|
+
export const ONLINE_STEP = 1 / ONLINE_TICK_RATE;
|
|
11
|
+
/** The room sends a snapshot every this many ticks (30 Hz). */
|
|
12
|
+
export const SNAPSHOT_EVERY = 2;
|
|
13
|
+
export const SNAPSHOT_INTERVAL_MS = (1000 * SNAPSHOT_EVERY) / ONLINE_TICK_RATE;
|
|
14
|
+
export const IDLE_INPUT = 0;
|
|
15
|
+
/** Bits that are presses (kick, special) or worth keeping for a tick (jump): never lost when two inputs fold together. */
|
|
16
|
+
const ACTION_BITS = INPUT_BITS.jump | INPUT_BITS.kick | INPUT_BITS.special;
|
|
17
|
+
/** Folds two inputs that reached the room in one tick: the newest direction, and every action either one held. */
|
|
18
|
+
export function mergeInputs(pending, next) {
|
|
19
|
+
return (next & ~ACTION_BITS) | ((pending | next) & ACTION_BITS);
|
|
20
|
+
}
|
|
21
|
+
class WireError extends Error {
|
|
22
|
+
}
|
|
23
|
+
const num = { enc: v => v, dec: n => n };
|
|
24
|
+
const int = {
|
|
25
|
+
enc: v => v,
|
|
26
|
+
dec: (n) => {
|
|
27
|
+
if (!Number.isInteger(n)) {
|
|
28
|
+
throw new WireError(`expected an integer, got ${n}`);
|
|
29
|
+
}
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const bool = {
|
|
34
|
+
enc: v => (v ? 1 : 0),
|
|
35
|
+
dec: (n) => {
|
|
36
|
+
if (n !== 0 && n !== 1) {
|
|
37
|
+
throw new WireError(`expected 0 or 1, got ${n}`);
|
|
38
|
+
}
|
|
39
|
+
return n === 1;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function oneOf(list) {
|
|
43
|
+
return {
|
|
44
|
+
enc: v => list.indexOf(v),
|
|
45
|
+
dec: (n) => {
|
|
46
|
+
const value = list[n];
|
|
47
|
+
if (value === undefined) {
|
|
48
|
+
throw new WireError(`no value at index ${n}`);
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const side = {
|
|
55
|
+
enc: v => v,
|
|
56
|
+
dec: (n) => {
|
|
57
|
+
if (n !== 0 && n !== 1) {
|
|
58
|
+
throw new WireError(`expected a side, got ${n}`);
|
|
59
|
+
}
|
|
60
|
+
return n;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/** A side or nobody, as -1. */
|
|
64
|
+
const maybeSide = {
|
|
65
|
+
enc: v => (v === null ? -1 : v),
|
|
66
|
+
dec: n => (n === -1 ? null : side.dec(n))
|
|
67
|
+
};
|
|
68
|
+
const facing = {
|
|
69
|
+
enc: v => v,
|
|
70
|
+
dec: (n) => {
|
|
71
|
+
if (n !== 1 && n !== -1) {
|
|
72
|
+
throw new WireError(`expected a facing, got ${n}`);
|
|
73
|
+
}
|
|
74
|
+
return n;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const PLAYER = {
|
|
78
|
+
side,
|
|
79
|
+
character: oneOf(CHARACTER_IDS),
|
|
80
|
+
x: num,
|
|
81
|
+
y: num,
|
|
82
|
+
vx: num,
|
|
83
|
+
vy: num,
|
|
84
|
+
onGround: bool,
|
|
85
|
+
facing,
|
|
86
|
+
headScale: num,
|
|
87
|
+
frozen: bool,
|
|
88
|
+
energy: num,
|
|
89
|
+
kickTicks: int,
|
|
90
|
+
kickHit: bool,
|
|
91
|
+
headerTicks: int,
|
|
92
|
+
specialTicks: int,
|
|
93
|
+
specialArmed: bool,
|
|
94
|
+
dashTicks: int,
|
|
95
|
+
dashHitBall: bool,
|
|
96
|
+
dashHitFoe: bool,
|
|
97
|
+
stunTicks: int,
|
|
98
|
+
touchCooldown: int,
|
|
99
|
+
input: int,
|
|
100
|
+
anim: oneOf(ANIM_STATES),
|
|
101
|
+
animTicks: int
|
|
102
|
+
};
|
|
103
|
+
const BALL = {
|
|
104
|
+
x: num,
|
|
105
|
+
y: num,
|
|
106
|
+
vx: num,
|
|
107
|
+
vy: num,
|
|
108
|
+
r: num,
|
|
109
|
+
lastToucher: maybeSide,
|
|
110
|
+
mode: oneOf(BALL_MODES),
|
|
111
|
+
modeTicks: int,
|
|
112
|
+
modeOwner: maybeSide,
|
|
113
|
+
modeAge: int
|
|
114
|
+
};
|
|
115
|
+
const GOAL = { crossbarY: num, depth: num, shield: bool };
|
|
116
|
+
const ITEM = { id: int, kind: oneOf(POWERUP_KINDS), x: num, y: num, landed: bool, age: int };
|
|
117
|
+
const EFFECT = { kind: oneOf(POWERUP_KINDS), owner: side, target: side, ticks: int };
|
|
118
|
+
const HEADER = {
|
|
119
|
+
tick: int,
|
|
120
|
+
phase: oneOf(PHASES),
|
|
121
|
+
phaseTicks: int,
|
|
122
|
+
clockTicks: int,
|
|
123
|
+
goldenGoal: bool,
|
|
124
|
+
goldenTicks: int,
|
|
125
|
+
nextItemTicks: int,
|
|
126
|
+
nextItemId: int,
|
|
127
|
+
powerUps: bool,
|
|
128
|
+
lastScorer: maybeSide,
|
|
129
|
+
winner: maybeSide,
|
|
130
|
+
rng: int
|
|
131
|
+
};
|
|
132
|
+
/** More items or effects than a match can hold means a corrupt message. */
|
|
133
|
+
const MAX_LIST = 32;
|
|
134
|
+
function write(out, value, spec) {
|
|
135
|
+
for (const key of Object.keys(spec)) {
|
|
136
|
+
out.push(spec[key].enc(value[key]));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
class Reader {
|
|
140
|
+
data;
|
|
141
|
+
i = 0;
|
|
142
|
+
constructor(data) {
|
|
143
|
+
this.data = data;
|
|
144
|
+
}
|
|
145
|
+
next() {
|
|
146
|
+
if (this.i >= this.data.length) {
|
|
147
|
+
throw new WireError('the state ends early');
|
|
148
|
+
}
|
|
149
|
+
const value = this.data[this.i++];
|
|
150
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
151
|
+
throw new WireError(`expected a number at ${this.i - 1}`);
|
|
152
|
+
}
|
|
153
|
+
return value;
|
|
154
|
+
}
|
|
155
|
+
record(spec) {
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const key of Object.keys(spec)) {
|
|
158
|
+
out[key] = spec[key].dec(this.next());
|
|
159
|
+
}
|
|
160
|
+
// Every key of the spec, which by its type is every key of T, was just read.
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
list(spec) {
|
|
164
|
+
const count = int.dec(this.next());
|
|
165
|
+
if (count < 0 || count > MAX_LIST) {
|
|
166
|
+
throw new WireError(`a list of ${count}`);
|
|
167
|
+
}
|
|
168
|
+
return Array.from({ length: count }, () => this.record(spec));
|
|
169
|
+
}
|
|
170
|
+
end() {
|
|
171
|
+
if (this.i !== this.data.length) {
|
|
172
|
+
throw new WireError('the state has extra values');
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** The match as a flat list of numbers. */
|
|
177
|
+
export function encodeState(state) {
|
|
178
|
+
const out = [];
|
|
179
|
+
write(out, state, HEADER);
|
|
180
|
+
out.push(state.score[0], state.score[1]);
|
|
181
|
+
write(out, state.players[0], PLAYER);
|
|
182
|
+
write(out, state.players[1], PLAYER);
|
|
183
|
+
write(out, state.ball, BALL);
|
|
184
|
+
write(out, state.goals[0], GOAL);
|
|
185
|
+
write(out, state.goals[1], GOAL);
|
|
186
|
+
out.push(state.items.length);
|
|
187
|
+
for (const item of state.items) {
|
|
188
|
+
write(out, item, ITEM);
|
|
189
|
+
}
|
|
190
|
+
out.push(state.effects.length);
|
|
191
|
+
for (const effect of state.effects) {
|
|
192
|
+
write(out, effect, EFFECT);
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
/** The match `encodeState` wrote. Throws a RangeError on anything malformed. */
|
|
197
|
+
export function decodeState(data) {
|
|
198
|
+
try {
|
|
199
|
+
const reader = new Reader(data);
|
|
200
|
+
const header = reader.record(HEADER);
|
|
201
|
+
const score = [int.dec(reader.next()), int.dec(reader.next())];
|
|
202
|
+
const players = [reader.record(PLAYER), reader.record(PLAYER)];
|
|
203
|
+
if (players[0].side !== 0 || players[1].side !== 1) {
|
|
204
|
+
throw new WireError('players out of order');
|
|
205
|
+
}
|
|
206
|
+
const ball = reader.record(BALL);
|
|
207
|
+
const goals = [reader.record(GOAL), reader.record(GOAL)];
|
|
208
|
+
const items = reader.list(ITEM);
|
|
209
|
+
const effects = reader.list(EFFECT);
|
|
210
|
+
reader.end();
|
|
211
|
+
return { ...header, score, players, ball, goals, items, effects };
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof WireError) {
|
|
215
|
+
throw new RangeError(`decodeState: ${error.message}`);
|
|
216
|
+
}
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const round = (value) => Math.round(value * 10) / 10;
|
|
221
|
+
/** An event with its floats trimmed to a tenth: events are only drawn and heard, never simulated. */
|
|
222
|
+
function compactEvent(event) {
|
|
223
|
+
const out = {};
|
|
224
|
+
for (const [key, value] of Object.entries(event)) {
|
|
225
|
+
out[key] = typeof value === 'number' && !Number.isInteger(value) ? round(value) : value;
|
|
226
|
+
}
|
|
227
|
+
// Same keys and kinds of values as `event`, only rounded.
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
/** The snapshot message for `state` at room tick `tick`, with the events since the previous one. */
|
|
231
|
+
export function snapshotOf(state, tick, events) {
|
|
232
|
+
return {
|
|
233
|
+
tick,
|
|
234
|
+
state: encodeState(state),
|
|
235
|
+
...(events.length ? { events: events.map(e => ({ tick: e.tick, event: compactEvent(e.event) })) } : {})
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** True when `value` has the outer shape of a snapshot; `readSnapshot` checks the state itself. */
|
|
239
|
+
export function isSnapshot(value) {
|
|
240
|
+
if (!value || typeof value !== 'object') {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
const message = value;
|
|
244
|
+
return Number.isInteger(message.tick) && Array.isArray(message.state)
|
|
245
|
+
&& (message.events === undefined || Array.isArray(message.events));
|
|
246
|
+
}
|
|
247
|
+
/** The match and events of a snapshot message, or null if it is malformed, so nothing broken reaches a renderer. */
|
|
248
|
+
export function readSnapshot(value) {
|
|
249
|
+
if (!isSnapshot(value)) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const events = (value.events ?? []).filter(isTimedEvent);
|
|
254
|
+
return { tick: value.tick, state: decodeState(value.state), events };
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function isTimedEvent(value) {
|
|
261
|
+
if (!value || typeof value !== 'object') {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
const timed = value;
|
|
265
|
+
return Number.isInteger(timed.tick) && !!timed.event && typeof timed.event === 'object' && typeof timed.event.type === 'string';
|
|
266
|
+
}
|