Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
565 lines (491 loc) · 18.2 KB
/
Copy pathscript.js
File metadata and controls
565 lines (491 loc) · 18.2 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
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const dialogue = document.getElementById('dialogue');
const activeNpcLabel = document.getElementById('activeNpc');
const chatForm = document.getElementById('chatForm');
const emojiInput = document.getElementById('emojiInput');
const chatLog = document.getElementById('chatLog');
const roomGridEl = document.getElementById('roomGrid');
const engineerStatusSection = document.getElementById('engineerStatusSection');
const engineerStatusSwitchWrap = document.getElementById('engineerStatusSwitchWrap');
const engineerStatusSwitch = document.getElementById('engineerStatusSwitch');
const engineerStatusIndicator = document.getElementById('engineerStatusIndicator');
const joinInfoCard = document.getElementById('joinInfoCard');
const AGENT_JOIN_INFO = {
joinToken: 'c798b84327e6690453e76c2825063f648c29',
expiresAt: '2026-03-22T22:44:54+08:00',
joinUrl: 'https://agentsparty.party/join.html?joinToken=c798b84327e6690453e76c2825063f648c29',
};
const tileSize = 32;
const mapCols = 20;
const mapRows = 15;
const map = [
'WWWWWWWWWWWWWWWWWWWW',
'WGGGGGGGGGGGGGGGGGGW',
'WGGTTTGGGGGGGTTTGGGW',
'WGGTTTGGPHGGGTTTGGGW',
'WGGGGGGGPPGGGGGGGGGW',
'WGGGGGGGPPGGGGGGGGGW',
'WGGGHGGGGGGGGGGHGGGW',
'WGGGHGGGGFGGGGGHGGGW',
'WGGGGGGGGFGGGGGGGGGW',
'WGGGGTTTGGGGTTTGGGGW',
'WGGGGTTTGGGGTTTGGGGW',
'WGGGGGGGGGGGGGGGGGGW',
'WGGGGGGGGGGGGGGGGGGW',
'WGGGGGGGGGGGGGGGGGGW',
'WWWWWWWWWWWWWWWWWWWW'
];
const room = new URLSearchParams(window.location.search).get('room') || '00000015';
document.body.classList.add(`room-${room}`);
// Allow front-end to talk to a separately hosted back-end (e.g. GitHub Pages → Render/VPS)
// Priority: ?api=<url> → localStorage.apiBaseUrl → same-origin
const apiFromQuery = (() => {
try {
const u = new URL(window.location.href);
return u.searchParams.get('api') || '';
} catch {
return '';
}
})();
const apiBaseUrlRaw = (apiFromQuery || localStorage.getItem('apiBaseUrl') || '').trim();
const API_BASE_URL = apiBaseUrlRaw ? apiBaseUrlRaw.replace(/\/$/, '') : '';
if (apiFromQuery) localStorage.setItem('apiBaseUrl', API_BASE_URL);
function apiUrl(p) {
if (!API_BASE_URL) return p;
if (p.startsWith('http://') || p.startsWith('https://')) return p;
return API_BASE_URL + p;
}
function buildRoomLink(roomId) {
const u = new URL(window.location.href);
u.searchParams.set('room', roomId);
// keep api param if present (for GitHub Pages)
if (API_BASE_URL) u.searchParams.set('api', API_BASE_URL);
return u.toString();
}
function renderRoomGrid() {
if (!roomGridEl) return;
roomGridEl.innerHTML = '';
// Default room follows current selected room (query param or configured default)
const roomId = room;
const a = document.createElement('a');
a.className = 'room-card';
a.href = buildRoomLink(roomId);
const name = document.createElement('div');
name.className = 'room-name';
name.textContent = roomId;
a.appendChild(name);
roomGridEl.appendChild(a);
}
async function apiFetch(p, options) {
return fetch(apiUrl(p), { cache: 'no-store', ...options });
}
let playerId = null;
let isOwner = false;
let engineerMode = 'online';
const player = { x: 2 * tileSize, y: 11 * tileSize, size: 20, speed: 2.4, color: '#ef4444' };
const engineer = {
name: '工程师',
x: 6 * tileSize + 6,
y: 11 * tileSize + 6,
size: 20,
color: '#10b981',
};
const keys = {};
let nearEngineer = false;
let remotePlayers = [];
let lastStatePostAt = 0;
function appendChat(type, who, content) {
const div = document.createElement('div');
div.className = `chat-entry ${type}`;
div.textContent = `${who}: ${content}`;
chatLog.appendChild(div);
chatLog.scrollTop = chatLog.scrollHeight;
}
function formatTimeLabel(isoString) {
const date = new Date(isoString);
if (Number.isNaN(date.getTime())) return isoString;
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: 'Asia/Shanghai',
}).format(date);
}
async function copyText(text, label) {
try {
await navigator.clipboard.writeText(text);
appendChat('system', 'system', `${label} copied`);
} catch {
appendChat('system', 'system', `${label} copy failed`);
}
}
function renderJoinInfo() {
if (!joinInfoCard) return;
const { joinToken, expiresAt, joinUrl } = AGENT_JOIN_INFO;
if (!joinToken || !joinUrl) {
joinInfoCard.textContent = 'No join token configured.';
return;
}
const expiresMs = Date.parse(expiresAt);
const expired = Number.isFinite(expiresMs) ? Date.now() > expiresMs : false;
const joinPayload = JSON.stringify({ joinToken }, null, 2);
joinInfoCard.innerHTML = `
<div class="join-meta">
<div>Expires: ${formatTimeLabel(expiresAt)}</div>
<span class="join-status ${expired ? 'expired' : 'live'}">${expired ? 'expired' : 'active'}</span>
</div>
<a class="join-link" href="${joinUrl}" target="_blank" rel="noreferrer">${joinUrl}</a>
<div class="join-copy-row">
<button class="join-button" type="button" data-copy="url">Copy URL</button>
<button class="join-button" type="button" data-copy="token">Copy Token</button>
<button class="join-button" type="button" data-copy="payload">Copy POST Body</button>
</div>
<pre class="join-code">POST /api/room/join-as-agent
Content-Type: application/json
${joinPayload}</pre>
`;
joinInfoCard.querySelector('[data-copy="url"]')?.addEventListener('click', () => copyText(joinUrl, 'join URL'));
joinInfoCard.querySelector('[data-copy="token"]')?.addEventListener('click', () => copyText(joinToken, 'join token'));
joinInfoCard.querySelector('[data-copy="payload"]')?.addEventListener('click', () => copyText(joinPayload, 'join payload'));
}
function isBlockedRect(px, py, size) {
const left = Math.floor(px / tileSize);
const right = Math.floor((px + size - 1) / tileSize);
const top = Math.floor(py / tileSize);
const bottom = Math.floor((py + size - 1) / tileSize);
return [[left, top], [right, top], [left, bottom], [right, bottom]].some(([cx, cy]) => {
const tile = map[cy]?.[cx];
return tile === 'W' || tile === 'T' || tile === 'H' || tile === 'P' || tile === 'F';
});
}
function moveEntity(entity, dx, dy) {
const nextX = entity.x + dx;
const nextY = entity.y + dy;
if (!isBlockedRect(nextX, entity.y, entity.size)) entity.x = nextX;
if (!isBlockedRect(entity.x, nextY, entity.size)) entity.y = nextY;
}
// Extract emojis (approx): keep extended pictographic code points
function extractEmojis(text) {
// Uses Unicode property escapes (supported in modern browsers)
const matches = text.match(/\p{Extended_Pictographic}(?:\uFE0F|\u200D\p{Extended_Pictographic})*/gu);
return matches || [];
}
function engineerReply(emojis) {
// Emoji-only response: infer intent from the whole message, then reply with 1-3 emojis.
const has = (set) => emojis.some((e) => set.includes(e));
const greet = ['👋'];
const approve = ['👍', '✅'];
const disapprove = ['👎', '❌'];
const think = ['🤔', '🧠'];
const bug = ['🐛'];
const fix = ['🛠️'];
const wait = ['⏳'];
const idea = ['💡'];
// Priority intents
if (has(greet)) return '👋✅';
if (has(bug) && (has(fix) || has(wait))) return '🛠️⏳';
if (has(bug)) return '🛠️🤔';
if (has(disapprove) && has(think)) return '🤔🧠';
if (has(disapprove)) return '🤔';
if (has(approve) && has(idea)) return '💡✅';
if (has(approve)) return '✅';
if (has(fix)) return '🛠️✅';
if (has(wait)) return '⏳';
if (has(idea)) return '💡';
if (has(think)) return '🤔';
// Default: acknowledge + think
return '🤔';
}
function update() {
let dx = 0, dy = 0;
if (keys.ArrowUp) dy -= player.speed;
if (keys.ArrowDown) dy += player.speed;
if (keys.ArrowLeft) dx -= player.speed;
if (keys.ArrowRight) dx += player.speed;
moveEntity(player, dx, dy);
const dist = Math.hypot(player.x - engineer.x, player.y - engineer.y);
const wasNear = nearEngineer;
nearEngineer = dist < 42;
if (nearEngineer && !wasNear) {
activeNpcLabel.textContent = '当前角色:工程师';
dialogue.textContent = '靠近了工程师。输入多个表情后发送。';
emojiInput.focus();
}
if (!nearEngineer && wasNear) {
activeNpcLabel.textContent = '当前未锁定角色';
dialogue.textContent = '靠近工程师开始对话。';
}
}
function drawTile(x, y, tile) {
const px = x * tileSize;
const py = y * tileSize;
if (tile === 'G') {
ctx.fillStyle = '#3f9b4f'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#4fbf61'; ctx.fillRect(px + 4, py + 6, 4, 4); ctx.fillRect(px + 18, py + 18, 4, 4);
}
if (tile === 'W') {
ctx.fillStyle = '#1f2937'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#374151'; ctx.fillRect(px + 4, py + 4, 10, 10); ctx.fillRect(px + 18, py + 16, 8, 8);
}
if (tile === 'T') {
ctx.fillStyle = '#2f6f35'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#14532d'; ctx.fillRect(px + 6, py + 4, 20, 18);
ctx.fillStyle = '#6b4f2a'; ctx.fillRect(px + 13, py + 20, 6, 10);
}
if (tile === 'H') {
ctx.fillStyle = '#3f9b4f'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#d97706'; ctx.fillRect(px + 4, py + 10, 24, 18);
ctx.fillStyle = '#92400e'; ctx.fillRect(px + 10, py + 18, 8, 10);
ctx.fillStyle = '#fef3c7'; ctx.fillRect(px + 8, py + 14, 6, 6);
}
if (tile === 'P') {
ctx.fillStyle = '#d1b48c'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#b08968'; ctx.fillRect(px + 10, py, 12, tileSize);
}
if (tile === 'F') {
ctx.fillStyle = '#4ade80'; ctx.fillRect(px, py, tileSize, tileSize);
ctx.fillStyle = '#2563eb'; ctx.fillRect(px + 8, py + 8, 16, 16);
ctx.fillStyle = '#93c5fd'; ctx.fillRect(px + 12, py + 12, 8, 8);
}
}
function drawCharacter(x, y, color, headColor = '#fde68a') {
ctx.fillStyle = headColor; ctx.fillRect(x + 6, y, 10, 8);
ctx.fillStyle = color; ctx.fillRect(x + 4, y + 8, 14, 12);
ctx.fillStyle = '#111827'; ctx.fillRect(x + 5, y + 20, 4, 6); ctx.fillRect(x + 13, y + 20, 4, 6);
}
function drawSleepingCharacter(x, y, color) {
// Draw a simple "lying down" sprite
ctx.fillStyle = '#fde68a';
ctx.fillRect(x, y + 10, 18, 8); // head
ctx.fillStyle = color;
ctx.fillRect(x + 18, y + 8, 18, 12); // body
ctx.fillStyle = '#111827';
ctx.fillRect(x + 26, y + 18, 4, 4);
ctx.fillRect(x + 34, y + 18, 4, 4);
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let y = 0; y < mapRows; y++) for (let x = 0; x < mapCols; x++) drawTile(x, y, map[y][x]);
// engineer
if (engineerMode === 'offline') {
drawSleepingCharacter(engineer.x, engineer.y, engineer.color);
ctx.fillStyle = '#000'; ctx.font = '12px monospace'; ctx.fillText('工程师😴', engineer.x - 8, engineer.y - 6);
} else {
drawCharacter(engineer.x, engineer.y, engineer.color);
ctx.fillStyle = '#000'; ctx.font = '12px monospace'; ctx.fillText('工程师', engineer.x - 8, engineer.y - 6);
}
// other players
for (const p of remotePlayers) {
if (!p || p.playerId === playerId) continue;
drawCharacter(p.x, p.y, p.color || '#60a5fa', '#bfdbfe');
ctx.fillStyle = '#000'; ctx.font = '12px monospace';
ctx.fillText(p.name || '玩家', p.x - 8, p.y - 6);
}
// local player
drawCharacter(player.x, player.y, player.color, '#fecaca');
ctx.fillStyle = '#000'; ctx.font = '12px monospace'; ctx.fillText('你', player.x + 4, player.y - 6);
}
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!nearEngineer) {
appendChat('system', '系统', '先靠近工程师');
return;
}
const raw = emojiInput.value;
const emojis = extractEmojis(raw);
if (emojis.length === 0) {
appendChat('system', '系统', '只能发送表情包');
return;
}
const outgoing = emojis.join('');
emojiInput.value = '';
appendChat('player', '你', outgoing);
// Offline: never call bot/back-end thinking, reply locally.
if (engineerMode === 'offline') {
appendChat('npc', '工程师', '😴');
dialogue.textContent = '工程师离线。';
return;
}
// Online: ask engineer (Syber relay) to infer meaning and reply with emoji-only.
try {
const prompt = `玩家发送的表情序列是:${outgoing}\n请你理解其含义,并只用 1-3 个表情包进行回应。要求:只输出表情,不要输出任何文字、标点或空格。`;
const response = await apiFetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ npc: 'engineer', text: prompt, source: 'emoji-only', playerId: 'Vincent' })
});
const data = await response.json();
if (!data?.ok) throw new Error(data?.error || 'chat failed');
const replyEmojis = extractEmojis(String(data.reply || ''));
const reply = replyEmojis.length ? replyEmojis.join('') : engineerReply(emojis); // last-resort fallback
appendChat('npc', '工程师', reply);
dialogue.textContent = '表情包已发送。';
} catch {
// Fallback: local heuristic
const reply = engineerReply(emojis);
appendChat('npc', '工程师', reply);
dialogue.textContent = '表情包已发送(fallback)。';
}
});
window.addEventListener('keydown', (e) => {
keys[e.key] = true;
keys[e.key.toLowerCase?.() || e.key] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.key] = false;
keys[e.key.toLowerCase?.() || e.key] = false;
});
// Layout mode toggle: AUTO → MOBILE → DESKTOP
const layoutToggle = document.getElementById('layoutToggle');
const layoutModes = ['auto', 'mobile', 'desktop'];
const layoutModeLabel = { auto: '自适应', mobile: '手机', desktop: '桌面' };
let layoutMode = localStorage.getItem('layoutMode') || 'auto';
function applyLayoutMode() {
document.body.classList.remove('layout-mobile', 'layout-desktop');
if (layoutMode === 'mobile') document.body.classList.add('layout-mobile');
if (layoutMode === 'desktop') document.body.classList.add('layout-desktop');
if (layoutToggle) layoutToggle.textContent = layoutModeLabel[layoutMode] || '自适应';
}
if (layoutToggle) {
layoutToggle.addEventListener('click', () => {
const idx = layoutModes.indexOf(layoutMode);
layoutMode = layoutModes[(idx + 1) % layoutModes.length];
localStorage.setItem('layoutMode', layoutMode);
applyLayoutMode();
});
}
applyLayoutMode();
// Mobile D-pad (touch)
const dpad = document.getElementById('dpad');
if (dpad) {
const press = (key, down) => {
keys[key] = down;
keys[key.toLowerCase?.() || key] = down;
};
dpad.querySelectorAll('[data-key]').forEach((btn) => {
const key = btn.getAttribute('data-key');
const onDown = (e) => { e.preventDefault(); press(key, true); };
const onUp = (e) => { e.preventDefault(); press(key, false); };
btn.addEventListener('pointerdown', onDown);
btn.addEventListener('pointerup', onUp);
btn.addEventListener('pointercancel', onUp);
btn.addEventListener('pointerleave', onUp);
});
}
async function joinRoom() {
try {
const res = await apiFetch('/api/room/join', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room, name: 'Vincent' })
});
const data = await res.json();
if (data?.ok) {
playerId = data.playerId;
isOwner = Boolean(data.isOwner);
// spawn player near server-provided position
if (typeof data.x === 'number') player.x = data.x;
if (typeof data.y === 'number') player.y = data.y;
if (typeof data.color === 'string') player.color = data.color;
// Only owner can control engineer online/offline
if (!isOwner) {
if (engineerStatusSwitchWrap) engineerStatusSwitchWrap.style.display = 'none';
}
}
} catch {
// ignore
}
}
async function pollPlayers() {
if (!playerId) return;
try {
const res = await apiFetch(`/api/room/players?room=${encodeURIComponent(room)}`);
const data = await res.json();
if (data?.ok && Array.isArray(data.players)) {
remotePlayers = data.players;
}
} catch {
// ignore
}
}
async function pollEngineerStatus() {
try {
const res = await apiFetch(`/api/engineer/status?room=${encodeURIComponent(room)}`);
const data = await res.json();
if (data?.ok && (data.status === 'online' || data.status === 'offline')) {
engineerMode = data.status;
if (engineerStatusIndicator) engineerStatusIndicator.textContent = engineerMode;
if (statusOnlineBtn && statusOfflineBtn) {
statusOnlineBtn.classList.toggle('active', engineerMode === 'online');
statusOfflineBtn.classList.toggle('active', engineerMode === 'offline');
}
}
} catch {
// ignore
}
}
async function setEngineerStatus(status) {
if (!isOwner) return;
try {
const res = await apiFetch('/api/engineer/status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room, playerId, status })
});
const data = await res.json();
if (data?.ok) {
engineerMode = data.status;
if (engineerStatusIndicator) engineerStatusIndicator.textContent = engineerMode;
await pollEngineerStatus();
}
} catch {
// ignore
}
}
async function postState() {
if (!playerId) return;
try {
await apiFetch('/api/room/state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room, playerId, x: player.x, y: player.y })
});
} catch {
// ignore
}
}
function loop() {
update();
// send state at ~2Hz
const t = performance.now();
if (t - lastStatePostAt > 500) {
lastStatePostAt = t;
postState();
}
render();
requestAnimationFrame(loop);
}
activeNpcLabel.textContent = '当前未锁定角色';
dialogue.textContent = '靠近工程师开始对话。';
renderRoomGrid();
renderJoinInfo();
joinRoom().then(() => {
pollPlayers();
pollEngineerStatus();
postState();
setInterval(pollPlayers, 1000);
setInterval(pollEngineerStatus, 1000);
// Heartbeat: keep presence even if rAF is throttled (mobile background)
setInterval(postState, 2000);
if (engineerStatusSwitch) {
engineerStatusSwitch.addEventListener('change', () => {
setEngineerStatus(engineerStatusSwitch.checked ? 'offline' : 'online');
});
}
});
loop();