-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
804 lines (706 loc) · 24 KB
/
Copy pathserver.js
File metadata and controls
804 lines (706 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
require("dotenv").config();
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const fs = require("fs");
const path = require("path");
const cookieSession = require("cookie-session");
const pokemonData = require("./public/data/pokemon.json");
const itemData = require("./public/data/items.json");
const moveData = require("./public/data/moves.json");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
const knex = require("knex")(
require("./knexfile")[process.env.NODE_ENV || "development"]
);
// Run migrations on startup
knex.migrate.latest().then(() => {
console.log("Database migrations complete");
});
const SESSION_SECRET = process.env.SESSION_SECRET || "pokecode-dev-secret-change-me";
const HC_CLIENT_ID = process.env.HC_CLIENT_ID;
const HC_CLIENT_SECRET = process.env.HC_CLIENT_SECRET;
const configuredBaseUrl = process.env.BASE_URL || "http://localhost:3000";
const BASE_URL = new URL(
/^https?:\/\//i.test(configuredBaseUrl)
? configuredBaseUrl
: `https://${configuredBaseUrl}`
).toString().replace(/\/+$/, "");
const BASE_PATH = `${new URL(BASE_URL).pathname.replace(/\/+$/, "")}/`;
const publicDir = path.join(__dirname, "public");
const indexHtml = fs
.readFileSync(path.join(publicDir, "index.html"), "utf8")
.replace("__BASE_PATH__", BASE_PATH);
app.use(express.json());
app.use(
cookieSession({
name: "session",
keys: [SESSION_SECRET],
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
})
);
app.get(["/", "/index.html"], (req, res) => {
res.type("html").send(indexHtml);
});
app.use(express.static(publicDir, { index: false }));
// Auth middleware
function requireAuth(req, res, next) {
if (!req.session.userId) {
return res.status(401).json({ error: "Not authenticated" });
}
next();
}
async function requireAdmin(req, res, next) {
const user = await knex("users").where({ id: req.session.userId }).first();
if (!user?.admin) {
return res.status(403).json({ error: "Admin access required" });
}
next();
}
// Get current user
app.get("/api/me", async (req, res) => {
if (!req.session.userId) {
return res.json({ user: null });
}
const user = await knex("users").where({ id: req.session.userId }).first();
if (!user) {
req.session = null;
return res.json({ user: null });
}
const pokemon = await knex("user_pokemon")
.where({ userId: user.id })
.select("id")
.first();
res.json({
user: {
id: user.id,
email: user.email,
slackId: user.slackId,
username: user.username,
gender: user.gender,
x: user.x,
y: user.y,
direction: user.direction,
admin: user.admin,
needsStarter: !user.starterReceived && !pokemon,
},
});
});
// Start OAuth flow
app.get("/auth/login", (req, res) => {
const params = new URLSearchParams({
client_id: HC_CLIENT_ID,
redirect_uri: `${BASE_URL}/auth/callback`,
response_type: "code",
scope: "email slack_id",
});
res.redirect(`https://auth.hackclub.com/oauth/authorize?${params}`);
});
// OAuth callback
app.get("/auth/callback", async (req, res) => {
const { code } = req.query;
if (!code) {
return res.redirect(`${BASE_URL}/?error=no_code`);
}
try {
// Exchange code for tokens
const tokenRes = await fetch("https://auth.hackclub.com/oauth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
client_id: HC_CLIENT_ID,
client_secret: HC_CLIENT_SECRET,
redirect_uri: `${BASE_URL}/auth/callback`,
code,
grant_type: "authorization_code",
}),
});
if (!tokenRes.ok) {
console.error("Token exchange failed:", await tokenRes.text());
return res.redirect(`${BASE_URL}/?error=token_failed`);
}
const tokenData = await tokenRes.json();
// Get user info
const meRes = await fetch("https://auth.hackclub.com/api/v1/me", {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
if (!meRes.ok) {
console.error("User info fetch failed:", await meRes.text());
return res.redirect(`${BASE_URL}/?error=user_fetch_failed`);
}
const meData = await meRes.json();
const identity = meData.identity;
// Upsert user
let user = await knex("users").where({ hackclubId: identity.id }).first();
if (user) {
await knex("users").where({ id: user.id }).update({
email: identity.primary_email || user.email,
slackId: identity.slack_id || user.slackId,
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token,
updated_at: knex.fn.now(),
});
user = await knex("users").where({ id: user.id }).first();
} else {
const [newUser] = await knex("users")
.insert({
hackclubId: identity.id,
email: identity.primary_email,
slackId: identity.slack_id,
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token,
})
.returning("*");
user = newUser;
}
req.session.userId = user.id;
res.redirect(`${BASE_URL}/`);
} catch (err) {
console.error("OAuth error:", err);
res.redirect(`${BASE_URL}/?error=oauth_error`);
}
});
// Logout
app.post("/auth/logout", (req, res) => {
req.session = null;
res.json({ ok: true });
});
// Set username and gender (after first login)
app.post("/api/setup", requireAuth, async (req, res) => {
const { username, gender } = req.body;
if (!username || username.trim().length === 0 || username.trim().length > 12) {
return res.status(400).json({ error: "Username must be 1-12 characters" });
}
if (!["male", "female"].includes(gender)) {
return res.status(400).json({ error: "Invalid gender" });
}
const trimmed = username.trim();
// Check uniqueness
const existing = await knex("users")
.where({ username: trimmed })
.whereNot({ id: req.session.userId })
.first();
if (existing) {
return res.status(409).json({ error: "Username already taken" });
}
await knex("users").where({ id: req.session.userId }).update({
username: trimmed,
gender,
updated_at: knex.fn.now(),
});
const user = await knex("users").where({ id: req.session.userId }).first();
const pokemon = await knex("user_pokemon")
.where({ userId: user.id })
.select("id")
.first();
res.json({
user: {
id: user.id,
email: user.email,
slackId: user.slackId,
username: user.username,
gender: user.gender,
x: user.x,
y: user.y,
direction: user.direction,
admin: user.admin,
needsStarter: !user.starterReceived && !pokemon,
},
});
});
function learnableMovesForLevel(speciesId, level) {
return (pokemonData[speciesId]?.moves || [])
.filter((learnedMove) => learnedMove.level <= level)
.map((learnedMove) => learnedMove.move);
}
function knownMovesForLevel(speciesId, level) {
return learnableMovesForLevel(speciesId, level).slice(-4);
}
function maxHealthForLevel(speciesId, level) {
const baseHp = pokemonData[speciesId].stats.HP;
return Math.floor((baseHp * 2 * level) / 100) + level + 10;
}
function formatOwnedPokemon(row) {
return {
id: row.id,
speciesId: row.speciesId,
nickname: row.nickname,
level: row.level,
health: row.health,
friendship: row.friendship,
slot: row.slot,
moves: Array.isArray(row.moves) ? row.moves : [],
};
}
const STARTER_SPECIES = new Set([
"charmander",
"bulbasaur",
"squirtle",
"eevee",
"pikachu",
]);
// Give an eligible user their one-time level 5 starter.
app.post("/api/starter", requireAuth, async (req, res) => {
const { speciesId } = req.body;
if (!STARTER_SPECIES.has(speciesId)) {
return res.status(400).json({ error: "Invalid starter Pokémon" });
}
try {
const pokemon = await knex.transaction(async (trx) => {
const user = await trx("users")
.where({ id: req.session.userId })
.forUpdate()
.first();
if (user.starterReceived) {
const err = new Error("Starter already received");
err.status = 409;
throw err;
}
const existingPokemon = await trx("user_pokemon")
.where({ userId: user.id })
.select("id")
.first();
if (existingPokemon) {
const err = new Error("You already have a Pokémon");
err.status = 409;
throw err;
}
const level = 5;
const [row] = await trx("user_pokemon")
.insert({
userId: user.id,
speciesId,
location: "party",
slot: 0,
level,
health: maxHealthForLevel(speciesId, level),
moves: JSON.stringify(knownMovesForLevel(speciesId, level)),
})
.returning("*");
await trx("users").where({ id: user.id }).update({
starterReceived: true,
updated_at: trx.fn.now(),
});
return row;
});
res.status(201).json({ pokemon: formatOwnedPokemon(pokemon) });
} catch (err) {
if (err.status) {
return res.status(err.status).json({ error: err.message });
}
throw err;
}
});
// Get the current user's Pokémon, split into party (max 6) and box
app.get("/api/my-pokemon", requireAuth, async (req, res) => {
const rows = await knex("user_pokemon")
.where({ userId: req.session.userId })
.orderBy("slot", "asc");
res.json({
party: rows.filter((r) => r.location === "party").map(formatOwnedPokemon),
box: rows.filter((r) => r.location === "box").map(formatOwnedPokemon),
});
});
// Update the four moves known by one of the current user's Pokémon.
app.patch("/api/my-pokemon/:id/moves", requireAuth, async (req, res) => {
const pokemonId = Number(req.params.id);
const selectedMoves = req.body?.moves;
if (!Number.isInteger(pokemonId) || pokemonId <= 0 || !Array.isArray(selectedMoves)) {
return res.status(400).json({ error: "Invalid move selection" });
}
const pokemon = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.first();
if (!pokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
const learnableMoves = learnableMovesForLevel(pokemon.speciesId, pokemon.level);
const requiredMoveCount = Math.min(4, learnableMoves.length);
const uniqueMoves = new Set(selectedMoves);
const isValidSelection =
selectedMoves.length === requiredMoveCount &&
uniqueMoves.size === selectedMoves.length &&
selectedMoves.every(
(moveId) => typeof moveId === "string" && learnableMoves.includes(moveId)
);
if (!isValidSelection) {
return res.status(400).json({
error: `Choose exactly ${requiredMoveCount} moves this Pokémon can learn`,
});
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ moves: JSON.stringify(selectedMoves), updated_at: knex.fn.now() })
.returning("*");
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can update the level of one of their Pokémon.
app.patch("/api/my-pokemon/:id/level", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
const level = Number(req.body?.level);
if (
!Number.isInteger(pokemonId) ||
pokemonId <= 0 ||
!Number.isInteger(level) ||
level < 1 ||
level > 100
) {
return res.status(400).json({ error: "Level must be a whole number from 1 to 100" });
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ level, updated_at: knex.fn.now() })
.returning("*");
if (!updatedPokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can update the health of one of their Pokémon.
app.patch("/api/my-pokemon/:id/health", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
const health = Number(req.body?.health);
if (!Number.isInteger(pokemonId) || pokemonId <= 0 || !Number.isInteger(health)) {
return res.status(400).json({ error: "Health must be a whole number" });
}
const pokemon = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.first();
if (!pokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
const maxHealth = maxHealthForLevel(pokemon.speciesId, pokemon.level);
if (health < 0 || health > maxHealth) {
return res.status(400).json({
error: `Health must be a whole number from 0 to ${maxHealth}`,
});
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ health, updated_at: knex.fn.now() })
.returning("*");
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can add a Pokémon directly to their own party
app.post("/api/my-pokemon", requireAuth, requireAdmin, async (req, res) => {
const { speciesId } = req.body;
if (typeof speciesId !== "string" || !pokemonData[speciesId]) {
return res.status(400).json({ error: "Invalid Pokémon species" });
}
try {
const pokemon = await knex.transaction(async (trx) => {
// Lock the user row so simultaneous requests cannot overfill the party.
await trx("users").where({ id: req.session.userId }).forUpdate().first();
const party = await trx("user_pokemon")
.where({ userId: req.session.userId, location: "party" })
.orderBy("slot", "asc");
if (party.length >= 6) {
const err = new Error("Your party is full");
err.status = 409;
throw err;
}
const usedSlots = new Set(party.map((row) => row.slot));
let slot = 0;
while (usedSlots.has(slot)) slot++;
const [row] = await trx("user_pokemon")
.insert({
userId: req.session.userId,
speciesId,
location: "party",
slot,
health: maxHealthForLevel(speciesId, 1),
moves: JSON.stringify(knownMovesForLevel(speciesId, 1)),
})
.returning("*");
return row;
});
res.status(201).json({
pokemon: formatOwnedPokemon(pokemon),
});
} catch (err) {
if (err.status) {
return res.status(err.status).json({ error: err.message });
}
throw err;
}
});
// Admins can delete one of their Pokémon.
app.delete("/api/my-pokemon/:id", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
if (!Number.isInteger(pokemonId) || pokemonId <= 0) {
return res.status(400).json({ error: "Invalid Pokémon" });
}
const deleted = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.del();
if (!deleted) {
return res.status(404).json({ error: "Pokémon not found" });
}
res.json({ ok: true });
});
// Get the current user's item quantities. Item details live in items.json.
app.get("/api/my-items", requireAuth, async (req, res) => {
const rows = await knex("user_items")
.where({ userId: req.session.userId })
.orderBy("itemId", "asc");
res.json({
items: rows.map((row) => ({
itemId: row.itemId,
quantity: row.quantity,
})),
});
});
// Admins can add one or more items to their own bag.
app.post("/api/my-items", requireAuth, requireAdmin, async (req, res) => {
const { itemId } = req.body;
const quantity = Number(req.body?.quantity ?? 1);
if (typeof itemId !== "string" || !itemData[itemId]) {
return res.status(400).json({ error: "Invalid item" });
}
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 999) {
return res.status(400).json({ error: "Quantity must be a whole number from 1 to 999" });
}
const [item] = await knex("user_items")
.insert({ userId: req.session.userId, itemId, quantity })
.onConflict(["userId", "itemId"])
.merge({
quantity: knex.raw("user_items.quantity + ?", [quantity]),
updated_at: knex.fn.now(),
})
.returning(["itemId", "quantity"]);
res.status(201).json({ item });
});
// Persist the player-owned state produced by a completed battle.
app.post("/api/battle/results", requireAuth, async (req, res) => {
const health = req.body?.health;
const usedItems = req.body?.usedItems;
const caughtPokemon = req.body?.caughtPokemon || null;
if (!Array.isArray(health) || !Array.isArray(usedItems)) {
return res.status(400).json({ error: "Invalid battle results" });
}
try {
const caught = await knex.transaction(async (trx) => {
const party = await trx("user_pokemon")
.where({ userId: req.session.userId, location: "party" })
.orderBy("slot", "asc")
.forUpdate();
const partyById = new Map(party.map((pokemon) => [pokemon.id, pokemon]));
if (health.length !== party.length) {
const error = new Error("The party changed during the battle");
error.status = 409;
throw error;
}
for (const result of health) {
const pokemon = partyById.get(Number(result?.id));
const value = Number(result?.health);
const maxHealth = pokemon
? maxHealthForLevel(pokemon.speciesId, pokemon.level)
: -1;
if (!pokemon || !Number.isInteger(value) || value < 0 || value > maxHealth) {
const error = new Error("Invalid Pokémon health result");
error.status = 400;
throw error;
}
await trx("user_pokemon")
.where({ id: pokemon.id, userId: req.session.userId })
.update({ health: value, updated_at: trx.fn.now() });
}
const itemTotals = new Map();
for (const usedItem of usedItems) {
const itemId = usedItem?.itemId;
const quantity = Number(usedItem?.quantity);
if (!itemData[itemId]?.battleUsable || !Number.isInteger(quantity) || quantity < 1) {
const error = new Error("Invalid used item");
error.status = 400;
throw error;
}
itemTotals.set(itemId, (itemTotals.get(itemId) || 0) + quantity);
}
for (const [itemId, quantity] of itemTotals) {
const item = await trx("user_items")
.where({ userId: req.session.userId, itemId })
.forUpdate()
.first();
if (!item || item.quantity < quantity) {
const error = new Error(`Not enough ${itemData[itemId].name}`);
error.status = 409;
throw error;
}
if (item.quantity === quantity) {
await trx("user_items").where({ id: item.id }).del();
} else {
await trx("user_items")
.where({ id: item.id })
.update({ quantity: item.quantity - quantity, updated_at: trx.fn.now() });
}
}
if (!caughtPokemon) return null;
const { speciesId, destination } = caughtPokemon;
const level = Number(caughtPokemon.level);
const caughtHealth = Number(caughtPokemon.health);
const moves = caughtPokemon.moves;
if (
!pokemonData[speciesId] ||
!["party", "box"].includes(destination) ||
!Number.isInteger(level) ||
level < 1 ||
level > 100 ||
!Number.isInteger(caughtHealth) ||
caughtHealth < 1 ||
caughtHealth > maxHealthForLevel(speciesId, level) ||
!Array.isArray(moves) ||
moves.length < 1 ||
moves.length > 4 ||
moves.some((moveId) => typeof moveId !== "string" || !moveData[moveId])
) {
const error = new Error("Invalid caught Pokémon");
error.status = 400;
throw error;
}
if (destination === "party" && party.length >= 6) {
const error = new Error("Your party is full");
error.status = 409;
throw error;
}
const destinationPokemon = await trx("user_pokemon")
.where({ userId: req.session.userId, location: destination })
.orderBy("slot", "asc");
const usedSlots = new Set(destinationPokemon.map((pokemon) => pokemon.slot));
let slot = 0;
while (usedSlots.has(slot)) slot++;
const [newPokemon] = await trx("user_pokemon")
.insert({
userId: req.session.userId,
speciesId,
location: destination,
slot,
level,
health: caughtHealth,
moves: JSON.stringify(moves),
})
.returning("*");
return formatOwnedPokemon(newPokemon);
});
res.json({ ok: true, caughtPokemon: caught });
} catch (error) {
if (error.status) {
return res.status(error.status).json({ error: error.message });
}
throw error;
}
});
// Track which sockets belong to which user
const activeSockets = {}; // socketId -> userId
const players = {};
io.on("connection", (socket) => {
console.log(`Socket connected: ${socket.id}`);
socket.on("playerJoin", async (data) => {
const { userId } = data;
if (!userId) return;
const user = await knex("users").where({ id: userId }).first();
if (!user || !user.username) return;
activeSockets[socket.id] = userId;
players[socket.id] = {
id: socket.id,
name: user.username,
gender: user.gender,
x: user.x,
y: user.y,
direction: user.direction || "down",
moving: false,
};
socket.emit("currentPlayers", players);
socket.broadcast.emit("playerJoined", players[socket.id]);
// Broadcast join message to all players
const joinMsg = {
username: user.username,
message: `${user.username} joined the game!`,
type: "system",
timestamp: Date.now(),
};
io.emit("chatMessage", joinMsg);
// Log join message to DB after broadcast
knex("chat_messages")
.insert({
userId: userId,
username: user.username,
message: joinMsg.message,
type: "system",
})
.catch((err) => console.error("Failed to log join message:", err));
});
socket.on("chatMessage", async (data) => {
const player = players[socket.id];
const userId = activeSockets[socket.id];
if (!player || !userId || !data.message) return;
const message = data.message.trim().slice(0, 200);
if (!message) return;
const msg = {
username: player.name,
message,
type: "chat",
timestamp: Date.now(),
};
io.emit("chatMessage", msg);
// Log to DB after broadcast
knex("chat_messages")
.insert({
userId,
username: player.name,
message,
type: "chat",
})
.catch((err) => console.error("Failed to log chat message:", err));
});
socket.on("playerMove", async (data) => {
if (!players[socket.id]) return;
players[socket.id].x = data.x;
players[socket.id].y = data.y;
players[socket.id].direction = data.direction;
players[socket.id].moving = data.moving;
socket.broadcast.emit("playerMoved", {
id: socket.id,
x: data.x,
y: data.y,
direction: data.direction,
moving: data.moving,
});
// Persist position to DB (throttled per socket via debounce)
if (!socket._saveTimer) {
socket._saveTimer = setTimeout(async () => {
socket._saveTimer = null;
const userId = activeSockets[socket.id];
if (userId && players[socket.id]) {
await knex("users").where({ id: userId }).update({
x: players[socket.id].x,
y: players[socket.id].y,
direction: players[socket.id].direction,
});
}
}, 2000);
}
});
socket.on("disconnect", async () => {
console.log(`Socket disconnected: ${socket.id}`);
// Save final position
const userId = activeSockets[socket.id];
if (userId && players[socket.id]) {
await knex("users").where({ id: userId }).update({
x: players[socket.id].x,
y: players[socket.id].y,
direction: players[socket.id].direction,
});
}
if (socket._saveTimer) {
clearTimeout(socket._saveTimer);
}
delete activeSockets[socket.id];
delete players[socket.id];
io.emit("playerDisconnected", socket.id);
});
});
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});