BlueGit

timfa questward

Files

questward / server / tests / proximity-speech.test.js

proximity-speech.test.js

proximity-speech.test.js 2.4 KiB Download Raw
1import test from "node:test";
2import assert from "node:assert/strict";
3import { CHUNK_SIZE, MessageType } from "../../shared/protocol/constants.js";
4import { obscureSpeech, speechReadability } from "../../shared/speech/proximity.js";
5import { broadcastSpeech } from "../src/chat/speech.js";
6
7test("speech stays clear until half a chunk, then falls to zero at one chunk", () =>
8{
9 assert.equal(speechReadability(0), 1);
10 assert.equal(speechReadability(CHUNK_SIZE * 0.5), 1);
11 assert.equal(speechReadability(CHUNK_SIZE * 0.75), 0.5);
12 assert.equal(speechReadability(CHUNK_SIZE), 0);
13 assert.equal(speechReadability(CHUNK_SIZE + 4), 0);
14});
15
16test("obscured speech is deterministic and hides letters with distance", () =>
17{
18 const source = "Hello there";
19 assert.equal(obscureSpeech(source, 1, 7), source);
20 assert.equal(obscureSpeech(source, 0, 7), "");
21 const far = obscureSpeech(source, 0.4, 7);
22 assert.equal(obscureSpeech(source, 0.4, 7), far);
23 assert.match(far, /\./);
24 assert.match(far, / /);
25});
26
27test("broadcastSpeech trims, caps length, and only sends audible bubbles", () =>
28{
29 function session (id, entityId)
30 {
31 const sent = [];
32 return {
33 id,
34 entityId,
35 characterId: entityId,
36 socket: { readyState: 1, send (raw) { sent.push(JSON.parse(raw)); } },
37 sent
38 };
39 }
40
41 const speaker = session(1, 10);
42 const near = session(2, 20);
43 const mid = session(3, 30);
44 const silent = session(4, 40);
45 const positions = new Map([
46 [10, { tileX: 0, tileY: 0 }],
47 [20, { tileX: 4, tileY: 0 }],
48 [30, { tileX: 12, tileY: 0 }],
49 [40, { tileX: 16, tileY: 0 }]
50 ]);
51 const simulation = {
52 settings: { chatMaxCharacters: 8 },
53 positionOf (id)
54 {
55 return positions.get(id) ?? null;
56 }
57 };
58 const sessions = new Map([
59 [speaker.id, speaker],
60 [near.id, near],
61 [mid.id, mid],
62 [silent.id, silent]
63 ]);
64
65 broadcastSpeech(sessions, simulation, speaker, " hello world ");
66 assert.equal(speaker.sent.length, 1);
67 assert.equal(speaker.sent[0].type, MessageType.chatBubble);
68 assert.equal(speaker.sent[0].text, "hello wo");
69 assert.equal(near.sent[0].text, "hello wo");
70 assert.equal(
71 mid.sent[0].text,
72 obscureSpeech("hello wo", speechReadability(12), speaker.sent[0].messageId ^ mid.id)
73 );
74 assert.equal(silent.sent.length, 0);
75
76 for (const entry of sessions.values())
77 { entry.sent.length = 0; }
78 broadcastSpeech(sessions, simulation, speaker, " ");
79 assert.equal(speaker.sent.length, 0);
80});