net.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { Packr } from 'msgpackr';
  2. import { afterEach, describe, expect, it } from 'vitest';
  3. import WebSocket from 'ws';
  4. import { loadCharacterStats, loadMap } from '../src/server/assets';
  5. import { Game } from '../src/server/game';
  6. import { GameServer, type GameServerOptions } from '../src/server/net';
  7. import { HASH_CHECK_INTERVAL_S, PROTOCOL_VERSION, START_COUNTDOWN_S, TICK_RATE } from '../src/shared/constants';
  8. import { Button } from '../src/shared/input';
  9. import type { ClientMessage, ServerMessage } from '../src/shared/protocol';
  10. import type { TerrainBitmap } from '../src/shared/terrain/bitmap';
  11. import { applyTerrainEvent } from '../src/shared/terrain/events';
  12. import { ASSETS, realMaterials } from './helpers';
  13. const packr = new Packr({ useRecords: false });
  14. const materials = realMaterials();
  15. const freshTerrain = (): TerrainBitmap => loadMap(ASSETS, 'gateau-etages', materials).terrain;
  16. const flush = (ms = 30): Promise<void> => new Promise((r) => setTimeout(r, ms));
  17. /** A headless client that keeps its own bitmap in sync, like the renderer does. */
  18. class TestClient {
  19. readonly messages: ServerMessage[] = [];
  20. readonly socket: WebSocket;
  21. terrain = freshTerrain();
  22. mapId = 'gateau-etages';
  23. lastSeq = 0;
  24. playerId = -1;
  25. hashChecks: { seq: number; server: number; mine: number }[] = [];
  26. constructor(port: number) {
  27. this.socket = new WebSocket(`ws://127.0.0.1:${port}`);
  28. this.socket.on('message', (data: Buffer) => this.onMessage(packr.unpack(data) as ServerMessage));
  29. }
  30. async hello(name: string, characterId = 'generic', version = PROTOCOL_VERSION): Promise<void> {
  31. await new Promise((r) => this.socket.once('open', r));
  32. this.send({ t: 'hello', version, name, characterId });
  33. }
  34. send(msg: ClientMessage): void {
  35. this.socket.send(packr.pack(msg));
  36. }
  37. last<T extends ServerMessage['t']>(t: T): Extract<ServerMessage, { t: T }> | undefined {
  38. return [...this.messages].reverse().find((m) => m.t === t) as Extract<ServerMessage, { t: T }> | undefined;
  39. }
  40. private onMessage(msg: ServerMessage): void {
  41. this.messages.push(msg);
  42. if (msg.t === 'welcome') {
  43. this.playerId = msg.playerId;
  44. for (const { seq, ev } of msg.events) this.apply(seq, ev);
  45. } else if (msg.t === 'start') {
  46. this.mapId = msg.mapId;
  47. this.terrain = loadMap(ASSETS, msg.mapId, materials).terrain;
  48. this.lastSeq = 0;
  49. } else if (msg.t === 'terrain') {
  50. this.apply(msg.seq, msg.ev);
  51. } else if (msg.t === 'hash') {
  52. expect(this.lastSeq).toBe(msg.seq);
  53. this.hashChecks.push({ seq: msg.seq, server: msg.hash, mine: this.terrain.hash() });
  54. }
  55. }
  56. private apply(seq: number, ev: Parameters<typeof applyTerrainEvent>[1]): void {
  57. expect(seq).toBe(this.lastSeq + 1);
  58. this.lastSeq = seq;
  59. applyTerrainEvent(this.terrain, ev, materials);
  60. }
  61. }
  62. describe('LAN server (M3)', () => {
  63. let server: GameServer | null = null;
  64. const clients: TestClient[] = [];
  65. afterEach(() => {
  66. for (const c of clients) c.socket.close();
  67. clients.length = 0;
  68. server?.close();
  69. server = null;
  70. });
  71. async function startServer(pacing: Partial<GameServerOptions> = {}): Promise<GameServer> {
  72. await new Promise<void>((resolve) => {
  73. server = new GameServer({
  74. maps: [
  75. { id: 'gateau-etages', name: 'Le Gâteau à Étages' },
  76. { id: 'mille-feuille', name: 'Le Mille-Feuille' },
  77. { id: 'piece-montee', name: 'La Pièce Montée' },
  78. ],
  79. ...pacing,
  80. createGame: (seed, rules, stats, mapId) => {
  81. const { definition, terrain } = loadMap(ASSETS, mapId, materials);
  82. return new Game({ map: definition, terrain, materials, seed, rules, stats, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
  83. },
  84. seed: 42,
  85. port: 0,
  86. host: '127.0.0.1',
  87. onListening: resolve,
  88. });
  89. });
  90. return server!;
  91. }
  92. function tick(n: number): void {
  93. for (let i = 0; i < n; i++) server!.tickOnce();
  94. }
  95. it('rejects a client with another protocol version', async () => {
  96. const s = await startServer();
  97. const c = new TestClient(s.port);
  98. clients.push(c);
  99. await c.hello('Vieux', 'generic', PROTOCOL_VERSION - 1);
  100. await flush();
  101. expect(c.last('reject')).toMatchObject({ reason: 'version', serverVersion: PROTOCOL_VERSION });
  102. });
  103. it('lobby → everyone ready → countdown → match on a fresh map, clients stay bit-identical', async () => {
  104. const s = await startServer();
  105. const a = new TestClient(s.port);
  106. const b = new TestClient(s.port);
  107. clients.push(a, b);
  108. await a.hello('Alice');
  109. await b.hello('Bob', 'castor');
  110. await flush();
  111. expect(a.last('lobby')).toMatchObject({ phase: 'lobby', countdown: null });
  112. expect(a.last('lobby')!.players.map((p) => p.name)).toEqual(['Alice', 'Bob']);
  113. // Warm-up destruction, then only one player ready: no countdown.
  114. tick(120);
  115. a.send({ t: 'ready', ready: true });
  116. await flush();
  117. tick(1);
  118. await flush();
  119. expect(b.last('lobby')).toMatchObject({ countdown: null });
  120. b.send({ t: 'ready', ready: true });
  121. await flush();
  122. expect(a.last('lobby')!.countdown).toBe(START_COUNTDOWN_S);
  123. tick(START_COUNTDOWN_S * TICK_RATE);
  124. await flush();
  125. expect(a.last('start')).toBeDefined();
  126. expect(b.last('start')!.players.map((p) => p.id).sort()).toEqual([a.playerId, b.playerId].sort());
  127. expect(a.last('lobby')).toMatchObject({ phase: 'playing' });
  128. // Both dig for a while; snapshots, terrain events and hash checks flow to both clients.
  129. for (let i = 0; i < HASH_CHECK_INTERVAL_S * TICK_RATE * 2; i++) {
  130. if (i % 10 === 0) {
  131. const snap = a.last('snapshot');
  132. for (const [c, dy] of [
  133. [a, 40],
  134. [b, 60],
  135. ] as const) {
  136. const me = snap?.players.find((p) => p.id === c.playerId);
  137. if (me) c.send({ t: 'input', buttons: c === a ? Button.Attack : Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + dy) });
  138. }
  139. await flush(5);
  140. }
  141. tick(1);
  142. }
  143. await flush(100);
  144. expect(a.lastSeq).toBeGreaterThan(5);
  145. for (const c of [a, b]) {
  146. expect(c.hashChecks.length).toBeGreaterThanOrEqual(2);
  147. for (const h of c.hashChecks) expect(h.mine).toBe(h.server);
  148. }
  149. expect(a.terrain.hash()).toBe(b.terrain.hash());
  150. });
  151. it('a player leaving is announced and an empty server goes back to the lobby', async () => {
  152. const s = await startServer();
  153. const a = new TestClient(s.port);
  154. const b = new TestClient(s.port);
  155. clients.push(a, b);
  156. await a.hello('Alice');
  157. await b.hello('Bob');
  158. await flush();
  159. b.socket.close();
  160. await flush();
  161. expect(a.last('playerLeft')).toMatchObject({ id: b.playerId });
  162. expect(a.last('lobby')!.players).toHaveLength(1);
  163. a.socket.close();
  164. await flush();
  165. expect(s.currentPhase).toBe('lobby');
  166. expect(s.playerCount).toBe(0);
  167. });
  168. it('a whole match: rounds with results in between, final results with trophies, then back to the lobby', async () => {
  169. const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 0.25, matchEndPause: 0.25 });
  170. const a = new TestClient(s.port);
  171. clients.push(a);
  172. await a.hello('Alice', 'castor');
  173. await flush();
  174. a.send({ t: 'ready', ready: true });
  175. await flush();
  176. tick(START_COUNTDOWN_S * TICK_RATE);
  177. await flush();
  178. expect(a.last('start')).toMatchObject({ round: 1, rounds: 2 });
  179. // Alice eats the cake during round 1 so she earns a trophy.
  180. for (let i = 0; i < TICK_RATE + 2; i++) {
  181. const me = a.last('snapshot')?.players.find((p) => p.id === a.playerId);
  182. if (me && i % 10 === 0) {
  183. a.send({ t: 'input', buttons: Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + 100) });
  184. await flush(5);
  185. }
  186. tick(1);
  187. }
  188. await flush();
  189. expect(a.last('roundEnd')).toMatchObject({ round: 1, rounds: 2 });
  190. expect(a.last('lobby')).toMatchObject({ phase: 'roundEnd' });
  191. tick(Math.round(0.25 * TICK_RATE));
  192. await flush();
  193. expect(a.last('start')).toMatchObject({ round: 2 });
  194. tick(TICK_RATE + 2);
  195. await flush();
  196. const end = a.last('matchEnd')!;
  197. expect(end).toBeDefined();
  198. expect(end.results.map((r) => r.id)).toEqual([a.playerId]);
  199. expect(end.trophies).toContainEqual(expect.objectContaining({ id: 'glutton', playerId: a.playerId }));
  200. tick(Math.round(0.25 * TICK_RATE));
  201. await flush();
  202. expect(a.last('start')).toMatchObject({ round: 0 });
  203. expect(a.last('lobby')).toMatchObject({ phase: 'lobby' });
  204. expect(a.last('lobby')!.players[0].ready).toBe(false);
  205. });
  206. it('only the host sets the rotation; the warm-up moves to its first map', async () => {
  207. const s = await startServer();
  208. const host = new TestClient(s.port);
  209. const guest = new TestClient(s.port);
  210. clients.push(host, guest);
  211. await host.hello('Hote');
  212. await guest.hello('Invite');
  213. await flush();
  214. expect(guest.last('lobby')).toMatchObject({ hostId: host.playerId, rotation: { mode: 'all' } });
  215. expect(guest.last('lobby')!.maps.map((m) => m.id)).toEqual(['gateau-etages', 'mille-feuille', 'piece-montee']);
  216. guest.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee'] } });
  217. await flush();
  218. expect(host.last('lobby')!.rotation.mode).toBe('all');
  219. host.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee', 'nope'] } });
  220. await flush(400); // the warm-up map is reloaded: give the server time to decode it
  221. expect(guest.last('lobby')!.rotation).toEqual({ mode: 'selection', selection: ['piece-montee'] });
  222. expect(guest.last('start')).toMatchObject({ mapId: 'piece-montee', round: 0 });
  223. });
  224. it('the last-placed player picks the next map during the round results', async () => {
  225. const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 1, matchEndPause: 0.25 });
  226. const a = new TestClient(s.port);
  227. const b = new TestClient(s.port);
  228. clients.push(a, b);
  229. await a.hello('Alice');
  230. await b.hello('Bob');
  231. await flush();
  232. a.send({ t: 'ready', ready: true });
  233. b.send({ t: 'ready', ready: true });
  234. await flush();
  235. tick(START_COUNTDOWN_S * TICK_RATE);
  236. await flush();
  237. expect(a.last('start')).toMatchObject({ round: 1, mapId: 'gateau-etages' });
  238. tick(TICK_RATE + 2);
  239. await flush();
  240. const end = a.last('roundEnd')!;
  241. // Nobody scored: the tie goes to the latest to join.
  242. expect(end.picker).toBe(b.playerId);
  243. expect(end.choices).toHaveLength(3);
  244. a.send({ t: 'pickMap', mapId: 'piece-montee' }); // not Alice's call
  245. b.send({ t: 'pickMap', mapId: 'mille-feuille' });
  246. await flush();
  247. expect(a.last('mapPicked')).toEqual({ t: 'mapPicked', mapId: 'mille-feuille', by: b.playerId });
  248. tick(TICK_RATE);
  249. await flush();
  250. expect(a.last('start')).toMatchObject({ round: 2, mapId: 'mille-feuille' });
  251. expect(b.mapId).toBe('mille-feuille');
  252. });
  253. });