Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
686 lines (615 loc) · 22.3 KB
/
Copy pathscript.js
File metadata and controls
686 lines (615 loc) · 22.3 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
let isLoginMode = true;
let isAutoLoggingIn = false;
const loginModal = document.getElementById('loginModal');
const continueModal = document.getElementById('continueModal');
const modeModal = document.getElementById('modeModal');
const customModal = document.getElementById('customModal');
const title = document.getElementById('modalTitle');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const messageEl = document.getElementById('message');
const submitBtn = document.getElementById('submitBtn');
const switchText = document.getElementById('switchText');
// ==================== 登录模块 ====================
window.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (token) {
isAutoLoggingIn = true;
try {
const response = await fetch('/api/check', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
});
const data = await response.json();
if (data.loggedIn) {
// 检查是否有存档
await checkAndHandleSave();
loginModal.classList.remove('active');
return;
} else {
localStorage.removeItem('token');
localStorage.removeItem('username');
}
} catch (e) {
localStorage.removeItem('token');
localStorage.removeItem('username');
}
isAutoLoggingIn = false;
}
loginModal.classList.add('active');
});
function closeLoginModal() {
loginModal.classList.remove('active');
}
function toggleMode() {
isLoginMode = !isLoginMode;
title.textContent = isLoginMode ? '登录' : '注册';
submitBtn.textContent = isLoginMode ? '登录' : '注册';
switchText.textContent = isLoginMode ? '没有账号?注册' : '已有账号?登录';
messageEl.textContent = '';
messageEl.className = 'message';
}
async function handleSubmit() {
const username = usernameInput.value.trim();
const password = passwordInput.value.trim();
if (!username || !password) {
messageEl.textContent = '请输入用户名和密码';
messageEl.className = 'message error';
return;
}
const url = isLoginMode ? '/api/login' : '/api/register';
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.success) {
messageEl.textContent = data.message;
messageEl.className = 'message success';
localStorage.setItem('token', data.token);
localStorage.setItem('username', data.username);
setTimeout(async () => {
closeLoginModal();
// 检查是否有存档
await checkAndHandleSave();
}, 500);
} else {
messageEl.textContent = data.message;
messageEl.className = 'message error';
}
} catch (error) {
messageEl.textContent = '网络错误';
messageEl.className = 'message error';
}
}
document.getElementById('switchBtn').addEventListener('click', toggleMode);
document.getElementById('submitBtn').addEventListener('click', handleSubmit);
// ==================== 存档检测与继续游戏 ====================
const MODE_CN = { 'Random': '随机模拟', 'History': '历史模拟', 'Custom': '自定义模拟' };
let _currentSaveFilter = 'all'; // 'all' | 'active' | 'completed',记录当前存档列表的过滤模式
/**
* 检查是否有存档,有则弹出存档列表
*/
async function checkAndHandleSave() {
const token = localStorage.getItem('token');
if (!token) return;
try {
const response = await fetch('/api/game/has-save', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await response.json();
if (data.hasSave) {
// 只对进行中的存档弹窗提示,已结束的存档不打扰
const activeSaves = data.saves.filter(s => !s.isCompleted);
if (activeSaves.length > 0) {
_currentSaveFilter = 'active';
// 同步激活进行中按钮
document.querySelectorAll('.save-filter-btn').forEach(b => {
b.classList.remove('active');
if (b.dataset.filter === 'active') b.classList.add('active');
});
renderSaveList(activeSaves);
continueModal.classList.add('active');
}
}
} catch (e) {
console.error('检查存档失败:', e);
}
}
/**
* 渲染存档列表
*/
function renderSaveList(saves) {
const list = document.getElementById('saveList');
list.innerHTML = '';
// 根据当前过滤模式过滤
let filteredSaves = saves;
if (_currentSaveFilter === 'active') {
filteredSaves = saves.filter(s => !s.isCompleted);
} else if (_currentSaveFilter === 'completed') {
filteredSaves = saves.filter(s => s.isCompleted);
}
if (filteredSaves.length === 0) {
const emptyMsg = document.createElement('div');
emptyMsg.className = 'save-empty';
emptyMsg.textContent = _currentSaveFilter === 'all' ? '暂无存档'
: _currentSaveFilter === 'active' ? '没有进行中的存档'
: '没有已结束的存档';
list.appendChild(emptyMsg);
return;
}
filteredSaves.forEach(save => {
const item = document.createElement('div');
item.className = 'save-item';
const modeText = MODE_CN[save.gameMode] || save.gameMode || '未知';
const statusText = save.isCompleted ? '已结束' : '进行中';
const created = new Date(save.createdAt).toLocaleString('zh-CN');
const updated = new Date(save.updatedAt).toLocaleString('zh-CN');
// 已结束存档显示结束报告摘要,不显示"继续"按钮
let actionsHtml;
if (save.isCompleted) {
const er = save.endingReport || {};
const scoreStr = er.score != null ? `${er.score} ${er.scoreLabel || ''}` : '--';
const aliveStr = er.alive === true ? '存活' : (er.alive === false ? '阵亡' : '');
actionsHtml = `
<div class="save-ending-info">
<span class="save-score">${scoreStr}</span>
<span class="save-alive">${aliveStr}</span>
</div>
<div class="save-item-actions">
<button class="btn btn-outline btn-report" data-save-id="${save.saveId}">查看报告</button>
<button class="btn btn-outline btn-delete" data-save-id="${save.saveId}">删除</button>
</div>
`;
} else {
actionsHtml = `
<div class="save-item-actions">
<button class="btn btn-load" data-save-id="${save.saveId}">继续</button>
<button class="btn btn-outline btn-delete" data-save-id="${save.saveId}">删除</button>
</div>
`;
}
item.innerHTML = `
<div class="save-item-info">
<span class="save-mode">${modeText}</span>
<span class="save-round">第 ${save.round} 回合</span>
<span class="save-status">${statusText}</span>
</div>
<div class="save-item-time">创建: ${created} | 更新: ${updated}</div>
${actionsHtml}
`;
list.appendChild(item);
});
// 绑定继续按钮
list.querySelectorAll('.btn-load').forEach(btn => {
btn.addEventListener('click', () => loadSave(btn.dataset.saveId));
});
// 绑定查看报告按钮
list.querySelectorAll('.btn-report').forEach(btn => {
btn.addEventListener('click', () => viewSaveReport(btn.dataset.saveId));
});
// 绑定删除按钮
list.querySelectorAll('.btn-delete').forEach(btn => {
btn.addEventListener('click', () => deleteSave(btn.dataset.saveId));
});
}
/**
* 加载指定存档
*/
async function loadSave(saveId) {
const token = localStorage.getItem('token');
try {
const response = await fetch('/api/game/load', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ saveId })
});
const data = await response.json();
if (data.success) {
continueModal.classList.remove('active');
window.location.href = 'game.html';
}
} catch (e) {
console.error('加载存档失败:', e);
}
}
/**
* 删除指定存档
*/
async function deleteSave(saveId) {
if (!confirm('确定删除这个存档吗?此操作不可撤销。')) return;
const token = localStorage.getItem('token');
try {
await fetch('/api/game/delete-save', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ saveId })
});
// 刷新存档列表(保持当前过滤模式)
const response = await fetch('/api/game/has-save', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await response.json();
if (data.hasSave) {
const saves = _currentSaveFilter === 'active'
? data.saves.filter(s => !s.isCompleted)
: _currentSaveFilter === 'completed'
? data.saves.filter(s => s.isCompleted)
: data.saves;
if (saves.length > 0) {
renderSaveList(saves);
} else {
continueModal.classList.remove('active');
}
} else {
continueModal.classList.remove('active');
}
} catch (e) {
console.error('删除存档失败:', e);
}
}
/**
* 取消 - 关闭弹窗,回主菜单
*/
function cancelContinue() {
continueModal.classList.remove('active');
}
document.getElementById('cancelContinueBtn').addEventListener('click', cancelContinue);
/**
* 重新获取存档列表并应用当前过滤
*/
async function refreshSaveList() {
const token = localStorage.getItem('token');
if (!token) return;
try {
const response = await fetch('/api/game/has-save', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await response.json();
if (data.hasSave) {
renderSaveList(data.saves);
} else {
renderSaveList([]);
}
} catch (e) {
console.error('获取存档列表失败:', e);
}
}
/**
* 查看已结束存档的完整生存报告
*/
async function viewSaveReport(saveId) {
const token = localStorage.getItem('token');
if (!token) return;
try {
const response = await fetch('/api/game/load', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ saveId })
});
const data = await response.json();
if (!data.success) {
alert('加载存档失败');
return;
}
const state = data.state;
const er = state.endingReport || {};
// 填充标题
const isAlive = er.alive === true;
document.getElementById('reportTitle').textContent = isAlive ? '生存报告' : '游戏结束';
document.getElementById('reportTitle').style.color = isAlive ? '#4caf50' : '#f44336';
// 填充评分
const score = er.score || '-';
document.getElementById('reportScore').textContent = score;
const scoreColors = { S: '#ffd700', A: '#4caf50', B: '#2196f3', C: '#ff9800', D: '#f44336' };
document.getElementById('reportScore').style.color = scoreColors[score] || '#fff';
// 填充叙事
document.getElementById('reportNarrative').textContent = er.narrative || generateReportNarrative(state, isAlive);
// 地震参数
document.getElementById('reportParams').innerHTML = `
<div class="ending-param"><span class="ep-label">震级</span><span class="ep-value">M ${state.magnitude || '-'}</span></div>
<div class="ending-param"><span class="ep-label">烈度</span><span class="ep-value">${state.earthquakeIntensity || '-'} 度</span></div>
<div class="ending-param"><span class="ep-label">深度</span><span class="ep-value">${state.depth || '-'} km</span></div>
<div class="ending-param"><span class="ep-label">震中距</span><span class="ep-value">${state.distance || '-'} km</span></div>
<div class="ending-param"><span class="ep-label">持时</span><span class="ep-value">${state.earthquakeDuration || '-'} s</span></div>
`;
// 最终状态
const stats = state.stats || {};
document.getElementById('reportStats').innerHTML = `
<div class="ending-stat"><span class="es-label">回合</span><span class="es-value">${state.round}</span></div>
<div class="ending-stat"><span class="es-label">存活时间</span><span class="es-value">${state.nowTime || '-'}</span></div>
<div class="ending-stat"><span class="es-label">体力</span><span class="es-value">${stats.stamina ?? '-'}</span></div>
<div class="ending-stat"><span class="es-label">恐慌</span><span class="es-value">${stats.panic ?? '-'}</span></div>
<div class="ending-stat"><span class="es-label">健康</span><span class="es-value">${stats.health ?? '-'}</span></div>
<div class="ending-stat"><span class="es-label">生命</span><span class="es-value">${stats.life ?? '-'}</span></div>
`;
// 成就
const achievements = stats.achievements || [];
const achSection = document.getElementById('reportAchievementsSection');
const achContainer = document.getElementById('reportAchievements');
if (achievements.length > 0) {
achSection.style.display = 'block';
achContainer.innerHTML = achievements.map(aid =>
`<div class="ending-achievement">🏆 成就 #${aid}</div>`
).join('');
} else {
achSection.style.display = 'none';
}
// 事件回顾
const history = state.eventHistory || [];
const timelineEl = document.getElementById('reportTimeline');
if (history.length > 0) {
timelineEl.innerHTML = history.map((evId, i) => {
const id = typeof evId === 'object' ? evId.id : evId;
return `<div class="ending-timeline-item"><span class="eti-id">#${id}</span> ${typeof evId === 'object' ? evId.title : '事件'}</div>`;
}).join('');
} else {
timelineEl.innerHTML = '<div class="ending-empty">暂无记录</div>';
}
// 显示覆盖层
document.getElementById('reportOverlay').classList.add('active');
document.getElementById('reportOverlay').scrollTop = 0;
} catch (e) {
console.error('加载报告失败:', e);
alert('加载报告失败');
}
}
/**
* 简易叙事生成(当 endingReport.narrative 不存在时的回退)
*/
function generateReportNarrative(state, alive) {
const intensity = state.earthquakeIntensity || 0;
const round = state.round || 1;
const days = Math.floor((state.elapsedMinutes || 0) / (24 * 60)) + 1;
const mag = state.magnitude || 0;
const distance = state.distance || 0;
if (alive) {
return `你在 M${mag} 级地震中存活了 ${days} 天,经历了 ${round} 次生死抉择。烈度 ${intensity} 度的震动和 ${distance} 公里的震中距离没有击垮你。`;
}
return `${days} 天后,你的生命在废墟中画上了句号。你经历了 ${round} 次抉择,在 M${mag} 级地震中坚持了 ${days} 天。`;
}
// ==================== 存档列表过滤按钮 ====================
// 过滤按钮事件委托
document.addEventListener('click', (e) => {
const btn = e.target.closest('.save-filter-btn');
if (!btn || !btn.closest('#continueModal')) return;
const filter = btn.dataset.filter;
if (filter === _currentSaveFilter) return;
_currentSaveFilter = filter;
document.querySelectorAll('.save-filter-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
refreshSaveList();
});
// ==================== 报告覆盖层 ====================
// 关闭报告
document.getElementById('reportCloseBtn').addEventListener('click', () => {
document.getElementById('reportOverlay').classList.remove('active');
});
// 点击背景关闭报告
document.getElementById('reportOverlay').addEventListener('click', (e) => {
if (e.target === document.getElementById('reportOverlay')) {
document.getElementById('reportOverlay').classList.remove('active');
}
});
// ==================== 模式选择模块 ====================
function openModeModal() {
modeModal.classList.add('active');
}
function closeModeModal() {
modeModal.classList.remove('active');
}
async function handleModeSelect(mode) {
// 自定义模式:先弹出设置弹窗
if (mode === 'custom') {
closeModeModal();
customModal.classList.add('active');
return;
}
const token = localStorage.getItem('token');
const modeMap = {
'random': 'Random',
'history': 'History',
'custom': 'Custom'
};
try {
await fetch('/api/game/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ gameMode: modeMap[mode] })
});
} catch (e) {
console.error('创建游戏失败:', e);
}
localStorage.setItem('gameMode', mode);
window.location.href = 'game.html';
}
// 新游戏按钮
document.getElementById('newGameBtn').addEventListener('click', () => {
const token = localStorage.getItem('token');
if (token) {
openModeModal();
} else {
loginModal.classList.add('active');
}
});
// 继续游戏按钮
document.getElementById('continueBtn').addEventListener('click', async () => {
const token = localStorage.getItem('token');
if (token) {
// 拉取存档列表
try {
const response = await fetch('/api/game/has-save', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await response.json();
if (data.hasSave) {
_currentSaveFilter = 'all';
// 同步激活全部按钮
document.querySelectorAll('.save-filter-btn').forEach(b => {
b.classList.remove('active');
if (b.dataset.filter === 'all') b.classList.add('active');
});
renderSaveList(data.saves);
continueModal.classList.add('active');
} else {
alert('暂无存档');
}
} catch (e) {
console.error('查询存档失败:', e);
}
} else {
loginModal.classList.add('active');
}
});
// 成就按钮
document.getElementById('achievementBtn').addEventListener('click', () => {
window.location.href = 'achievement.html';
});
document.getElementById('optionBtn').addEventListener('click', () => {
window.location.href = 'option.html';
});
// 模式选择按钮
document.querySelectorAll('.mode-btn').forEach(btn => {
btn.addEventListener('click', () => {
const mode = btn.getAttribute('data-mode');
handleModeSelect(mode);
});
});
// 返回按钮
document.getElementById('backToMenu').addEventListener('click', () => {
closeModeModal();
});
// ==================== 自定义模拟模块 ====================
// 滑块值实时显示
const customRanges = [
{ input: 'magInput', val: 'magVal', suffix: '' },
{ input: 'depthInput', val: 'depthVal', suffix: ' km' },
{ input: 'distInput', val: 'distVal', suffix: ' km' },
{ input: 'vs30Input', val: 'vs30Val', suffix: ' m/s' },
{ input: 'dopplerInput', val: 'dopplerVal', suffix: '', fixed: 2 },
{ input: 'bldInput', val: 'bldVal', suffix: ' 层' },
{ input: 'floorInput', val: 'floorVal', suffix: ' 层' }
];
customRanges.forEach(r => {
const input = document.getElementById(r.input);
const valEl = document.getElementById(r.val);
if (!input || !valEl) return;
input.addEventListener('input', () => {
let v = parseFloat(input.value);
if (r.fixed !== undefined) v = v.toFixed(r.fixed);
valEl.textContent = v + r.suffix;
});
});
// 建筑高度联动楼层上限
const bldInput = document.getElementById('bldInput');
const floorInput = document.getElementById('floorInput');
bldInput.addEventListener('input', () => {
const bldH = parseInt(bldInput.value);
floorInput.max = bldH;
if (parseInt(floorInput.value) > bldH) {
floorInput.value = bldH;
document.getElementById('floorVal').textContent = bldH + ' 层';
}
});
// 取消按钮 - 返回模式选择
document.getElementById('cancelCustomBtn').addEventListener('click', () => {
customModal.classList.remove('active');
openModeModal();
});
// 开始自定义游戏
document.getElementById('startCustomBtn').addEventListener('click', async () => {
const token = localStorage.getItem('token');
if (!token) {
customModal.classList.remove('active');
loginModal.classList.add('active');
return;
}
// 收集参数("random" 值不传,让服务端随机生成)
const custom = {};
const mag = parseFloat(document.getElementById('magInput').value);
const depth = parseFloat(document.getElementById('depthInput').value);
const dist = parseFloat(document.getElementById('distInput').value);
const vs30 = parseFloat(document.getElementById('vs30Input').value);
const doppler = parseFloat(document.getElementById('dopplerInput').value);
const bldH = parseInt(document.getElementById('bldInput').value);
const floor = parseInt(document.getElementById('floorInput').value);
custom.magnitude = mag;
custom.depth = depth;
custom.distance = dist;
custom.vs30 = vs30;
custom.doppler = doppler;
custom.buildingHeight = bldH;
custom.playerHeight = floor;
// select 字段:非 random 才传
const selects = {
fault: 'faultSelect',
ifbigs: 'ifbigsSelect',
landform: 'landformSelect',
weather: 'weatherSelect',
career: 'careerSelect',
hobby: 'hobbySelect',
structure: 'structSelect',
location: 'locSelect'
};
for (const [key, id] of Object.entries(selects)) {
const v = document.getElementById(id).value;
if (v !== 'random') {
// 数值类字段转 Number
if (['ifbigs', 'career', 'hobby', 'structure', 'location'].includes(key)) {
custom[key] = Number(v);
} else {
custom[key] = v;
}
}
}
// 禁用按钮防重复提交
const startBtn = document.getElementById('startCustomBtn');
startBtn.textContent = '创建中...';
startBtn.disabled = true;
try {
const response = await fetch('/api/game/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify({ gameMode: 'Custom', custom })
});
const data = await response.json();
if (!response.ok) {
alert(data.error || '创建游戏失败');
startBtn.textContent = '开始游戏';
startBtn.disabled = false;
return;
}
localStorage.setItem('gameMode', 'custom');
window.location.href = 'game.html';
} catch (e) {
console.error('创建自定义游戏失败:', e);
alert('网络错误,请重试');
startBtn.textContent = '开始游戏';
startBtn.disabled = false;
}
});