1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 | /**
* TypeScript smoke-compile of peer-kit's public API — the tripwire for
* `types/*.d.ts` drift (dev/docs/CLJS.md). It is not run; `npm run check`
* type-checks it with `tsc --noEmit -p test/types`.
*
* It exercises exactly the constructs real consumers use, and the FIRST
* section is the bot's actual value-level import list (bot/src/bot/*.cljs, the
* sole consumer) so a rename there fails here rather than at the bot's next
* build:
*
* bot.rooms GAMES SeanceClient NeonGridClient TesseraClient
* LampionClient OdeonClient ValleyBlocksClient
* bot.main loadIdentity Social installOrigin installBrowserGlobals
* fleet.link loadIdentity suiteFriendLink
* fleet.bootstrap parseFriendLink
* fleet.matchmaker GAMES newRoomSecret
* rl.train SeanceGym NeonGridGym ValleyBlocksGym mulberry32
* rl.valleyblocks_policy boardMetrics stockPick
*/
import {
GAMES,
SeanceClient,
NeonGridClient,
TesseraClient,
LampionClient,
OdeonClient,
ValleyBlocksClient,
loadIdentity,
Social,
installOrigin,
installBrowserGlobals,
suiteFriendLink,
parseFriendLink,
newRoomSecret,
SeanceGym,
NeonGridGym,
ValleyBlocksGym,
mulberry32,
boardMetrics,
stockPick,
} from "ardegazu-peer-kit";
// …and the rest of the root surface, so nothing silently disappears.
import {
connect,
createNet,
RoomPeer,
SIGNAL,
DEFAULT_ORIGIN,
GameRoom,
HostDriver,
SeanceHost,
NeonGridHost,
ValleyBlocksHost,
SeanceSim,
NeonGridSim,
ValleyBlocksSim,
ValleyBlocksEngine,
enumeratePlacements,
executePlacement,
placementStep,
planOf,
dellacherieScore,
snakeStep,
buildFriendLink,
SUITE_APPS,
mintRoomUrl,
} from "ardegazu-peer-kit";
import type {
AppDef,
GameName,
Net,
NetConfig,
NetIdentity,
PeerIdent,
ConnectOptions,
GameRoomOptions,
GameRoomEvents,
HostDriverLike,
SeanceOptions,
SeanceView,
NeonGridOptions,
NeonGridView,
TesseraOptions,
LampionOptions,
OdeonOptions,
ValleyBlocksOptions,
ValleyBlocksView,
ValleyBlocksPace,
SuiteIdentity,
LoadIdentityOptions,
SocialOptions,
SocialEvents,
SuiteAppDef,
HostOptions,
HostMatchPolicy,
SeanceHostOptions,
ValleyBlocksHostOptions,
BoardState,
PartyMode,
RoundReason,
VBFrame,
VBCandidate,
VBMetrics,
VBPlan,
Rng,
SimEmit,
SimFrame,
SeanceGymView,
SeanceGymOpts,
SeanceGymStep,
NeonGridGymView,
NeonGridGymOpts,
NeonGridGymStep,
ValleyBlocksGymOpts,
ValleyBlocksGymStep,
} from "ardegazu-peer-kit";
// the deep subpath exports the package still publishes
import { GameRoom as GameRoomDeep } from "ardegazu-peer-kit/games/room";
import { mulberry32 as mulberryDeep, type Rng as RngDeep } from "ardegazu-peer-kit/games/host/rng";
import { boardStateOf } from "ardegazu-peer-kit/games/host/valley-blocks-protocol";
import { installOriginWebSocket, loadIdentity as loadIdentityNode } from "ardegazu-peer-kit/node";
// an inline import() type, the way a consumer annotates without importing
type InlineView = import("ardegazu-peer-kit").ValleyBlocksView;
/* ---- values exist and are callable with the documented signatures -------- */
const app: GameName = "valley-blocks";
const def: AppDef = GAMES[app];
const _host: string = def.host;
const _salt: string = def.salt;
const _prefix: string = def.protocolPrefix;
const _descriptor: string = SIGNAL.descriptorUrl;
const _origin: string = DEFAULT_ORIGIN;
const _secret: string = newRoomSecret();
const _suiteApp: SuiteAppDef = SUITE_APPS[0];
const _mint: string = mintRoomUrl("game2.ardegazu.ro");
installOrigin(DEFAULT_ORIGIN);
installOrigin(DEFAULT_ORIGIN, [/\.ardegazu\.ro$/]);
installBrowserGlobals();
installBrowserGlobals("/var/lib/bot/kv.json");
installOriginWebSocket(DEFAULT_ORIGIN);
const rng: Rng = mulberry32(42);
const _r: number = rng();
const _rd: RngDeep = mulberryDeep(1);
/* ---- identity + social --------------------------------------------------- */
async function identityAndSocial(): Promise<void> {
const opts: LoadIdentityOptions = { seedFile: "/var/lib/bot/seed", name: "gazda" };
const suite: SuiteIdentity = await loadIdentity(opts);
const _pub: string = suite.identity.publicKeyB64;
const _seed: string = suite.seed;
const _name: string = suite.profile.name;
const ni: NetIdentity = suite.netIdentity(def.salt);
const _sig: string = await ni.sign("room", "peer");
const _link: string = await suiteFriendLink(suite);
const _also = await loadIdentityNode(opts);
const sopts: SocialOptions = {
suite,
app: "ardegazu.ro",
ns: "bot",
storageFile: "/var/lib/bot/social.json",
autoAcceptFriends: true,
joinLink: () => null,
brains: () => ({ seance: "59500@ab12cd34" }),
// the social-kit 1.2.0 hooks the vendored copy never had
profileSync: { get: () => ({ name: "gazda" }), apply: () => {} },
appState: { ns: "bot", get: () => ({ rooms: 2 }), apply: () => {} },
};
const social: Social = await Social.start(sopts);
social.on("presence", (pub, info) => {
const _p: string = pub;
if (info) {
const _n: string = info.name;
}
});
social.on("request", (f) => {
const _fp: string = f.pub;
});
social.on("invite", (inv) => {
const _u: string = inv.url;
});
const _fl: string = await social.friendLink();
const _agentPub: string = social.agent.myPub;
social.agent.syncNow();
const _stored = social.store.list();
await social.stop();
const parsed = await parseFriendLink("#add=a.b.c");
if (parsed) {
const _pp: string = parsed.pub;
}
const _built: string = buildFriendLink("https://ardegazu.ro/", {
pub: "p", x: "x", xs: "s", name: "n",
});
}
/* ---- rooms: the polymorphic static, events, subclass members ------------- */
async function rooms(): Promise<void> {
const base: GameRoomOptions = { app: "seance", roomSecret: "s", nick: "gazda" };
// `SeanceClient.join(...)` must yield a SeanceClient, not a GameRoom
const seance: SeanceClient = await SeanceClient.join({ ...base, app: "seance" });
const _wins: number = seance.wins;
const _seat: number = seance.seat;
const view: SeanceView = seance.view();
const _bell: number = view.bell;
const _medium: boolean = view.isMedium;
seance.pick(1);
const _started: boolean = seance.startMatch();
if (seance.host) {
const _running: boolean = seance.host.sim.running;
const _haunt: number = seance.host.sim.haunt;
}
seance.on("frame", (from, frame) => {
const _f: string = from;
const _t = frame.t;
});
seance.on("matchEnd", (w) => {
const _w: string | null = w;
});
seance.on("receipt", (rec) => {
const _g: string = rec.g;
});
seance.on("peerIdentity", (_id, ident) => {
const _ip: string = ident.pub;
});
await seance.close();
// the named per-game statics too
const s2: SeanceClient = await SeanceClient.joinSeance({
roomSecret: "s", nick: "n", onTurn: (v: SeanceView) => v.hintNot, actDelayMs: 0,
host: { rng, match: { minPlayers: 2, expectedPlayers: 2, maxMatches: 1 } },
} satisfies SeanceOptions);
await s2.close();
const grid: NeonGridClient = await NeonGridClient.joinGrid({
roomSecret: "s", nick: "n", autopilot: false,
onTick: (v: NeonGridView) => (v.alive ? (v.dir + 1) % 4 : null),
host: { match: { minPlayers: 2 } } satisfies HostOptions,
} satisfies NeonGridOptions);
const gv: NeonGridView = grid.view();
const _cells: Uint8Array = gv.grid;
const _heads: ([number, number] | null)[] = gv.heads;
grid.steer(2);
const _points: number = grid.points;
await grid.close();
const blocks: ValleyBlocksClient = await ValleyBlocksClient.joinBlocks({
roomSecret: "s", nick: "n", forfeit: false,
pace: { inputMs: 110, thinkMs: (l) => 700 - 30 * l } satisfies ValleyBlocksPace,
onPiece: (v: InlineView) => stockPick(v.candidates),
host: { mode: "race-survival", target: 5000, rng } satisfies ValleyBlocksHostOptions,
} satisfies ValleyBlocksOptions);
const _rw: number = blocks.roundWins;
await blocks.close();
const tess: TesseraClient = await TesseraClient.joinTessera({ roomSecret: "s", nick: "n" } satisfies TesseraOptions);
const lamp: LampionClient = await LampionClient.joinLampion({ roomSecret: "s", nick: "n" } satisfies LampionOptions);
const ode: OdeonClient = await OdeonClient.joinOdeon({
roomSecret: "s", nick: "n", instrument: 3, perform: true,
} satisfies OdeonOptions);
await Promise.all([tess.close(), lamp.close(), ode.close()]);
// the base class is constructible and its members typed
const peer: RoomPeer = await connect({ app, roomSecret: "s" } satisfies ConnectOptions);
const room: GameRoom = new GameRoomDeep(peer, base);
const _my: string = room.myId;
const _hosting: boolean = room.hosting;
const _hid: string | null = room.hostId;
const _lb = room.leaderboard;
const _sc: number | null = room.score();
const _cb: boolean = room.claimBeats("aaa", { host: "aaa" });
room.sendToHost({ t: "pk", r: 1 });
room.injectLocal({ t: "ro", host: room.myId, ps: [] });
room.wake();
const driver: HostDriverLike | null = room.hostDriver;
if (driver) driver.onClaimed();
await room.close();
}
/* ---- the raw net layer --------------------------------------------------- */
async function net(): Promise<void> {
const cfg: NetConfig = {
secret: newRoomSecret(),
appSalt: GAMES.seance.salt,
protocolPrefix: GAMES.seance.protocolPrefix,
descriptorUrl: SIGNAL.descriptorUrl,
turnUrl: SIGNAL.turnUrl,
relayFallback: SIGNAL.relayFallback,
identity: null,
webrtc: false,
};
const n: Net = await createNet(cfg, {
onRoomRoster: (peers: string[]) => void peers,
onPeerOpen: () => {},
onPeerGone: () => {},
onMessage: (_from, _payload) => {},
onStatus: () => {},
onPeerIdentity: (_id, ident: PeerIdent) => void ident.pub,
});
const _members: ReadonlySet<string> = n.roomPeers();
const _open: string[] = n.openPeers();
const _count: number = n.openCount();
const _connected: boolean = n.relayConnected();
const _rid: string = n.roomId;
const _id: PeerIdent | null = n.identityOf("x");
n.send("x", { t: "hi" });
n.broadcast({ t: "hi" });
n.wake();
await n.close();
}
/* ---- host sims, drivers, engine, brain ---------------------------------- */
function sims(): void {
const seanceSim = new SeanceSim({
rng,
now: () => 0,
roster: () => [["a", "a", 0, 0]],
addWin: (_id: string) => {},
});
const emit: SimEmit<Record<string, unknown>> = seanceSim.start(1, ["a", "b"]);
const first: SimFrame<Record<string, unknown>> = emit.frames[0];
const _to: string | undefined = first.to;
const _next = emit.next;
const _me = emit.matchEnd;
seanceSim.step("bell");
seanceSim.pick("a", 1);
seanceSim.peerGone("b");
seanceSim.snapshot("late");
seanceSim.abort();
const _order: readonly string[] = seanceSim.order;
const _candles: readonly number[] = seanceSim.candles;
const ngSim = new NeonGridSim({
roster: () => [["a", "a", 0, 0]],
addScore: () => {},
resetScores: () => {},
});
ngSim.newMatch();
ngSim.startRound([{ id: "a", color: 0 }]);
ngSim.input("a", 1);
ngSim.peerGone("a");
ngSim.step("tick");
const _grid: Uint8Array = ngSim.grid;
const mode: PartyMode = "survival";
const vbSim = new ValleyBlocksSim({ roster: () => [["a", "A", 0]], addWin: () => {}, mode, target: 1000 });
const st: SimEmit<VBFrame> = vbSim.startRound(["a", "b"], 7);
const frame: VBFrame = st.frames[0].f;
if (frame.t === "st") {
const _seed: number = frame.seed;
}
const board: BoardState = { grid: ".", score: 0, lines: 0, level: 1, snake: null, over: false };
const verdict = vbSim.onBoardState("a", vbSim.round, 0, board);
const ov = verdict.frames[0]?.f;
if (ov && ov.t === "ov") {
const _reason: RoundReason = ov.reason;
}
vbSim.playerLeft("b");
vbSim.snapshot("late");
const engine = new ValleyBlocksEngine(424243, {
onLock: () => {},
onLinesCleared: (n: number, rows: number[]) => void [n, rows],
onGameOver: () => {},
});
engine.update(0.05);
engine.setSoftDrop(true);
const _stepped: boolean = engine.softStep();
const _moved: boolean = engine.move(-1);
const _rot: boolean = engine.rotate(true);
engine.hardDrop();
const _held: boolean = engine.holdPiece();
const _ghost: number = engine.ghostY;
const _queue = engine.nextQueue;
const _snake = engine.snake;
const _cellGrid = engine.board.grid;
const _state: BoardState = boardStateOf(engine);
const cands: VBCandidate[] = enumeratePlacements(engine);
const metrics: VBMetrics = boardMetrics(cands[0].grid);
const _holes: number = metrics.holes;
const _heights: number[] = metrics.heights;
const _score: number = dellacherieScore(cands[0]);
const idx: number = stockPick(cands);
const plan: VBPlan = planOf(cands[idx]);
const _stepResult: "continue" | "done" = placementStep(engine, plan);
executePlacement(engine, cands[idx]);
snakeStep(engine);
}
/* ---- gyms ---------------------------------------------------------------- */
function gyms(): void {
const sOpts: SeanceGymOpts = { players: 3, seed: 11 };
const sg = new SeanceGym(sOpts);
const sViews: SeanceGymView[] = sg.reset();
const sStep: SeanceGymStep = sg.step(sViews.map((v) => (v.isMedium ? v.hintNot : null)));
const _sw: number | null = sStep.winner;
const _sr: number[] = sStep.rewards;
const _sp: number = sg.players;
const nOpts: NeonGridGymOpts = { players: 2 };
const ng = new NeonGridGym(nOpts);
const nViews: NeonGridGymView[] = ng.reset();
const nStep: NeonGridGymStep = ng.step(nViews.map((v) => (v.alive ? v.dir : null)));
const _nd: boolean = nStep.done;
const vOpts: ValleyBlocksGymOpts = { players: 2, seed: 1, mode: "race", target: 2000, maxPlacements: 100 };
const vg = new ValleyBlocksGym(vOpts);
const vViews: ValleyBlocksView[] = vg.reset();
const vStep: ValleyBlocksGymStep = vg.step(vViews.map((v) => stockPick(v.candidates)));
const _vr: RoundReason | null = vStep.reason;
const _vm: PartyMode = vg.mode;
const _vt: number = vg.target;
}
/* ---- drivers: subclassing and the abstract-ish surface ------------------- */
function drivers(room: GameRoom): void {
const policy: HostMatchPolicy = { minPlayers: 2, expectedPlayers: 4, startTimeoutMs: 25_000, maxMatches: 1 };
const opts: HostOptions = { match: policy };
const sh: SeanceHost = new SeanceHost(room, { ...opts, rng } satisfies SeanceHostOptions);
const nh: NeonGridHost = new NeonGridHost(room, opts);
const vh: ValleyBlocksHost = new ValleyBlocksHost(room, { ...opts, mode: "race", target: 900 });
for (const d of [sh, nh, vh] as HostDriver[]) {
d.onMatchEnd((scores) => void scores[0][2]);
const _now: boolean = d.startNow();
d.onSelfFrame({ t: "hi" });
const _conceded: boolean = d.onForeignClaim("aaa", { host: "aaa" });
d.close();
}
const _simRunning: boolean = sh.sim.running;
const _ngRound: number = nh.sim.round;
const _vbMode: PartyMode = vh.sim.mode;
}
// keep tsc from pruning everything as unused
export { identityAndSocial, rooms, net, sims, gyms, drivers };
export type { GameRoomEvents, SocialEvents };
|