-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
214 lines (188 loc) · 7.1 KB
/
Copy pathserver.js
File metadata and controls
214 lines (188 loc) · 7.1 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
// Pique Catch — Node web server + global multiplayer relay (Render Web Service).
// Serves the Vite build and runs the authoritative game loop on the same port:
// every round one player is "marked" and everyone else has 30s to tag them.
// Tag -> the catcher scores; nobody tags in time -> the marked player scores.
const http = require('http');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
// Vite builds the client into ./dist; that's what we serve in production.
const ROOT = path.join(__dirname, 'dist');
const PORT = process.env.PORT || 3000;
const HOST = '0.0.0.0';
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.ogg': 'audio/ogg',
'.map': 'application/json; charset=utf-8',
'.ttf': 'font/ttf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
// ---------------------------------------------------------------- static files
const server = http.createServer((req, res) => {
let urlPath = decodeURIComponent(req.url.split('?')[0]);
if (urlPath === '/') urlPath = '/index.html';
const filePath = path.normalize(path.join(ROOT, urlPath));
if (!filePath.startsWith(ROOT)) {
res.writeHead(403);
return res.end('Forbidden');
}
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('Not found');
}
const ext = path.extname(filePath).toLowerCase();
// index.html must always revalidate (it points at the current hashed bundle);
// hashed assets are safe to cache. This avoids stale clients after a deploy.
const cache = ext === '.html' ? 'no-cache' : 'public, max-age=3600';
res.writeHead(200, {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Cache-Control': cache
});
fs.createReadStream(filePath).pipe(res);
});
});
// ----------------------------------------------------------------- game config
const ROUND_MS = 30000; // time the marked player must survive
const GRACE_MS = 1500; // no tags count right after a round starts
const CATCH_DIST = 22; // tag radius (player sprite is ~16px)
const COLORS = [
0xff4d4d, 0x4286f4, 0x4bd964, 0xffd23f, 0xff8c42,
0xb967ff, 0x35d0ba, 0xff6fcf, 0xa0e426, 0xff5e5e,
];
const SPAWNS = [
[150, 290], [650, 290], [400, 200], [250, 350], [550, 350],
];
let nextId = 1;
const players = new Map(); // id -> { id, name, x, y, flip, color, score, ws }
// round state
let phase = 'waiting'; // 'waiting' | 'playing' | 'intermission'
let marked = null; // id of the marked player
let phaseUntil = 0; // timestamp when the current phase ends
let roundStartedAt = 0;
function sanitizeName(raw) {
if (typeof raw !== 'string') return 'Player';
const name = raw.replace(/[ -<>]/g, '').trim().slice(0, 16);
return name.length ? name : 'Player';
}
const wss = new WebSocket.Server({ server });
function broadcast(obj) {
const data = typeof obj === 'string' ? obj : JSON.stringify(obj);
wss.clients.forEach((c) => {
if (c.readyState === WebSocket.OPEN) c.send(data);
});
}
function beginRound(now) {
const list = [...players.values()];
if (list.length === 0) { phase = 'waiting'; marked = null; return; }
let candidates = list.filter((p) => p.id !== marked);
if (candidates.length === 0) candidates = list;
const chosen = candidates[Math.floor(Math.random() * candidates.length)];
marked = chosen.id;
roundStartedAt = now;
phaseUntil = now + ROUND_MS;
phase = 'playing';
broadcast({ t: 'round', marked, name: chosen.name });
}
function beginIntermission(now, ms) {
phase = 'intermission';
marked = null;
phaseUntil = now + ms;
}
function awardCaught(catcher, victim) {
catcher.score = (catcher.score || 0) + 1;
broadcast({
t: 'roundEnd', reason: 'caught', winner: catcher.id, name: catcher.name,
catcher: { id: catcher.id, name: catcher.name, x: Math.round(catcher.x), y: Math.round(catcher.y) },
victim: { id: victim.id, name: victim.name, x: Math.round(victim.x), y: Math.round(victim.y) }
});
// long enough for the freeze-frame cinematic to finish before the next round
beginIntermission(Date.now(), 3400);
}
function awardSurvived(survivor) {
survivor.score = (survivor.score || 0) + 1;
broadcast({ t: 'roundEnd', reason: 'survived', winner: survivor.id, name: survivor.name });
beginIntermission(Date.now(), 1800);
}
function tick() {
const now = Date.now();
if (players.size === 0) { phase = 'waiting'; marked = null; return; }
if (phase === 'waiting') {
beginRound(now);
} else if (phase === 'intermission') {
if (now >= phaseUntil) beginRound(now);
} else if (phase === 'playing') {
const m = players.get(marked);
if (!m) { beginIntermission(now, 800); return; }
if (now >= phaseUntil) { awardSurvived(m); return; }
if (now - roundStartedAt > GRACE_MS) {
for (const p of players.values()) {
if (p.id === marked) continue;
const dx = p.x - m.x;
const dy = p.y - m.y;
if (dx * dx + dy * dy < CATCH_DIST * CATCH_DIST) {
awardCaught(p, m);
break;
}
}
}
}
}
function snapshot() {
const now = Date.now();
const list = [];
players.forEach((p) => {
list.push({
id: p.id, name: p.name,
x: Math.round(p.x), y: Math.round(p.y),
flip: p.flip, color: p.color, score: p.score || 0,
});
});
const roundLeft = phase === 'playing' ? Math.max(0, Math.ceil((phaseUntil - now) / 1000)) : 0;
return JSON.stringify({ t: 'state', players: list, marked, roundLeft, phase });
}
// authoritative loop: update the round, then broadcast the world ~20x/second
setInterval(() => {
tick();
if (players.size > 0) broadcast(snapshot());
}, 50);
// ---------------------------------------------------------------- connections
wss.on('connection', (ws) => {
const id = nextId++;
const spawn = SPAWNS[id % SPAWNS.length];
const color = COLORS[id % COLORS.length];
const player = { id, name: 'Player', x: spawn[0], y: spawn[1], flip: false, color, score: 0, ws };
ws.on('message', (raw) => {
let msg;
try { msg = JSON.parse(raw); } catch (e) { return; }
if (msg.t === 'join') {
player.name = sanitizeName(msg.name);
players.set(id, player);
ws.send(JSON.stringify({ t: 'welcome', id, color, x: player.x, y: player.y }));
} else if (msg.t === 'move' && players.has(id)) {
if (typeof msg.x === 'number') player.x = msg.x;
if (typeof msg.y === 'number') player.y = msg.y;
player.flip = !!msg.flip;
} else if (msg.t === 'ping') {
ws.send(JSON.stringify({ t: 'pong', ts: msg.ts }));
}
});
ws.on('close', () => { players.delete(id); });
ws.on('error', () => { players.delete(id); });
});
server.listen(PORT, HOST, () => {
console.log(`Pique Catch server running on http://${HOST}:${PORT}`);
});