BlueGit

timfa questward

Show player first names on hover and add character friend requests.

Clicking another player inspects them; friendships are accepted, stored per character, and removed on both sides so a later pigeon can address friends by name.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
34d858d6ab1fe05a26a0f92aa45fcb9c2112168b
Parent
4f08b384
14 files changed +864 −26
client/index.html +20 −0
@@ -10,8 +10,28 @@
10 10 <span id="you"></span>
11 11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="friends-toggle" type="button">Friends</button>
13 14 <button id="leave" type="button">Leave world</button>
14 15 </div>
16 <aside id="friends-panel" hidden>
17 <h2>Friends</h2>
18 <div id="friends-list"></div>
19 <h3>Incoming</h3>
20 <div id="incoming-list"></div>
21 <h3>Outgoing</h3>
22 <div id="outgoing-list"></div>
23 <p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
24 </aside>
25 <div id="nametag" hidden></div>
26 <div id="inspect-backdrop" hidden></div>
27 <div id="inspect-modal" hidden>
28 <header>
29 <h2 id="inspect-name">Player</h2>
30 <button id="inspect-close" type="button">Close</button>
31 </header>
32 <p id="inspect-error" class="error"></p>
33 <div id="inspect-action"></div>
34 </div>
15 35 <div id="overlay">
16 36 <section class="panel">
17 37 <h1>Tile MMO</h1>
@@ -10,8 +10,28 @@
10 <span id="you"></span>
10 <span id="you"></span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="friends-toggle" type="button">Friends</button>
13 <button id="leave" type="button">Leave world</button>
14 <button id="leave" type="button">Leave world</button>
14 </div>
15 </div>
16 <aside id="friends-panel" hidden>
17 <h2>Friends</h2>
18 <div id="friends-list"></div>
19 <h3>Incoming</h3>
20 <div id="incoming-list"></div>
21 <h3>Outgoing</h3>
22 <div id="outgoing-list"></div>
23 <p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
24 </aside>
25 <div id="nametag" hidden></div>
26 <div id="inspect-backdrop" hidden></div>
27 <div id="inspect-modal" hidden>
28 <header>
29 <h2 id="inspect-name">Player</h2>
30 <button id="inspect-close" type="button">Close</button>
31 </header>
32 <p id="inspect-error" class="error"></p>
33 <div id="inspect-action"></div>
34 </div>
15 <div id="overlay">
35 <div id="overlay">
16 <section class="panel">
36 <section class="panel">
17 <h1>Tile MMO</h1>
37 <h1>Tile MMO</h1>
client/src/play/main.js +33 −4
@@ -2,6 +2,7 @@ import { MessageType, GAIT } from "/shared/protocol/constants.js";
2 2 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3 3 import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4 4 import { WorldView } from "../render/worldView.js";
5 import { initSocial } from "./social.js";
5 6
6 7 const game = new Game();
7 8 const hud = document.getElementById("hud");
@@ -17,6 +18,7 @@ let view = null;
17 18 let scene = null;
18 19 let gait = GAIT.walk;
19 20 let catalog = { grounds: {}, blocks: {} };
21 let social;
20 22
21 23 function showError (message)
22 24 {
@@ -69,10 +71,20 @@ function startPlay (payload)
69 71 const ticker = new GameObject(0, 0, null, 10);
70 72 ticker.update = (dt) =>
71 73 {
72 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing)
74 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking())
73 75 {
74 const tile = view.screenToTile(GameInput.mousePosition.x, GameInput.mousePosition.y);
75 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
76 const canvas = scene.canvas;
77 const rect = canvas.getBoundingClientRect();
78 const mouseX = GameInput.mousePosition.x - rect.left;
79 const mouseY = GameInput.mousePosition.y - rect.top;
80 const entity = view.entityAtScreen(mouseX, mouseY);
81 if (entity && entity.entityId !== view.localEntityId && entity.characterId)
82 { social.inspect(entity); }
83 else
84 {
85 const tile = view.screenToTile(mouseX, mouseY);
86 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
87 }
76 88 }
77 89 if (GameInput.isPressed(82))
78 90 {
@@ -80,6 +92,8 @@ function startPlay (payload)
80 92 socket.send({ type: MessageType.setGait, gait });
81 93 document.getElementById("gait").textContent = gait;
82 94 }
95 if (playing)
96 { social?.updateNametag(view, scene, view.localEntityId); }
83 97 view.update(dt);
84 98 };
85 99 scene.addObject(ticker);
@@ -99,7 +113,16 @@ function startPlay (payload)
99 113 }
100 114 view.settings = payload.settings ?? view.settings;
101 115 view.worldHour = payload.worldTime?.hour ?? 12;
102 view.setLocalEntity(payload.entityId, payload.tileX, payload.tileY, payload.gait, payload.sex);
116 view.setLocalEntity(
117 payload.entityId,
118 payload.tileX,
119 payload.tileY,
120 payload.gait,
121 payload.sex,
122 payload.firstName,
123 payload.lastName,
124 payload.characterId
125 );
103 126 }
104 127
105 128 async function main ()
@@ -107,6 +130,7 @@ async function main ()
107 130 catalog = await loadSpriteCatalog();
108 131 await game.preloadImages(playImagesFromCatalog(catalog));
109 132 applySpriteSheets(game.images, catalog);
133 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
110 134 game.startGame();
111 135
112 136 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -145,8 +169,12 @@ async function main ()
145 169 view.worldHour = message.worldTime?.hour ?? view.worldHour;
146 170 }
147 171 break;
172 case MessageType.friends:
173 social?.handleFriends(message);
174 break;
148 175 case MessageType.error:
149 176 showError(message.message);
177 social?.showError(message.message);
150 178 break;
151 179 }
152 180 });
@@ -169,6 +197,7 @@ document.getElementById("leave").addEventListener("click", () =>
169 197 {
170 198 socket.send({ type: MessageType.leaveWorld });
171 199 playing = false;
200 social?.reset();
172 201 overlay.hidden = false;
173 202 hud.hidden = true;
174 203 });
@@ -2,6 +2,7 @@ import { MessageType, GAIT } from "/shared/protocol/constants.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
3import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { WorldView } from "../render/worldView.js";
4import { WorldView } from "../render/worldView.js";
5import { initSocial } from "./social.js";
5
6
6const game = new Game();
7const game = new Game();
7const hud = document.getElementById("hud");
8const hud = document.getElementById("hud");
@@ -17,6 +18,7 @@ let view = null;
17let scene = null;
18let scene = null;
18let gait = GAIT.walk;
19let gait = GAIT.walk;
19let catalog = { grounds: {}, blocks: {} };
20let catalog = { grounds: {}, blocks: {} };
21let social;
20
22
21function showError (message)
23function showError (message)
22{
24{
@@ -69,10 +71,20 @@ function startPlay (payload)
69 const ticker = new GameObject(0, 0, null, 10);
71 const ticker = new GameObject(0, 0, null, 10);
70 ticker.update = (dt) =>
72 ticker.update = (dt) =>
71 {
73 {
72 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing)
74 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking())
73 {
75 {
74 const tile = view.screenToTile(GameInput.mousePosition.x, GameInput.mousePosition.y);
76 const canvas = scene.canvas;
75 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
77 const rect = canvas.getBoundingClientRect();
78 const mouseX = GameInput.mousePosition.x - rect.left;
79 const mouseY = GameInput.mousePosition.y - rect.top;
80 const entity = view.entityAtScreen(mouseX, mouseY);
81 if (entity && entity.entityId !== view.localEntityId && entity.characterId)
82 { social.inspect(entity); }
83 else
84 {
85 const tile = view.screenToTile(mouseX, mouseY);
86 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
87 }
76 }
88 }
77 if (GameInput.isPressed(82))
89 if (GameInput.isPressed(82))
78 {
90 {
@@ -80,6 +92,8 @@ function startPlay (payload)
80 socket.send({ type: MessageType.setGait, gait });
92 socket.send({ type: MessageType.setGait, gait });
81 document.getElementById("gait").textContent = gait;
93 document.getElementById("gait").textContent = gait;
82 }
94 }
95 if (playing)
96 { social?.updateNametag(view, scene, view.localEntityId); }
83 view.update(dt);
97 view.update(dt);
84 };
98 };
85 scene.addObject(ticker);
99 scene.addObject(ticker);
@@ -99,7 +113,16 @@ function startPlay (payload)
99 }
113 }
100 view.settings = payload.settings ?? view.settings;
114 view.settings = payload.settings ?? view.settings;
101 view.worldHour = payload.worldTime?.hour ?? 12;
115 view.worldHour = payload.worldTime?.hour ?? 12;
102 view.setLocalEntity(payload.entityId, payload.tileX, payload.tileY, payload.gait, payload.sex);
116 view.setLocalEntity(
117 payload.entityId,
118 payload.tileX,
119 payload.tileY,
120 payload.gait,
121 payload.sex,
122 payload.firstName,
123 payload.lastName,
124 payload.characterId
125 );
103}
126}
104
127
105async function main ()
128async function main ()
@@ -107,6 +130,7 @@ async function main ()
107 catalog = await loadSpriteCatalog();
130 catalog = await loadSpriteCatalog();
108 await game.preloadImages(playImagesFromCatalog(catalog));
131 await game.preloadImages(playImagesFromCatalog(catalog));
109 applySpriteSheets(game.images, catalog);
132 applySpriteSheets(game.images, catalog);
133 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
110 game.startGame();
134 game.startGame();
111
135
112 socket = new GameSocket(defaultSocketUrl(), (message) =>
136 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -145,8 +169,12 @@ async function main ()
145 view.worldHour = message.worldTime?.hour ?? view.worldHour;
169 view.worldHour = message.worldTime?.hour ?? view.worldHour;
146 }
170 }
147 break;
171 break;
172 case MessageType.friends:
173 social?.handleFriends(message);
174 break;
148 case MessageType.error:
175 case MessageType.error:
149 showError(message.message);
176 showError(message.message);
177 social?.showError(message.message);
150 break;
178 break;
151 }
179 }
152 });
180 });
@@ -169,6 +197,7 @@ document.getElementById("leave").addEventListener("click", () =>
169{
197{
170 socket.send({ type: MessageType.leaveWorld });
198 socket.send({ type: MessageType.leaveWorld });
171 playing = false;
199 playing = false;
200 social?.reset();
172 overlay.hidden = false;
201 overlay.hidden = false;
173 hud.hidden = true;
202 hud.hidden = true;
174});
203});
client/src/play/social.js added +251 −0
@@ -0,0 +1,251 @@
1 export function initSocial ({ socket, MessageType })
2 {
3 const nametag = document.getElementById("nametag");
4 const inspect = document.getElementById("inspect-modal");
5 const inspectBackdrop = document.getElementById("inspect-backdrop");
6 const inspectName = document.getElementById("inspect-name");
7 const inspectAction = document.getElementById("inspect-action");
8 const inspectError = document.getElementById("inspect-error");
9 const friendsPanel = document.getElementById("friends-panel");
10 const friendsList = document.getElementById("friends-list");
11 const incomingList = document.getElementById("incoming-list");
12 const outgoingList = document.getElementById("outgoing-list");
13 let social = { friends: [], incoming: [], outgoing: [] };
14 let inspected = null;
15 let open = false;
16
17 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
18 inspectBackdrop.addEventListener("click", () => hideInspect());
19 document.getElementById("friends-toggle").addEventListener("click", () =>
20 {
21 friendsPanel.hidden = !friendsPanel.hidden;
22 });
23
24 function hideInspect ()
25 {
26 open = false;
27 inspected = null;
28 inspect.hidden = true;
29 inspectBackdrop.hidden = true;
30 inspectError.textContent = "";
31 }
32
33 function relation (characterId)
34 {
35 if (social.friends.some((entry) => entry.characterId === characterId))
36 { return "friends"; }
37 if (social.incoming.some((entry) => entry.characterId === characterId))
38 { return "incoming"; }
39 if (social.outgoing.some((entry) => entry.characterId === characterId))
40 { return "outgoing"; }
41 return "none";
42 }
43
44 function renderInspect ()
45 {
46 if (!inspected)
47 { return; }
48 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
49 inspectAction.replaceChildren();
50 const status = relation(inspected.characterId);
51 if (status === "friends")
52 {
53 inspectAction.append(actionButton("Remove friend", () =>
54 {
55 socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });
56 }));
57 }
58 else if (status === "incoming")
59 {
60 inspectAction.append(
61 actionButton("Accept friend request", () =>
62 {
63 socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });
64 }),
65 actionButton("Decline", () =>
66 {
67 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
68 })
69 );
70 }
71 else if (status === "outgoing")
72 {
73 const pending = document.createElement("p");
74 pending.className = "hint";
75 pending.textContent = "Friend request sent.";
76 inspectAction.append(
77 pending,
78 actionButton("Cancel request", () =>
79 {
80 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
81 })
82 );
83 }
84 else
85 {
86 inspectAction.append(actionButton("Send friend request", () =>
87 {
88 socket.send({ type: MessageType.friendRequest, characterId: inspected.characterId });
89 }));
90 }
91 }
92
93 function renderLists ()
94 {
95 fillList(friendsList, social.friends, "No friends yet.", (entry) =>
96 {
97 const row = namedRow(entry);
98 row.append(actionButton("Remove", () =>
99 {
100 socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
101 }));
102 return row;
103 });
104 fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>
105 {
106 const row = namedRow(entry);
107 row.append(
108 actionButton("Accept", () =>
109 {
110 socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });
111 }),
112 actionButton("Decline", () =>
113 {
114 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
115 })
116 );
117 return row;
118 });
119 fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>
120 {
121 const row = namedRow(entry);
122 row.append(actionButton("Cancel", () =>
123 {
124 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
125 }));
126 return row;
127 });
128 }
129
130 return {
131 isBlocking ()
132 {
133 if (open)
134 { return true; }
135 const x = GameInput.mousePosition.x;
136 const y = GameInput.mousePosition.y;
137 for (const element of [document.getElementById("hud"), friendsPanel, inspect, inspectBackdrop])
138 {
139 if (!element || element.hidden)
140 { continue; }
141 const box = element.getBoundingClientRect();
142 if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
143 { return true; }
144 }
145 return false;
146 },
147 inspectOpen: () => open,
148 handleFriends (message)
149 {
150 social = {
151 friends: message.friends ?? [],
152 incoming: message.incoming ?? [],
153 outgoing: message.outgoing ?? []
154 };
155 renderLists();
156 if (open)
157 { renderInspect(); }
158 },
159 inspect (entity)
160 {
161 if (!entity?.characterId)
162 { return; }
163 inspected = {
164 characterId: entity.characterId,
165 firstName: entity.firstName ?? "",
166 lastName: entity.lastName ?? ""
167 };
168 open = true;
169 inspectError.textContent = "";
170 inspect.hidden = false;
171 inspectBackdrop.hidden = false;
172 renderInspect();
173 },
174 hideInspect,
175 reset ()
176 {
177 hideInspect();
178 friendsPanel.hidden = true;
179 nametag.hidden = true;
180 },
181 updateNametag (view, scene, localEntityId)
182 {
183 if (!view || !scene?.canvas)
184 {
185 nametag.hidden = true;
186 return;
187 }
188 const canvas = scene.canvas;
189 const rect = canvas.getBoundingClientRect();
190 const mouseX = GameInput.mousePosition.x - rect.left;
191 const mouseY = GameInput.mousePosition.y - rect.top;
192 const entity = view.entityAtScreen(mouseX, mouseY);
193 if (!entity || entity.entityId === localEntityId || !entity.firstName)
194 {
195 nametag.hidden = true;
196 canvas.style.cursor = "";
197 return;
198 }
199 const anchor = view.nametagAnchor(entity);
200 if (!anchor)
201 {
202 nametag.hidden = true;
203 return;
204 }
205 nametag.hidden = false;
206 nametag.textContent = entity.firstName;
207 nametag.style.left = `${rect.left + anchor.x}px`;
208 nametag.style.top = `${rect.top + anchor.y - 6}px`;
209 canvas.style.cursor = "pointer";
210 },
211 showError (message)
212 {
213 if (open)
214 { inspectError.textContent = message; }
215 }
216 };
217 }
218
219 function namedRow (entry)
220 {
221 const row = document.createElement("div");
222 row.className = "social-row";
223 const name = document.createElement("span");
224 name.textContent = `${entry.firstName} ${entry.lastName}`;
225 row.append(name);
226 return row;
227 }
228
229 function fillList (root, entries, emptyText, renderRow)
230 {
231 root.replaceChildren();
232 if (!entries.length)
233 {
234 const empty = document.createElement("p");
235 empty.className = "hint";
236 empty.textContent = emptyText;
237 root.append(empty);
238 return;
239 }
240 for (const entry of entries)
241 { root.append(renderRow(entry)); }
242 }
243
244 function actionButton (label, onClick)
245 {
246 const button = document.createElement("button");
247 button.type = "button";
248 button.textContent = label;
249 button.addEventListener("click", onClick);
250 return button;
251 }
@@ -0,0 +1,251 @@
1export function initSocial ({ socket, MessageType })
2{
3 const nametag = document.getElementById("nametag");
4 const inspect = document.getElementById("inspect-modal");
5 const inspectBackdrop = document.getElementById("inspect-backdrop");
6 const inspectName = document.getElementById("inspect-name");
7 const inspectAction = document.getElementById("inspect-action");
8 const inspectError = document.getElementById("inspect-error");
9 const friendsPanel = document.getElementById("friends-panel");
10 const friendsList = document.getElementById("friends-list");
11 const incomingList = document.getElementById("incoming-list");
12 const outgoingList = document.getElementById("outgoing-list");
13 let social = { friends: [], incoming: [], outgoing: [] };
14 let inspected = null;
15 let open = false;
16
17 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
18 inspectBackdrop.addEventListener("click", () => hideInspect());
19 document.getElementById("friends-toggle").addEventListener("click", () =>
20 {
21 friendsPanel.hidden = !friendsPanel.hidden;
22 });
23
24 function hideInspect ()
25 {
26 open = false;
27 inspected = null;
28 inspect.hidden = true;
29 inspectBackdrop.hidden = true;
30 inspectError.textContent = "";
31 }
32
33 function relation (characterId)
34 {
35 if (social.friends.some((entry) => entry.characterId === characterId))
36 { return "friends"; }
37 if (social.incoming.some((entry) => entry.characterId === characterId))
38 { return "incoming"; }
39 if (social.outgoing.some((entry) => entry.characterId === characterId))
40 { return "outgoing"; }
41 return "none";
42 }
43
44 function renderInspect ()
45 {
46 if (!inspected)
47 { return; }
48 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
49 inspectAction.replaceChildren();
50 const status = relation(inspected.characterId);
51 if (status === "friends")
52 {
53 inspectAction.append(actionButton("Remove friend", () =>
54 {
55 socket.send({ type: MessageType.friendRemove, characterId: inspected.characterId });
56 }));
57 }
58 else if (status === "incoming")
59 {
60 inspectAction.append(
61 actionButton("Accept friend request", () =>
62 {
63 socket.send({ type: MessageType.friendAccept, characterId: inspected.characterId });
64 }),
65 actionButton("Decline", () =>
66 {
67 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
68 })
69 );
70 }
71 else if (status === "outgoing")
72 {
73 const pending = document.createElement("p");
74 pending.className = "hint";
75 pending.textContent = "Friend request sent.";
76 inspectAction.append(
77 pending,
78 actionButton("Cancel request", () =>
79 {
80 socket.send({ type: MessageType.friendDecline, characterId: inspected.characterId });
81 })
82 );
83 }
84 else
85 {
86 inspectAction.append(actionButton("Send friend request", () =>
87 {
88 socket.send({ type: MessageType.friendRequest, characterId: inspected.characterId });
89 }));
90 }
91 }
92
93 function renderLists ()
94 {
95 fillList(friendsList, social.friends, "No friends yet.", (entry) =>
96 {
97 const row = namedRow(entry);
98 row.append(actionButton("Remove", () =>
99 {
100 socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
101 }));
102 return row;
103 });
104 fillList(incomingList, social.incoming, "No incoming requests.", (entry) =>
105 {
106 const row = namedRow(entry);
107 row.append(
108 actionButton("Accept", () =>
109 {
110 socket.send({ type: MessageType.friendAccept, characterId: entry.characterId });
111 }),
112 actionButton("Decline", () =>
113 {
114 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
115 })
116 );
117 return row;
118 });
119 fillList(outgoingList, social.outgoing, "No outgoing requests.", (entry) =>
120 {
121 const row = namedRow(entry);
122 row.append(actionButton("Cancel", () =>
123 {
124 socket.send({ type: MessageType.friendDecline, characterId: entry.characterId });
125 }));
126 return row;
127 });
128 }
129
130 return {
131 isBlocking ()
132 {
133 if (open)
134 { return true; }
135 const x = GameInput.mousePosition.x;
136 const y = GameInput.mousePosition.y;
137 for (const element of [document.getElementById("hud"), friendsPanel, inspect, inspectBackdrop])
138 {
139 if (!element || element.hidden)
140 { continue; }
141 const box = element.getBoundingClientRect();
142 if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
143 { return true; }
144 }
145 return false;
146 },
147 inspectOpen: () => open,
148 handleFriends (message)
149 {
150 social = {
151 friends: message.friends ?? [],
152 incoming: message.incoming ?? [],
153 outgoing: message.outgoing ?? []
154 };
155 renderLists();
156 if (open)
157 { renderInspect(); }
158 },
159 inspect (entity)
160 {
161 if (!entity?.characterId)
162 { return; }
163 inspected = {
164 characterId: entity.characterId,
165 firstName: entity.firstName ?? "",
166 lastName: entity.lastName ?? ""
167 };
168 open = true;
169 inspectError.textContent = "";
170 inspect.hidden = false;
171 inspectBackdrop.hidden = false;
172 renderInspect();
173 },
174 hideInspect,
175 reset ()
176 {
177 hideInspect();
178 friendsPanel.hidden = true;
179 nametag.hidden = true;
180 },
181 updateNametag (view, scene, localEntityId)
182 {
183 if (!view || !scene?.canvas)
184 {
185 nametag.hidden = true;
186 return;
187 }
188 const canvas = scene.canvas;
189 const rect = canvas.getBoundingClientRect();
190 const mouseX = GameInput.mousePosition.x - rect.left;
191 const mouseY = GameInput.mousePosition.y - rect.top;
192 const entity = view.entityAtScreen(mouseX, mouseY);
193 if (!entity || entity.entityId === localEntityId || !entity.firstName)
194 {
195 nametag.hidden = true;
196 canvas.style.cursor = "";
197 return;
198 }
199 const anchor = view.nametagAnchor(entity);
200 if (!anchor)
201 {
202 nametag.hidden = true;
203 return;
204 }
205 nametag.hidden = false;
206 nametag.textContent = entity.firstName;
207 nametag.style.left = `${rect.left + anchor.x}px`;
208 nametag.style.top = `${rect.top + anchor.y - 6}px`;
209 canvas.style.cursor = "pointer";
210 },
211 showError (message)
212 {
213 if (open)
214 { inspectError.textContent = message; }
215 }
216 };
217}
218
219function namedRow (entry)
220{
221 const row = document.createElement("div");
222 row.className = "social-row";
223 const name = document.createElement("span");
224 name.textContent = `${entry.firstName} ${entry.lastName}`;
225 row.append(name);
226 return row;
227}
228
229function fillList (root, entries, emptyText, renderRow)
230{
231 root.replaceChildren();
232 if (!entries.length)
233 {
234 const empty = document.createElement("p");
235 empty.className = "hint";
236 empty.textContent = emptyText;
237 root.append(empty);
238 return;
239 }
240 for (const entry of entries)
241 { root.append(renderRow(entry)); }
242}
243
244function actionButton (label, onClick)
245{
246 const button = document.createElement("button");
247 button.type = "button";
248 button.textContent = label;
249 button.addEventListener("click", onClick);
250 return button;
251}
client/src/render/worldView.js +60 −11
@@ -29,17 +29,18 @@ export class WorldView
29 29 this.followPlayer = true;
30 30 }
31 31
32 setLocalEntity (entityId, tileX, tileY, gait, sex)
32 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null)
33 33 {
34 34 this.localEntityId = entityId;
35 35 this.#upsertEntity({
36 36 entityId,
37 characterId,
37 38 tileX,
38 39 tileY,
39 40 gait,
40 41 sex,
41 firstName: "",
42 lastName: ""
42 firstName,
43 lastName
43 44 });
44 45 }
45 46
@@ -86,13 +87,7 @@ export class WorldView
86 87 const existing = this.entities.get(payload.entityId);
87 88 if (!existing)
88 89 {
89 this.#upsertEntity({
90 entityId: payload.entityId,
91 tileX: payload.tileX,
92 tileY: payload.tileY,
93 gait: payload.gait,
94 sex: "male"
95 });
90 this.#upsertEntity(payload);
96 91 return;
97 92 }
98 93 existing.fromX = existing.visualX;
@@ -150,6 +145,52 @@ export class WorldView
150 145 };
151 146 }
152 147
148 entityAtScreen (mouseX, mouseY)
149 {
150 let best = null;
151 let bestLayer = -Infinity;
152 for (const entity of this.entities.values())
153 {
154 const box = this.#entityScreenBox(entity);
155 if (!box)
156 { continue; }
157 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
158 {
159 const layer = entity.object?.layer ?? 0;
160 if (layer >= bestLayer)
161 {
162 best = entity;
163 bestLayer = layer;
164 }
165 }
166 }
167 return best;
168 }
169
170 nametagAnchor (entity)
171 {
172 const box = this.#entityScreenBox(entity);
173 if (!box)
174 { return null; }
175 return { x: (box.left + box.right) / 2, y: box.top };
176 }
177
178 #entityScreenBox (entity)
179 {
180 const object = entity?.object;
181 if (!object)
182 { return null; }
183 const size = object.transform.size;
184 const x = object.transform.position.x + this.scene.cameraPosition.x;
185 const y = object.transform.position.y + this.scene.cameraPosition.y;
186 return {
187 left: x - size.x / 2,
188 right: x + size.x / 2,
189 top: y - size.y / 2,
190 bottom: y + size.y / 2
191 };
192 }
193
153 194 update (deltaTime)
154 195 {
155 196 const now = performance.now();
@@ -240,10 +281,18 @@ export class WorldView
240 281 entity = { object, visualX: pivot.x, visualY: pivot.y };
241 282 this.entities.set(payload.entityId, entity);
242 283 }
284 entity.entityId = payload.entityId;
243 285 entity.tileX = payload.tileX;
244 286 entity.tileY = payload.tileY;
245 287 entity.gait = payload.gait;
246 entity.sex = payload.sex;
288 entity.sex = payload.sex ?? entity.sex;
289 entity.characterId = payload.characterId ?? entity.characterId ?? null;
290 if (payload.firstName)
291 { entity.firstName = payload.firstName; }
292 if (payload.lastName)
293 { entity.lastName = payload.lastName; }
294 entity.firstName = entity.firstName ?? "";
295 entity.lastName = entity.lastName ?? "";
247 296 entity.visualX = pivot.x;
248 297 entity.visualY = pivot.y;
249 298 entity.fromX = pivot.x;
@@ -29,17 +29,18 @@ export class WorldView
29 this.followPlayer = true;
29 this.followPlayer = true;
30 }
30 }
31
31
32 setLocalEntity (entityId, tileX, tileY, gait, sex)
32 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null)
33 {
33 {
34 this.localEntityId = entityId;
34 this.localEntityId = entityId;
35 this.#upsertEntity({
35 this.#upsertEntity({
36 entityId,
36 entityId,
37 characterId,
37 tileX,
38 tileX,
38 tileY,
39 tileY,
39 gait,
40 gait,
40 sex,
41 sex,
41 firstName: "",
42 firstName,
42 lastName: ""
43 lastName
43 });
44 });
44 }
45 }
45
46
@@ -86,13 +87,7 @@ export class WorldView
86 const existing = this.entities.get(payload.entityId);
87 const existing = this.entities.get(payload.entityId);
87 if (!existing)
88 if (!existing)
88 {
89 {
89 this.#upsertEntity({
90 this.#upsertEntity(payload);
90 entityId: payload.entityId,
91 tileX: payload.tileX,
92 tileY: payload.tileY,
93 gait: payload.gait,
94 sex: "male"
95 });
96 return;
91 return;
97 }
92 }
98 existing.fromX = existing.visualX;
93 existing.fromX = existing.visualX;
@@ -150,6 +145,52 @@ export class WorldView
150 };
145 };
151 }
146 }
152
147
148 entityAtScreen (mouseX, mouseY)
149 {
150 let best = null;
151 let bestLayer = -Infinity;
152 for (const entity of this.entities.values())
153 {
154 const box = this.#entityScreenBox(entity);
155 if (!box)
156 { continue; }
157 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
158 {
159 const layer = entity.object?.layer ?? 0;
160 if (layer >= bestLayer)
161 {
162 best = entity;
163 bestLayer = layer;
164 }
165 }
166 }
167 return best;
168 }
169
170 nametagAnchor (entity)
171 {
172 const box = this.#entityScreenBox(entity);
173 if (!box)
174 { return null; }
175 return { x: (box.left + box.right) / 2, y: box.top };
176 }
177
178 #entityScreenBox (entity)
179 {
180 const object = entity?.object;
181 if (!object)
182 { return null; }
183 const size = object.transform.size;
184 const x = object.transform.position.x + this.scene.cameraPosition.x;
185 const y = object.transform.position.y + this.scene.cameraPosition.y;
186 return {
187 left: x - size.x / 2,
188 right: x + size.x / 2,
189 top: y - size.y / 2,
190 bottom: y + size.y / 2
191 };
192 }
193
153 update (deltaTime)
194 update (deltaTime)
154 {
195 {
155 const now = performance.now();
196 const now = performance.now();
@@ -240,10 +281,18 @@ export class WorldView
240 entity = { object, visualX: pivot.x, visualY: pivot.y };
281 entity = { object, visualX: pivot.x, visualY: pivot.y };
241 this.entities.set(payload.entityId, entity);
282 this.entities.set(payload.entityId, entity);
242 }
283 }
284 entity.entityId = payload.entityId;
243 entity.tileX = payload.tileX;
285 entity.tileX = payload.tileX;
244 entity.tileY = payload.tileY;
286 entity.tileY = payload.tileY;
245 entity.gait = payload.gait;
287 entity.gait = payload.gait;
246 entity.sex = payload.sex;
288 entity.sex = payload.sex ?? entity.sex;
289 entity.characterId = payload.characterId ?? entity.characterId ?? null;
290 if (payload.firstName)
291 { entity.firstName = payload.firstName; }
292 if (payload.lastName)
293 { entity.lastName = payload.lastName; }
294 entity.firstName = entity.firstName ?? "";
295 entity.lastName = entity.lastName ?? "";
247 entity.visualX = pivot.x;
296 entity.visualX = pivot.x;
248 entity.visualY = pivot.y;
297 entity.visualY = pivot.y;
249 entity.fromX = pivot.x;
298 entity.fromX = pivot.x;
client/ui/play.css +77 −0
@@ -66,3 +66,80 @@ button {
66 66 .error { color: #f0a0a0; min-height: 1.2em; }
67 67 .hint { color: #9aa3b2; font-size: 0.9rem; }
68 68 a { color: #d4c48a; }
69
70 #nametag {
71 position: fixed;
72 z-index: 4;
73 pointer-events: none;
74 transform: translate(-50%, -100%);
75 background: rgba(12, 14, 18, 0.88);
76 border: 1px solid #3a4250;
77 padding: 0.1rem 0.45rem;
78 font-size: 0.85rem;
79 }
80
81 #inspect-backdrop {
82 position: fixed;
83 inset: 0;
84 z-index: 6;
85 background: rgba(0, 0, 0, 0.45);
86 }
87
88 #inspect-modal {
89 position: fixed;
90 z-index: 7;
91 left: 50%;
92 top: 40%;
93 transform: translate(-50%, -50%);
94 width: min(360px, 92vw);
95 background: #161a22;
96 border: 1px solid #3a4250;
97 padding: 0.85rem 1rem 1rem;
98 }
99
100 #inspect-modal header {
101 display: flex;
102 align-items: center;
103 justify-content: space-between;
104 gap: 0.75rem;
105 }
106
107 #inspect-action {
108 display: flex;
109 flex-wrap: wrap;
110 gap: 0.4rem;
111 margin-top: 0.5rem;
112 }
113
114 #friends-panel {
115 position: fixed;
116 z-index: 5;
117 top: 48px;
118 right: 0.75rem;
119 width: min(280px, 92vw);
120 max-height: calc(100vh - 64px);
121 overflow: auto;
122 background: #1a1e26;
123 border: 1px solid #2c3340;
124 padding: 0.75rem;
125 }
126
127 #friends-panel h2, #friends-panel h3 {
128 margin: 0.4rem 0;
129 font-size: 0.95rem;
130 }
131
132 .social-row {
133 display: flex;
134 flex-wrap: wrap;
135 gap: 0.35rem;
136 align-items: center;
137 margin: 0.35rem 0;
138 }
139
140 #inspect-modal[hidden],
141 #inspect-backdrop[hidden],
142 #friends-panel[hidden],
143 #nametag[hidden] {
144 display: none !important;
145 }
@@ -66,3 +66,80 @@ button {
66.error { color: #f0a0a0; min-height: 1.2em; }
66.error { color: #f0a0a0; min-height: 1.2em; }
67.hint { color: #9aa3b2; font-size: 0.9rem; }
67.hint { color: #9aa3b2; font-size: 0.9rem; }
68a { color: #d4c48a; }
68a { color: #d4c48a; }
69
70#nametag {
71 position: fixed;
72 z-index: 4;
73 pointer-events: none;
74 transform: translate(-50%, -100%);
75 background: rgba(12, 14, 18, 0.88);
76 border: 1px solid #3a4250;
77 padding: 0.1rem 0.45rem;
78 font-size: 0.85rem;
79}
80
81#inspect-backdrop {
82 position: fixed;
83 inset: 0;
84 z-index: 6;
85 background: rgba(0, 0, 0, 0.45);
86}
87
88#inspect-modal {
89 position: fixed;
90 z-index: 7;
91 left: 50%;
92 top: 40%;
93 transform: translate(-50%, -50%);
94 width: min(360px, 92vw);
95 background: #161a22;
96 border: 1px solid #3a4250;
97 padding: 0.85rem 1rem 1rem;
98}
99
100#inspect-modal header {
101 display: flex;
102 align-items: center;
103 justify-content: space-between;
104 gap: 0.75rem;
105}
106
107#inspect-action {
108 display: flex;
109 flex-wrap: wrap;
110 gap: 0.4rem;
111 margin-top: 0.5rem;
112}
113
114#friends-panel {
115 position: fixed;
116 z-index: 5;
117 top: 48px;
118 right: 0.75rem;
119 width: min(280px, 92vw);
120 max-height: calc(100vh - 64px);
121 overflow: auto;
122 background: #1a1e26;
123 border: 1px solid #2c3340;
124 padding: 0.75rem;
125}
126
127#friends-panel h2, #friends-panel h3 {
128 margin: 0.4rem 0;
129 font-size: 0.95rem;
130}
131
132.social-row {
133 display: flex;
134 flex-wrap: wrap;
135 gap: 0.35rem;
136 align-items: center;
137 margin: 0.35rem 0;
138}
139
140#inspect-modal[hidden],
141#inspect-backdrop[hidden],
142#friends-panel[hidden],
143#nametag[hidden] {
144 display: none !important;
145}
docs/FEATURES.md +8 −2
@@ -130,7 +130,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
130 130 ## Play viewport and camera
131 131
132 132 **Status:** full
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility.
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134 134 **Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
135 135
136 136 ## Night shading
@@ -190,9 +190,15 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
190 190 ## Combat, skills, groups, proximity chat, pigeons
191 191
192 192 **Status:** not implemented
193 **Spec:** Later systems described in the design. Not part of the first playable slice.
193 **Spec:** Later systems described in the design. Not part of the first playable slice. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
194 194 **Code:** —
195 195
196 ## Friends
197
198 **Status:** full
199 **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
200 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
201
196 202 ## Banking, cheques, shops, player-driven marketplace
197 203
198 204 **Status:** not implemented
@@ -130,7 +130,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
130## Play viewport and camera
130## Play viewport and camera
131
131
132**Status:** full
132**Status:** full
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility.
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134**Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
134**Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
135
135
136## Night shading
136## Night shading
@@ -190,9 +190,15 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
190## Combat, skills, groups, proximity chat, pigeons
190## Combat, skills, groups, proximity chat, pigeons
191
191
192**Status:** not implemented
192**Status:** not implemented
193**Spec:** Later systems described in the design. Not part of the first playable slice.
193**Spec:** Later systems described in the design. Not part of the first playable slice. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
194**Code:** —
194**Code:** —
195
195
196## Friends
197
198**Status:** full
199**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
200**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
201
196## Banking, cheques, shops, player-driven marketplace
202## Banking, cheques, shops, player-driven marketplace
197
203
198**Status:** not implemented
204**Status:** not implemented
server/src/friends/service.js added +113 −0
@@ -0,0 +1,113 @@
1 export class FriendService
2 {
3 constructor (stateDb)
4 {
5 this.stateDb = stateDb;
6 }
7
8 snapshot (characterId)
9 {
10 return {
11 friends: this.listFriends(characterId),
12 incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),
13 outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")
14 };
15 }
16
17 listFriends (characterId)
18 {
19 return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);
20 }
21
22 request (fromCharacterId, toCharacterId)
23 {
24 const fromId = Number(fromCharacterId);
25 const toId = Number(toCharacterId);
26 if (fromId === toId)
27 { throw userError("You cannot friend yourself."); }
28 this.#requireCharacter(fromId);
29 this.#requireCharacter(toId);
30 if (this.stateDb.areFriends(fromId, toId))
31 { throw userError("You are already friends."); }
32 if (this.stateDb.getFriendRequest(fromId, toId))
33 { throw userError("Friend request already sent."); }
34 if (this.stateDb.getFriendRequest(toId, fromId))
35 {
36 this.stateDb.deleteFriendRequest(toId, fromId);
37 this.stateDb.insertFriendship(fromId, toId);
38 return this.snapshot(fromId);
39 }
40 this.stateDb.insertFriendRequest(fromId, toId);
41 return this.snapshot(fromId);
42 }
43
44 accept (characterId, fromCharacterId)
45 {
46 const toId = Number(characterId);
47 const fromId = Number(fromCharacterId);
48 this.#requireCharacter(toId);
49 this.#requireCharacter(fromId);
50 if (!this.stateDb.getFriendRequest(fromId, toId))
51 { throw userError("There is no friend request to accept."); }
52 this.stateDb.deleteFriendRequest(fromId, toId);
53 this.stateDb.deleteFriendRequest(toId, fromId);
54 if (!this.stateDb.areFriends(fromId, toId))
55 { this.stateDb.insertFriendship(fromId, toId); }
56 return this.snapshot(toId);
57 }
58
59 decline (characterId, otherCharacterId)
60 {
61 const actorId = Number(characterId);
62 const otherId = Number(otherCharacterId);
63 this.stateDb.deleteFriendRequest(actorId, otherId);
64 this.stateDb.deleteFriendRequest(otherId, actorId);
65 return this.snapshot(actorId);
66 }
67
68 remove (characterId, otherCharacterId)
69 {
70 const actorId = Number(characterId);
71 const otherId = Number(otherCharacterId);
72 if (!this.stateDb.areFriends(actorId, otherId))
73 { throw userError("You are not friends with that player."); }
74 this.stateDb.deleteFriendship(actorId, otherId);
75 return this.snapshot(actorId);
76 }
77
78 findByFullName (firstName, lastName)
79 {
80 const row = this.stateDb.getCharacterByName(firstName, lastName);
81 return row ? this.#publicCharacter(row.character_id) : null;
82 }
83
84 #namedRequests (rows, idField)
85 {
86 return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);
87 }
88
89 #publicCharacter (characterId)
90 {
91 const row = this.stateDb.getCharacter(characterId);
92 if (!row)
93 { return null; }
94 return {
95 characterId: row.character_id,
96 firstName: row.first_name,
97 lastName: row.last_name
98 };
99 }
100
101 #requireCharacter (characterId)
102 {
103 if (!this.stateDb.getCharacter(characterId))
104 { throw userError("That player does not exist."); }
105 }
106 }
107
108 function userError (message)
109 {
110 const error = new Error(message);
111 error.userFacing = true;
112 return error;
113 }
@@ -0,0 +1,113 @@
1export class FriendService
2{
3 constructor (stateDb)
4 {
5 this.stateDb = stateDb;
6 }
7
8 snapshot (characterId)
9 {
10 return {
11 friends: this.listFriends(characterId),
12 incoming: this.#namedRequests(this.stateDb.listIncomingRequests(characterId), "from_character_id"),
13 outgoing: this.#namedRequests(this.stateDb.listOutgoingRequests(characterId), "to_character_id")
14 };
15 }
16
17 listFriends (characterId)
18 {
19 return this.stateDb.listFriendRecords(characterId).map((row) => this.#publicCharacter(row.character_id)).filter(Boolean);
20 }
21
22 request (fromCharacterId, toCharacterId)
23 {
24 const fromId = Number(fromCharacterId);
25 const toId = Number(toCharacterId);
26 if (fromId === toId)
27 { throw userError("You cannot friend yourself."); }
28 this.#requireCharacter(fromId);
29 this.#requireCharacter(toId);
30 if (this.stateDb.areFriends(fromId, toId))
31 { throw userError("You are already friends."); }
32 if (this.stateDb.getFriendRequest(fromId, toId))
33 { throw userError("Friend request already sent."); }
34 if (this.stateDb.getFriendRequest(toId, fromId))
35 {
36 this.stateDb.deleteFriendRequest(toId, fromId);
37 this.stateDb.insertFriendship(fromId, toId);
38 return this.snapshot(fromId);
39 }
40 this.stateDb.insertFriendRequest(fromId, toId);
41 return this.snapshot(fromId);
42 }
43
44 accept (characterId, fromCharacterId)
45 {
46 const toId = Number(characterId);
47 const fromId = Number(fromCharacterId);
48 this.#requireCharacter(toId);
49 this.#requireCharacter(fromId);
50 if (!this.stateDb.getFriendRequest(fromId, toId))
51 { throw userError("There is no friend request to accept."); }
52 this.stateDb.deleteFriendRequest(fromId, toId);
53 this.stateDb.deleteFriendRequest(toId, fromId);
54 if (!this.stateDb.areFriends(fromId, toId))
55 { this.stateDb.insertFriendship(fromId, toId); }
56 return this.snapshot(toId);
57 }
58
59 decline (characterId, otherCharacterId)
60 {
61 const actorId = Number(characterId);
62 const otherId = Number(otherCharacterId);
63 this.stateDb.deleteFriendRequest(actorId, otherId);
64 this.stateDb.deleteFriendRequest(otherId, actorId);
65 return this.snapshot(actorId);
66 }
67
68 remove (characterId, otherCharacterId)
69 {
70 const actorId = Number(characterId);
71 const otherId = Number(otherCharacterId);
72 if (!this.stateDb.areFriends(actorId, otherId))
73 { throw userError("You are not friends with that player."); }
74 this.stateDb.deleteFriendship(actorId, otherId);
75 return this.snapshot(actorId);
76 }
77
78 findByFullName (firstName, lastName)
79 {
80 const row = this.stateDb.getCharacterByName(firstName, lastName);
81 return row ? this.#publicCharacter(row.character_id) : null;
82 }
83
84 #namedRequests (rows, idField)
85 {
86 return rows.map((row) => this.#publicCharacter(row[idField])).filter(Boolean);
87 }
88
89 #publicCharacter (characterId)
90 {
91 const row = this.stateDb.getCharacter(characterId);
92 if (!row)
93 { return null; }
94 return {
95 characterId: row.character_id,
96 firstName: row.first_name,
97 lastName: row.last_name
98 };
99 }
100
101 #requireCharacter (characterId)
102 {
103 if (!this.stateDb.getCharacter(characterId))
104 { throw userError("That player does not exist."); }
105 }
106}
107
108function userError (message)
109{
110 const error = new Error(message);
111 error.userFacing = true;
112 return error;
113}
server/src/gateway/websocket.js +44 −2
@@ -5,7 +5,7 @@ import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 5
6 6 let nextSessionId = 1;
7 7
8 export function attachGateway ({ httpServer, auth, stateDb, characters, editor, simulation })
8 export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation })
9 9 {
10 10 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
11 11 const sessions = new Map();
@@ -102,6 +102,26 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
102 102 gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk
103 103 });
104 104 break;
105 case MessageType.friendRequest:
106 requirePlaying(session);
107 friends.request(session.characterId, message.characterId);
108 pushFriends(session.characterId, message.characterId);
109 break;
110 case MessageType.friendAccept:
111 requirePlaying(session);
112 friends.accept(session.characterId, message.characterId);
113 pushFriends(session.characterId, message.characterId);
114 break;
115 case MessageType.friendDecline:
116 requirePlaying(session);
117 friends.decline(session.characterId, message.characterId);
118 pushFriends(session.characterId, message.characterId);
119 break;
120 case MessageType.friendRemove:
121 requirePlaying(session);
122 friends.remove(session.characterId, message.characterId);
123 pushFriends(session.characterId, message.characterId);
124 break;
105 125 case MessageType.editorLoadChunk:
106 126 requireAdmin(session);
107 127 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -180,6 +200,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
180 200 worldTime: simulation.worldTime()
181 201 });
182 202 syncSubscriptions(session, true);
203 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
183 204 }
184 205
185 206 function leaveWorld (session)
@@ -258,6 +279,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
258 279 }
259 280 }
260 281
282 function pushFriends (...characterIds)
283 {
284 const seen = new Set();
285 for (const characterId of characterIds)
286 {
287 const id = Number(characterId);
288 if (!id || seen.has(id))
289 { continue; }
290 seen.add(id);
291 const payload = { type: MessageType.friends, ...friends.snapshot(id) };
292 for (const session of sessions.values())
293 {
294 if (session.characterId === id)
295 { send(session, payload); }
296 }
297 }
298 }
299
261 300 function broadcastSettings (payload)
262 301 {
263 302 for (const session of sessions.values())
@@ -296,7 +335,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
296 335 characterId: event.characterId,
297 336 tileX: event.tileX,
298 337 tileY: event.tileY,
299 gait: event.gait
338 gait: event.gait,
339 sex: event.sex,
340 firstName: event.firstName,
341 lastName: event.lastName
300 342 });
301 343 }
302 344 else if (seesFrom)
@@ -5,7 +5,7 @@ import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5
5
6let nextSessionId = 1;
6let nextSessionId = 1;
7
7
8export function attachGateway ({ httpServer, auth, stateDb, characters, editor, simulation })
8export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation })
9{
9{
10 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
10 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
11 const sessions = new Map();
11 const sessions = new Map();
@@ -102,6 +102,26 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
102 gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk
102 gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk
103 });
103 });
104 break;
104 break;
105 case MessageType.friendRequest:
106 requirePlaying(session);
107 friends.request(session.characterId, message.characterId);
108 pushFriends(session.characterId, message.characterId);
109 break;
110 case MessageType.friendAccept:
111 requirePlaying(session);
112 friends.accept(session.characterId, message.characterId);
113 pushFriends(session.characterId, message.characterId);
114 break;
115 case MessageType.friendDecline:
116 requirePlaying(session);
117 friends.decline(session.characterId, message.characterId);
118 pushFriends(session.characterId, message.characterId);
119 break;
120 case MessageType.friendRemove:
121 requirePlaying(session);
122 friends.remove(session.characterId, message.characterId);
123 pushFriends(session.characterId, message.characterId);
124 break;
105 case MessageType.editorLoadChunk:
125 case MessageType.editorLoadChunk:
106 requireAdmin(session);
126 requireAdmin(session);
107 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
127 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -180,6 +200,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
180 worldTime: simulation.worldTime()
200 worldTime: simulation.worldTime()
181 });
201 });
182 syncSubscriptions(session, true);
202 syncSubscriptions(session, true);
203 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
183 }
204 }
184
205
185 function leaveWorld (session)
206 function leaveWorld (session)
@@ -258,6 +279,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
258 }
279 }
259 }
280 }
260
281
282 function pushFriends (...characterIds)
283 {
284 const seen = new Set();
285 for (const characterId of characterIds)
286 {
287 const id = Number(characterId);
288 if (!id || seen.has(id))
289 { continue; }
290 seen.add(id);
291 const payload = { type: MessageType.friends, ...friends.snapshot(id) };
292 for (const session of sessions.values())
293 {
294 if (session.characterId === id)
295 { send(session, payload); }
296 }
297 }
298 }
299
261 function broadcastSettings (payload)
300 function broadcastSettings (payload)
262 {
301 {
263 for (const session of sessions.values())
302 for (const session of sessions.values())
@@ -296,7 +335,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
296 characterId: event.characterId,
335 characterId: event.characterId,
297 tileX: event.tileX,
336 tileX: event.tileX,
298 tileY: event.tileY,
337 tileY: event.tileY,
299 gait: event.gait
338 gait: event.gait,
339 sex: event.sex,
340 firstName: event.firstName,
341 lastName: event.lastName
300 });
342 });
301 }
343 }
302 else if (seesFrom)
344 else if (seesFrom)
server/src/index.js +3 −1
@@ -3,6 +3,7 @@ import { WorldDatabase } from "./persistence/worldDb.js";
3 3 import { StateDatabase } from "./persistence/stateDb.js";
4 4 import { EditorService } from "./editor/service.js";
5 5 import { CharacterService } from "./characters/service.js";
6 import { FriendService } from "./friends/service.js";
6 7 import { StubAuth } from "./auth/stub.js";
7 8 import { Simulation } from "./simulation/simulation.js";
8 9 import { createHttpServer, repoRootFrom } from "./gateway/http.js";
@@ -16,10 +17,11 @@ const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
16 17 const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
17 18 const editor = new EditorService(worldDb);
18 19 const characters = new CharacterService(stateDb, console);
20 const friends = new FriendService(stateDb);
19 21 const simulation = new Simulation(worldDb, stateDb);
20 22 const auth = new StubAuth();
21 23 const httpServer = createHttpServer(rootDir);
22 const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
24 const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
23 25
24 26 let tickTimer = null;
25 27 function scheduleTick ()
@@ -3,6 +3,7 @@ import { WorldDatabase } from "./persistence/worldDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
4import { EditorService } from "./editor/service.js";
4import { EditorService } from "./editor/service.js";
5import { CharacterService } from "./characters/service.js";
5import { CharacterService } from "./characters/service.js";
6import { FriendService } from "./friends/service.js";
6import { StubAuth } from "./auth/stub.js";
7import { StubAuth } from "./auth/stub.js";
7import { Simulation } from "./simulation/simulation.js";
8import { Simulation } from "./simulation/simulation.js";
8import { createHttpServer, repoRootFrom } from "./gateway/http.js";
9import { createHttpServer, repoRootFrom } from "./gateway/http.js";
@@ -16,10 +17,11 @@ const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
16const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
17const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
17const editor = new EditorService(worldDb);
18const editor = new EditorService(worldDb);
18const characters = new CharacterService(stateDb, console);
19const characters = new CharacterService(stateDb, console);
20const friends = new FriendService(stateDb);
19const simulation = new Simulation(worldDb, stateDb);
21const simulation = new Simulation(worldDb, stateDb);
20const auth = new StubAuth();
22const auth = new StubAuth();
21const httpServer = createHttpServer(rootDir);
23const httpServer = createHttpServer(rootDir);
22const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
24const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
23
25
24let tickTimer = null;
26let tickTimer = null;
25function scheduleTick ()
27function scheduleTick ()
server/src/persistence/stateDb.js +116 −0
@@ -26,6 +26,20 @@ CREATE TABLE IF NOT EXISTS characters (
26 26 gait TEXT NOT NULL DEFAULT 'walk',
27 27 deletion_scheduled_at INTEGER
28 28 );
29 CREATE TABLE IF NOT EXISTS friend_requests (
30 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
31 from_character_id INTEGER NOT NULL,
32 to_character_id INTEGER NOT NULL,
33 created_at INTEGER NOT NULL,
34 UNIQUE (from_character_id, to_character_id)
35 );
36
37 CREATE TABLE IF NOT EXISTS friendships (
38 character_id_a INTEGER NOT NULL,
39 character_id_b INTEGER NOT NULL,
40 created_at INTEGER NOT NULL,
41 PRIMARY KEY (character_id_a, character_id_b)
42 );
29 43 `;
30 44
31 45 export class StateDatabase
@@ -132,6 +146,14 @@ export class StateDatabase
132 146 try
133 147 {
134 148 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
149 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
150 characterId,
151 characterId
152 );
153 this.db.prepare("DELETE FROM friendships WHERE character_id_a = ? OR character_id_b = ?").run(
154 characterId,
155 characterId
156 );
135 157 const remaining = this.db.prepare(`
136 158 SELECT COUNT(*) AS count FROM characters
137 159 WHERE account_id = ? AND last_normalized = ?
@@ -170,6 +192,95 @@ export class StateDatabase
170 192 `).all(now);
171 193 }
172 194
195 getCharacterByName (firstName, lastName)
196 {
197 return this.db.prepare(`
198 SELECT * FROM characters
199 WHERE first_normalized = ? AND last_normalized = ?
200 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
201 }
202
203 listFriendRecords (characterId)
204 {
205 return this.db.prepare(`
206 SELECT
207 CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,
208 created_at
209 FROM friendships
210 WHERE character_id_a = ? OR character_id_b = ?
211 ORDER BY created_at ASC
212 `).all(characterId, characterId, characterId);
213 }
214
215 areFriends (characterId, otherId)
216 {
217 const [a, b] = pairIds(characterId, otherId);
218 return !!this.db.prepare(`
219 SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?
220 `).get(a, b);
221 }
222
223 insertFriendship (characterId, otherId)
224 {
225 const [a, b] = pairIds(characterId, otherId);
226 this.db.prepare(`
227 INSERT INTO friendships (character_id_a, character_id_b, created_at)
228 VALUES (?, ?, ?)
229 `).run(a, b, Date.now());
230 }
231
232 deleteFriendship (characterId, otherId)
233 {
234 const [a, b] = pairIds(characterId, otherId);
235 this.db.prepare(`
236 DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?
237 `).run(a, b);
238 }
239
240 listIncomingRequests (characterId)
241 {
242 return this.db.prepare(`
243 SELECT request_id, from_character_id, to_character_id, created_at
244 FROM friend_requests
245 WHERE to_character_id = ?
246 ORDER BY created_at ASC
247 `).all(characterId);
248 }
249
250 listOutgoingRequests (characterId)
251 {
252 return this.db.prepare(`
253 SELECT request_id, from_character_id, to_character_id, created_at
254 FROM friend_requests
255 WHERE from_character_id = ?
256 ORDER BY created_at ASC
257 `).all(characterId);
258 }
259
260 getFriendRequest (fromId, toId)
261 {
262 return this.db.prepare(`
263 SELECT * FROM friend_requests
264 WHERE from_character_id = ? AND to_character_id = ?
265 `).get(fromId, toId) ?? null;
266 }
267
268 insertFriendRequest (fromId, toId)
269 {
270 this.db.prepare(`
271 INSERT INTO friend_requests (from_character_id, to_character_id, created_at)
272 VALUES (?, ?, ?)
273 `).run(fromId, toId, Date.now());
274 }
275
276 deleteFriendRequest (fromId, toId)
277 {
278 this.db.prepare(`
279 DELETE FROM friend_requests
280 WHERE from_character_id = ? AND to_character_id = ?
281 `).run(fromId, toId);
282 }
283
173 284 close ()
174 285 {
175 286 this.db.close();
@@ -180,3 +291,8 @@ export function normalizeName (value)
180 291 {
181 292 return String(value ?? "").trim().toLocaleLowerCase();
182 293 }
294
295 function pairIds (left, right)
296 {
297 return left < right ? [left, right] : [right, left];
298 }
@@ -26,6 +26,20 @@ CREATE TABLE IF NOT EXISTS characters (
26 gait TEXT NOT NULL DEFAULT 'walk',
26 gait TEXT NOT NULL DEFAULT 'walk',
27 deletion_scheduled_at INTEGER
27 deletion_scheduled_at INTEGER
28);
28);
29CREATE TABLE IF NOT EXISTS friend_requests (
30 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
31 from_character_id INTEGER NOT NULL,
32 to_character_id INTEGER NOT NULL,
33 created_at INTEGER NOT NULL,
34 UNIQUE (from_character_id, to_character_id)
35);
36
37CREATE TABLE IF NOT EXISTS friendships (
38 character_id_a INTEGER NOT NULL,
39 character_id_b INTEGER NOT NULL,
40 created_at INTEGER NOT NULL,
41 PRIMARY KEY (character_id_a, character_id_b)
42);
29`;
43`;
30
44
31export class StateDatabase
45export class StateDatabase
@@ -132,6 +146,14 @@ export class StateDatabase
132 try
146 try
133 {
147 {
134 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
148 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
149 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
150 characterId,
151 characterId
152 );
153 this.db.prepare("DELETE FROM friendships WHERE character_id_a = ? OR character_id_b = ?").run(
154 characterId,
155 characterId
156 );
135 const remaining = this.db.prepare(`
157 const remaining = this.db.prepare(`
136 SELECT COUNT(*) AS count FROM characters
158 SELECT COUNT(*) AS count FROM characters
137 WHERE account_id = ? AND last_normalized = ?
159 WHERE account_id = ? AND last_normalized = ?
@@ -170,6 +192,95 @@ export class StateDatabase
170 `).all(now);
192 `).all(now);
171 }
193 }
172
194
195 getCharacterByName (firstName, lastName)
196 {
197 return this.db.prepare(`
198 SELECT * FROM characters
199 WHERE first_normalized = ? AND last_normalized = ?
200 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
201 }
202
203 listFriendRecords (characterId)
204 {
205 return this.db.prepare(`
206 SELECT
207 CASE WHEN character_id_a = ? THEN character_id_b ELSE character_id_a END AS character_id,
208 created_at
209 FROM friendships
210 WHERE character_id_a = ? OR character_id_b = ?
211 ORDER BY created_at ASC
212 `).all(characterId, characterId, characterId);
213 }
214
215 areFriends (characterId, otherId)
216 {
217 const [a, b] = pairIds(characterId, otherId);
218 return !!this.db.prepare(`
219 SELECT 1 FROM friendships WHERE character_id_a = ? AND character_id_b = ?
220 `).get(a, b);
221 }
222
223 insertFriendship (characterId, otherId)
224 {
225 const [a, b] = pairIds(characterId, otherId);
226 this.db.prepare(`
227 INSERT INTO friendships (character_id_a, character_id_b, created_at)
228 VALUES (?, ?, ?)
229 `).run(a, b, Date.now());
230 }
231
232 deleteFriendship (characterId, otherId)
233 {
234 const [a, b] = pairIds(characterId, otherId);
235 this.db.prepare(`
236 DELETE FROM friendships WHERE character_id_a = ? AND character_id_b = ?
237 `).run(a, b);
238 }
239
240 listIncomingRequests (characterId)
241 {
242 return this.db.prepare(`
243 SELECT request_id, from_character_id, to_character_id, created_at
244 FROM friend_requests
245 WHERE to_character_id = ?
246 ORDER BY created_at ASC
247 `).all(characterId);
248 }
249
250 listOutgoingRequests (characterId)
251 {
252 return this.db.prepare(`
253 SELECT request_id, from_character_id, to_character_id, created_at
254 FROM friend_requests
255 WHERE from_character_id = ?
256 ORDER BY created_at ASC
257 `).all(characterId);
258 }
259
260 getFriendRequest (fromId, toId)
261 {
262 return this.db.prepare(`
263 SELECT * FROM friend_requests
264 WHERE from_character_id = ? AND to_character_id = ?
265 `).get(fromId, toId) ?? null;
266 }
267
268 insertFriendRequest (fromId, toId)
269 {
270 this.db.prepare(`
271 INSERT INTO friend_requests (from_character_id, to_character_id, created_at)
272 VALUES (?, ?, ?)
273 `).run(fromId, toId, Date.now());
274 }
275
276 deleteFriendRequest (fromId, toId)
277 {
278 this.db.prepare(`
279 DELETE FROM friend_requests
280 WHERE from_character_id = ? AND to_character_id = ?
281 `).run(fromId, toId);
282 }
283
173 close ()
284 close ()
174 {
285 {
175 this.db.close();
286 this.db.close();
@@ -180,3 +291,8 @@ export function normalizeName (value)
180{
291{
181 return String(value ?? "").trim().toLocaleLowerCase();
292 return String(value ?? "").trim().toLocaleLowerCase();
182}
293}
294
295function pairIds (left, right)
296{
297 return left < right ? [left, right] : [right, left];
298}
server/src/simulation/simulation.js +5 −1
@@ -288,6 +288,7 @@ export class Simulation
288 288 this.#occupy(id, position.tileX, position.tileY);
289 289 this.#ensureVisibleChunks(position.tileX, position.tileY);
290 290 const character = this.ecs.get(id, "character");
291 const appearance = this.ecs.get(id, "appearance");
291 292 events.push({
292 293 type: "entity-move",
293 294 entityId: id,
@@ -296,7 +297,10 @@ export class Simulation
296 297 fromTileY,
297 298 tileX: position.tileX,
298 299 tileY: position.tileY,
299 gait: movement.gait
300 gait: movement.gait,
301 sex: appearance?.sex,
302 firstName: appearance?.firstName,
303 lastName: appearance?.lastName
300 304 });
301 305 }
302 306 return events;
@@ -288,6 +288,7 @@ export class Simulation
288 this.#occupy(id, position.tileX, position.tileY);
288 this.#occupy(id, position.tileX, position.tileY);
289 this.#ensureVisibleChunks(position.tileX, position.tileY);
289 this.#ensureVisibleChunks(position.tileX, position.tileY);
290 const character = this.ecs.get(id, "character");
290 const character = this.ecs.get(id, "character");
291 const appearance = this.ecs.get(id, "appearance");
291 events.push({
292 events.push({
292 type: "entity-move",
293 type: "entity-move",
293 entityId: id,
294 entityId: id,
@@ -296,7 +297,10 @@ export class Simulation
296 fromTileY,
297 fromTileY,
297 tileX: position.tileX,
298 tileX: position.tileX,
298 tileY: position.tileY,
299 tileY: position.tileY,
299 gait: movement.gait
300 gait: movement.gait,
301 sex: appearance?.sex,
302 firstName: appearance?.firstName,
303 lastName: appearance?.lastName
300 });
304 });
301 }
305 }
302 return events;
306 return events;
server/tests/friends.test.js added +87 −0
@@ -0,0 +1,87 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { StateDatabase } from "../src/persistence/stateDb.js";
7 import { FriendService } from "../src/friends/service.js";
8
9 function setup ()
10 {
11 const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
12 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
13 const accountA = stateDb.createAccount("admin-1", true);
14 const accountB = stateDb.createAccount("admin-2", true);
15 const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
16 const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
17 return {
18 stateDb,
19 friends: new FriendService(stateDb),
20 leftId: left.character_id,
21 rightId: right.character_id
22 };
23 }
24
25 test("a friend request must be accepted before both sides are friends", () =>
26 {
27 const { stateDb, friends, leftId, rightId } = setup();
28 try
29 {
30 const pending = friends.request(leftId, rightId);
31 assert.equal(pending.outgoing.length, 1);
32 assert.equal(pending.friends.length, 0);
33 assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");
34
35 friends.accept(rightId, leftId);
36 assert.equal(friends.snapshot(leftId).friends.length, 1);
37 assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");
38 assert.equal(friends.snapshot(leftId).outgoing.length, 0);
39 assert.equal(friends.snapshot(rightId).incoming.length, 0);
40 }
41 finally
42 { stateDb.close(); }
43 });
44
45 test("removing a friend removes them for both characters", () =>
46 {
47 const { stateDb, friends, leftId, rightId } = setup();
48 try
49 {
50 friends.request(leftId, rightId);
51 friends.accept(rightId, leftId);
52 friends.remove(leftId, rightId);
53 assert.equal(friends.snapshot(leftId).friends.length, 0);
54 assert.equal(friends.snapshot(rightId).friends.length, 0);
55 }
56 finally
57 { stateDb.close(); }
58 });
59
60 test("a reverse request accepts the pending invite", () =>
61 {
62 const { stateDb, friends, leftId, rightId } = setup();
63 try
64 {
65 friends.request(leftId, rightId);
66 friends.request(rightId, leftId);
67 assert.equal(friends.snapshot(leftId).friends.length, 1);
68 assert.equal(friends.snapshot(rightId).incoming.length, 0);
69 }
70 finally
71 { stateDb.close(); }
72 });
73
74 test("friends list is the pigeon address book of first and last names", () =>
75 {
76 const { stateDb, friends, leftId, rightId } = setup();
77 try
78 {
79 friends.request(leftId, rightId);
80 friends.accept(rightId, leftId);
81 const found = friends.findByFullName("Ben", "East");
82 assert.equal(found.characterId, rightId);
83 assert.deepEqual(friends.listFriends(leftId)[0], found);
84 }
85 finally
86 { stateDb.close(); }
87 });
@@ -0,0 +1,87 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { StateDatabase } from "../src/persistence/stateDb.js";
7import { FriendService } from "../src/friends/service.js";
8
9function setup ()
10{
11 const dir = mkdtempSync(join(tmpdir(), "mmo-friends-"));
12 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
13 const accountA = stateDb.createAccount("admin-1", true);
14 const accountB = stateDb.createAccount("admin-2", true);
15 const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8);
16 const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8);
17 return {
18 stateDb,
19 friends: new FriendService(stateDb),
20 leftId: left.character_id,
21 rightId: right.character_id
22 };
23}
24
25test("a friend request must be accepted before both sides are friends", () =>
26{
27 const { stateDb, friends, leftId, rightId } = setup();
28 try
29 {
30 const pending = friends.request(leftId, rightId);
31 assert.equal(pending.outgoing.length, 1);
32 assert.equal(pending.friends.length, 0);
33 assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada");
34
35 friends.accept(rightId, leftId);
36 assert.equal(friends.snapshot(leftId).friends.length, 1);
37 assert.equal(friends.snapshot(rightId).friends[0].lastName, "West");
38 assert.equal(friends.snapshot(leftId).outgoing.length, 0);
39 assert.equal(friends.snapshot(rightId).incoming.length, 0);
40 }
41 finally
42 { stateDb.close(); }
43});
44
45test("removing a friend removes them for both characters", () =>
46{
47 const { stateDb, friends, leftId, rightId } = setup();
48 try
49 {
50 friends.request(leftId, rightId);
51 friends.accept(rightId, leftId);
52 friends.remove(leftId, rightId);
53 assert.equal(friends.snapshot(leftId).friends.length, 0);
54 assert.equal(friends.snapshot(rightId).friends.length, 0);
55 }
56 finally
57 { stateDb.close(); }
58});
59
60test("a reverse request accepts the pending invite", () =>
61{
62 const { stateDb, friends, leftId, rightId } = setup();
63 try
64 {
65 friends.request(leftId, rightId);
66 friends.request(rightId, leftId);
67 assert.equal(friends.snapshot(leftId).friends.length, 1);
68 assert.equal(friends.snapshot(rightId).incoming.length, 0);
69 }
70 finally
71 { stateDb.close(); }
72});
73
74test("friends list is the pigeon address book of first and last names", () =>
75{
76 const { stateDb, friends, leftId, rightId } = setup();
77 try
78 {
79 friends.request(leftId, rightId);
80 friends.accept(rightId, leftId);
81 const found = friends.findByFullName("Ben", "East");
82 assert.equal(found.characterId, rightId);
83 assert.deepEqual(friends.listFriends(leftId)[0], found);
84 }
85 finally
86 { stateDb.close(); }
87});
shared/protocol/constants.js +6 −1
@@ -53,5 +53,10 @@ export const MessageType = Object.freeze({
53 53 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
54 54 editorSettings: "EDITOR_SETTINGS",
55 55 editorApplyRevision: "EDITOR_APPLY_REVISION",
56 editorChangelog: "EDITOR_CHANGELOG"
56 friendRequest: "FRIEND_REQUEST",
57 friendAccept: "FRIEND_ACCEPT",
58 friendDecline: "FRIEND_DECLINE",
59 friendRemove: "FRIEND_REMOVE",
60 friends: "FRIENDS"
57 61 });
62
@@ -53,5 +53,10 @@ export const MessageType = Object.freeze({
53 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
53 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
54 editorSettings: "EDITOR_SETTINGS",
54 editorSettings: "EDITOR_SETTINGS",
55 editorApplyRevision: "EDITOR_APPLY_REVISION",
55 editorApplyRevision: "EDITOR_APPLY_REVISION",
56 editorChangelog: "EDITOR_CHANGELOG"
56 friendRequest: "FRIEND_REQUEST",
57 friendAccept: "FRIEND_ACCEPT",
58 friendDecline: "FRIEND_DECLINE",
59 friendRemove: "FRIEND_REMOVE",
60 friends: "FRIENDS"
57});
61});
62
tile_mmo_server_technical_design_v0.6.md +41 −4
@@ -1,13 +1,13 @@
1 1 ---
2 2 title: Tile MMO Server Technical Design
3 version: 0.14
3 version: 0.15
4 4 status: proposed
5 5 format: living-design-document
6 6 ---
7 7
8 8 # Tile MMO Server Technical Design
9 9
10 **Version:** 0.14
10 **Version:** 0.15
11 11 **Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12 12 **Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13 13
@@ -2032,7 +2032,9 @@ SendPigeon
2032 2032
2033 2033 ## 23.4 Destinations
2034 2034
2035 **Player destination.** The pigeon flies toward the named player. On arrival:
2035 **Player destination.** The pigeon flies toward a character addressed by
2036 **first name and last name**. The sender may type that pair, or pick a
2037 friend from their friends list to fill the same fields. On arrival:
2036 2038
2037 2039 - Money is added to the recipient's carried `Currency` if they are online;
2038 2040 otherwise it is deposited into the recipient's bank.
@@ -2133,6 +2135,34 @@ Player action -> CourierService -> durable cargo/transit
2133 2135 This separation is also useful for marketplace settlement, which uses the same
2134 2136 carrier-pigeon delivery infrastructure for remote counterparties.
2135 2137
2138 ## 23.7 Character friends
2139
2140 Friendships are **character-to-character**, stored in `state.sqlite`. They
2141 are not account-wide. A hovering client shows only the nearby character's
2142 **first name**. Clicking that character opens an inspect modal with first
2143 and last name and a friend-request action.
2144
2145 A friend request must be accepted (or a reverse request counts as accept).
2146 Either character may remove the friendship; it then disappears for both.
2147 Incoming and outgoing requests and the friends list are shown in a Friends
2148 panel. Deleting a character clears its requests and friendships.
2149
2150 The friends list is an addressing book for later pigeon dispatch: pick a
2151 friend to fill first and last name, or type a name pair that the server
2152 resolves.
2153
2154 ```text
2155 FriendRequest
2156 - fromCharacterId
2157 - toCharacterId
2158 - createdAt
2159
2160 Friendship
2161 - characterIdA // min(id1, id2)
2162 - characterIdB // max(id1, id2)
2163 - createdAt
2164 ```
2165
2136 2166 # 24. Bank, cheques and shared vaults
2137 2167
2138 2168 ## 24.1 Bank location and access
@@ -3344,7 +3374,7 @@ Region → residency and simulation-worker ownership
3344 3374 Coordinator→ where regions execute
3345 3375 Gateway → stable client connections, auth, character select, and command/update routing
3346 3376 world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3347 state.sqlite→ accounts, characters, vaults, inheritance, and other durable live-game state
3377 state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state
3348 3378 systemd → process supervision and relaunch
3349 3379 Deployment hook → conditional Git update/build only for intentional deployment restarts
3350 3380 Controller → manual client input today; sandboxed player scripts later
@@ -3372,6 +3402,13 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3372 3402
3373 3403 # 34. Version history
3374 3404
3405 ## 0.15
3406
3407 - Hovering another player shows their first name. Clicking them opens an
3408 inspect modal (first + last name) to send a friend request. Requests
3409 must be accepted; removing a friend removes them on both sides. The
3410 friends list is the later pigeon address book.
3411
3375 3412 ## 0.14
3376 3413
3377 3414 - Ground and block types load visual states from per-type sprite folders
@@ -1,13 +1,13 @@
1---
1---
2title: Tile MMO Server Technical Design
2title: Tile MMO Server Technical Design
3version: 0.14
3version: 0.15
4status: proposed
4status: proposed
5format: living-design-document
5format: living-design-document
6---
6---
7
7
8# Tile MMO Server Technical Design
8# Tile MMO Server Technical Design
9
9
10**Version:** 0.14
10**Version:** 0.15
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
13
@@ -2032,7 +2032,9 @@ SendPigeon
2032
2032
2033## 23.4 Destinations
2033## 23.4 Destinations
2034
2034
2035**Player destination.** The pigeon flies toward the named player. On arrival:
2035**Player destination.** The pigeon flies toward a character addressed by
2036**first name and last name**. The sender may type that pair, or pick a
2037friend from their friends list to fill the same fields. On arrival:
2036
2038
2037- Money is added to the recipient's carried `Currency` if they are online;
2039- Money is added to the recipient's carried `Currency` if they are online;
2038 otherwise it is deposited into the recipient's bank.
2040 otherwise it is deposited into the recipient's bank.
@@ -2133,6 +2135,34 @@ Player action -> CourierService -> durable cargo/transit
2133This separation is also useful for marketplace settlement, which uses the same
2135This separation is also useful for marketplace settlement, which uses the same
2134carrier-pigeon delivery infrastructure for remote counterparties.
2136carrier-pigeon delivery infrastructure for remote counterparties.
2135
2137
2138## 23.7 Character friends
2139
2140Friendships are **character-to-character**, stored in `state.sqlite`. They
2141are not account-wide. A hovering client shows only the nearby character's
2142**first name**. Clicking that character opens an inspect modal with first
2143and last name and a friend-request action.
2144
2145A friend request must be accepted (or a reverse request counts as accept).
2146Either character may remove the friendship; it then disappears for both.
2147Incoming and outgoing requests and the friends list are shown in a Friends
2148panel. Deleting a character clears its requests and friendships.
2149
2150The friends list is an addressing book for later pigeon dispatch: pick a
2151friend to fill first and last name, or type a name pair that the server
2152resolves.
2153
2154```text
2155FriendRequest
2156- fromCharacterId
2157- toCharacterId
2158- createdAt
2159
2160Friendship
2161- characterIdA // min(id1, id2)
2162- characterIdB // max(id1, id2)
2163- createdAt
2164```
2165
2136# 24. Bank, cheques and shared vaults
2166# 24. Bank, cheques and shared vaults
2137
2167
2138## 24.1 Bank location and access
2168## 24.1 Bank location and access
@@ -3344,7 +3374,7 @@ Region → residency and simulation-worker ownership
3344Coordinator→ where regions execute
3374Coordinator→ where regions execute
3345Gateway → stable client connections, auth, character select, and command/update routing
3375Gateway → stable client connections, auth, character select, and command/update routing
3346world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3376world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3347state.sqlite→ accounts, characters, vaults, inheritance, and other durable live-game state
3377state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state
3348systemd → process supervision and relaunch
3378systemd → process supervision and relaunch
3349Deployment hook → conditional Git update/build only for intentional deployment restarts
3379Deployment hook → conditional Git update/build only for intentional deployment restarts
3350Controller → manual client input today; sandboxed player scripts later
3380Controller → manual client input today; sandboxed player scripts later
@@ -3372,6 +3402,13 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3372
3402
3373# 34. Version history
3403# 34. Version history
3374
3404
3405## 0.15
3406
3407- Hovering another player shows their first name. Clicking them opens an
3408 inspect modal (first + last name) to send a friend request. Requests
3409 must be accepted; removing a friend removes them on both sides. The
3410 friends list is the later pigeon address book.
3411
3375## 0.14
3412## 0.14
3376
3413
3377- Ground and block types load visual states from per-type sprite folders
3414- Ground and block types load visual states from per-type sprite folders