-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathrender.js
More file actions
1959 lines (1750 loc) · 89.3 KB
/
render.js
File metadata and controls
1959 lines (1750 loc) · 89.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
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
render.js: UI 渲染逻辑
包含所有与 DOM 操作相关的函数,如 `renderAll`、模态框显示、UI 交互等。
*/
/* =========== 晋级状态检查函数 =========== */
/**
* 获取学生的晋级状态信息
* @param {Student} student - 学生对象
* @returns {Object} - { hasQualification: boolean, nextContest: string, html: string }
*/
function getStudentQualificationStatus(student) {
const result = {
hasQualification: false,
nextContest: '',
html: ''
};
if (!student || !game || !game.qualification) {
return result;
}
try {
// 确定当前是第几个赛季(上半年还是下半年)
const currentHalf = (game.week > (typeof WEEKS_PER_HALF !== 'undefined' ? WEEKS_PER_HALF : 16)) ? 1 : 0;
// 获取所有比赛,按周数排序
const sortedComps = (typeof competitions !== 'undefined' && Array.isArray(competitions))
? competitions.slice().sort((a, b) => a.week - b.week)
: [];
// 找到下一场未进行的比赛
let nextComp = null;
for (let comp of sortedComps) {
if (comp.week > game.week) {
// 检查这场比赛是否已经完成
const key = `${currentHalf}_${comp.name}_${comp.week}`;
if (!game.completedCompetitions || !game.completedCompetitions.has(key)) {
nextComp = comp;
break;
}
}
}
if (!nextComp) {
return result; // 没有下一场比赛
}
result.nextContest = nextComp.name;
// 检查学生是否已经晋级下一场比赛
// CSP-S1 不需要晋级资格,所有人都可以参加
if (nextComp.name === 'CSP-S1') {
result.hasQualification = true;
result.html = '<span class="qualification-badge qualified" title="所有学生均可参加CSP-S1">✓</span>';
return result;
}
// 检查晋级链:CSP-S1 -> CSP-S2 -> NOIP -> 省选 -> NOI
const qualChain = {
'CSP-S2': 'CSP-S1',
'NOIP': 'CSP-S2',
'省选': 'NOIP',
'NOI': '省选'
};
const requiredComp = qualChain[nextComp.name];
if (requiredComp) {
// 检查学生是否在qualification集合中
const qualSet = game.qualification[currentHalf][requiredComp];
if (qualSet && (qualSet.has(student.name) || qualSet.has(student))) {
result.hasQualification = true;
result.html = `<span class="qualification-badge qualified" title="已晋级${nextComp.name}">✓ ${nextComp.name}</span>`;
} else {
result.hasQualification = false;
result.html = `<span class="qualification-badge not-qualified" title="未晋级${nextComp.name},需要先通过${requiredComp}">✗ ${nextComp.name}</span>`;
}
}
} catch (e) {
console.error('获取学生晋级状态失败:', e);
}
return result;
}
// 暴露到全局作用域,供其他模块使用
window.getStudentQualificationStatus = getStudentQualificationStatus;
/* 每日/每次渲染随机一言 */
const QUOTES = [
"想想你的对手正在干什么",
"下课必须放松吗?",
"没有天赋异禀的幸运,唯有水滴石穿的坚持",
"没有一步登天的幻想,唯有日积月累的付出",
"竞赛生没有特权你明白吗?",
"自律者出众,懒惰者出局",
"重质量,数量次之"
];
/* =========== UI 辅助 =========== */
const $ = id => document.getElementById(id);
function log(msg){
const el = $('log');
const wk = currWeek();
const text = `[周${wk}] ${msg}`;
if(el){ const p = document.createElement('div'); p.innerText = text; el.prepend(p); }
else { console.log(text); }
}
function renderDifficultyTag(diff){
const d = Number(diff) || 0;
let label = '';
let cls = '';
if(d <= 20){ label = '入门'; cls = 'diff-red'; }
else if(d <= 50){ label = '普及-'; cls = 'diff-orange'; }
else if(d <= 86){ label = '普及/提高-'; cls = 'diff-yellow'; }
else if(d <= 103){ label = '普及+/提高'; cls = 'diff-green'; }
else if(d <=120){ label = '提高+/省选-'; cls = 'diff-blue'; }
else if(d <= 150){ label = '省选/NOI-'; cls = 'diff-purple'; }
else { label = 'NOI+/CTSC'; cls = 'diff-black'; }
const legacy = (d <= 24) ? 'diff-beginner' : (d <= 34) ? 'diff-popular-low' : (d <= 44) ? 'diff-popular-high' : (d <= 64) ? 'diff-advanced-low' : (d <= 79) ? 'diff-provincial' : 'diff-noi';
return `<span class="diff-tag ${cls} ${legacy}" title="难度: ${d}">${label}</span>`;
}
function safeRenderAll(){
try{
if(typeof window.renderAll === 'function' && document.getElementById('header-week')){
window.renderAll();
}
}catch(e){ console.error('safeRenderAll error', e); }
}
function renderEventCards(){
const container = $('event-cards-container');
if(!container) return;
// 清空并重建结构,释放旧的DOM引用
const oldWrapper = document.getElementById('event-cards-wrapper');
if(oldWrapper){
// 移除滚动事件监听器
const clonedWrapper = oldWrapper.cloneNode(false);
if(oldWrapper.parentNode){
oldWrapper.parentNode.replaceChild(clonedWrapper, oldWrapper);
}
}
container.innerHTML = '';
if(recentEvents.length === 0){
container.classList.remove('has-overflow');
return;
}
// 创建滚动包装器
let wrapper = document.createElement('div');
wrapper.id = 'event-cards-wrapper';
container.appendChild(wrapper);
const nowWeek = currWeek();
let shown = 0;
for(let i = 0; i < recentEvents.length; i++){
const ev = recentEvents[i];
if(ev.week && (nowWeek - ev.week) > 2) continue;
if(ev._isHandled) continue;
const card = document.createElement('div');
let cardClass = 'event-card event-active';
if (ev.options && ev.options.length > 0) {
cardClass += ' event-required';
}
card.className = cardClass;
const titleHtml = `<div class="card-title">${ev.name || '突发事件'}` +
`${(ev.options && ev.options.length > 0) ? '<span class="required-tag">未选择</span>' : ''}` +
`</div>`;
const descText = ev.description || '';
// 基本 HTML 转义(并移除换行/br),确保事件描述为单行显示,避免占位符泄露
const esc = (s) => String(s||'').replace(/[&<>"']/g, function(ch){return ({'&':'&','<':'<','>':'>','"':'"',"'":"'"})[ch];});
const escNoBr = (s) => {
if(typeof s !== 'string') s = String(s||'');
// 将 <br> 和换行符替换为空格,再做 HTML 转义
const normalized = s.replace(/<br\s*\/?/gi, ' ').replace(/\r?\n/g, ' ');
return normalized.replace(/[&<>"']/g, function(ch){return ({'&':'&','<':'<','>':'>','"':'"',"'":"'"})[ch];});
};
// 先把描述标准化为无换行形式,再基于该结果生成 shortDesc(避免截断标签或占位符)
const normalizedDesc = (typeof descText === 'string') ? descText.replace(/<br\s*\/?/gi, ' ').replace(/\r?\n/g, ' ') : String(descText || '');
const shortDesc = (normalizedDesc.length > 120) ? normalizedDesc.slice(0, 118) + '…' : normalizedDesc;
let cardHTML = '';
cardHTML += titleHtml;
// 使用 escNoBr,所有换行/BR 将被转为空格,事件描述呈单行显示
cardHTML += `<div class="card-desc clamp" data-uid="${ev._uid}">${escNoBr(shortDesc)}</div>`;
cardHTML += `<div class="event-detail" data-uid="${ev._uid}" style="display:none">${escNoBr(descText)}</div>`;
if(descText && descText.length > 60){
cardHTML += `<button class="more-btn" data-action="toggle-detail" data-uid="${ev._uid}">更多</button>`;
}
if(ev.options && ev.options.length > 0){
cardHTML += '<div class="event-options" style="margin-top:10px; display:flex; gap:8px;">';
ev.options.forEach((opt, idx) => {
cardHTML += `<button class="btn event-choice-btn" data-event-uid="${ev._uid}" data-option-index="${idx}">${opt.label || `选项${idx+1}`}</button>`;
});
cardHTML += '</div>';
}
card.innerHTML = cardHTML;
wrapper.appendChild(card);
if(++shown >= 6) break;
}
// 检查是否有溢出内容
setTimeout(() => {
checkEventCardsOverflow();
}, 100);
}
// 检查事件卡片是否溢出并添加相应的视觉提示
function checkEventCardsOverflow() {
const container = $('event-cards-container');
const wrapper = $('event-cards-wrapper');
if(!container || !wrapper) return;
const hasOverflow = wrapper.scrollHeight > wrapper.clientHeight;
if(hasOverflow) {
container.classList.add('has-overflow');
// 仅添加类并监听滚动以控制渐变显示(不创建任何提示 DOM)
wrapper.addEventListener('scroll', function() {
const isAtBottom = wrapper.scrollHeight - wrapper.scrollTop <= wrapper.clientHeight + 10;
if(isAtBottom) {
container.classList.add('scrolled-to-bottom');
} else {
container.classList.remove('scrolled-to-bottom');
}
});
} else {
container.classList.remove('has-overflow');
container.classList.remove('scrolled-to-bottom');
}
}
// 使用单次初始化标志避免重复绑定
if(!window._eventCardsInitialized){
window._eventCardsInitialized = true;
window.addEventListener('load', () => {
const container = $('event-cards-container');
if (!container) return;
// 添加动画样式(仅一次)
(function(){
if(!document.getElementById('event-detail-animations')){
const s = document.createElement('style');
s.id = 'event-detail-animations';
s.textContent = `
@keyframes et-slide-in-right { from { opacity: 0; transform: translateX(24px); } to { opacity: 1; transform: translateX(0); } }
@keyframes et-slide-out-right { from { opacity: 1; transform: translateX(0); } to { opacity: 0; transform: translateX(24px); } }
.event-detail { display: none; }
.event-detail.visible { display: block; animation: et-slide-in-right 0.25s ease both; }
.event-detail.hiding { animation: et-slide-out-right 0.22s ease both; }
`;
document.head.appendChild(s);
}
})();
// 使用事件委托处理"更多"按钮点击
container.addEventListener('click', function(e){
const btn = e.target.closest('.more-btn');
if (!btn) return;
const uid = btn.dataset.uid ? parseInt(btn.dataset.uid, 10) : null;
if (!uid) return;
const detail = container.querySelector(`.event-detail[data-uid='${uid}']`);
const desc = container.querySelector(`.card-desc[data-uid='${uid}']`);
if (!detail || !desc) return;
if (detail.classList.contains('visible')){
detail.classList.remove('visible');
detail.classList.add('hiding');
desc.classList.add('clamp');
btn.innerText = '更多';
const onAnimEnd = function(ev){
detail.classList.remove('hiding');
detail.style.display = 'none';
detail.removeEventListener('animationend', onAnimEnd);
};
detail.addEventListener('animationend', onAnimEnd);
} else {
detail.style.display = 'block';
void detail.offsetWidth;
detail.classList.remove('hiding');
detail.classList.add('visible');
desc.classList.remove('clamp');
btn.innerText = '收起';
}
});
// 使用事件委托处理事件选择
container.addEventListener('click', handleEventChoice);
});
}
function showEventModal(evt){
const title = evt?.name || '事件';
const desc = evt?.description || evt?.text || '暂无描述';
const weekInfo = `[周${evt?.week || currWeek()}] `;
showModal(`<h3>${weekInfo}${title}</h3><div class="small" style="margin-top:6px">${desc}</div><div class="modal-actions"><button class="btn" onclick="closeModal()">关闭</button></div>`);
}
function showChoiceModal(evt){
const title = evt?.name || '选择事件';
const desc = evt?.description || '';
const options = evt?.options || [];
const eventId = `choice_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
pushEvent({
name: title,
description: desc,
week: evt?.week || currWeek(),
options: options,
eventId: eventId
});
}
function renderAll(){
if(!document.getElementById('header-week')) return;
// 清理旧的事件监听器标记
if(!window._renderAllCleanupDone){
window._renderAllCleanupDone = true;
}
$('header-week').innerText = `第 ${currWeek()} 周`;
$('header-province').innerText = `省份: ${game.province_name} (${game.province_type})`;
const headerBudgetEl = $('header-budget');
if(headerBudgetEl) headerBudgetEl.innerText = `经费: ¥${game.budget}`;
try{
if(headerBudgetEl){
if(Number(game.budget) < 20000){ headerBudgetEl.classList.add('low-funds'); }
else { headerBudgetEl.classList.remove('low-funds'); }
}
}catch(e){ /* ignore */ }
$('header-reputation').innerText = `声誉: ${game.reputation}`;
$('info-week').innerText = currWeek();
const infoWeekEl = $('info-week'); if(infoWeekEl) infoWeekEl.innerText = currWeek();
const tempText = game.temperature.toFixed(1) + "\u00b0C";
const weatherDesc = game.getWeatherDescription();
const infoTempEl = $('info-temp'); if(infoTempEl) infoTempEl.innerText = tempText;
const infoWeatherEl = $('info-weather'); if(infoWeatherEl) infoWeatherEl.innerText = weatherDesc;
const infoFutureEl = $('info-future-expense'); if(infoFutureEl) infoFutureEl.innerText = game.getFutureExpense();
const nextCompText = game.getNextCompetition();
const nextCompEl = $('next-comp'); if(nextCompEl) nextCompEl.innerText = nextCompText;
const headerNextSmall = $('header-next-comp-small'); if(headerNextSmall) headerNextSmall.innerText = nextCompText;
const headerWeatherText = $('header-weather-text'); if(headerWeatherText) headerWeatherText.innerText = weatherDesc;
const headerTempHeader = $('header-temp-header'); if(headerTempHeader) headerTempHeader.innerText = tempText;
const q = QUOTES[ Math.floor(Math.random() * QUOTES.length) ];
$('daily-quote').innerText = q;
let match = nextCompText.match(/还有(\d+)周/);
let weeksLeft = match ? parseInt(match[1],10) : null;
const panel = $('next-competition-panel');
if(weeksLeft !== null && weeksLeft <= 4){ panel.className = 'next-panel highlight'; }
else { panel.className = 'next-panel normal'; }
const scheduleComps = competitions.slice().sort((a, b) => a.week - b.week);
$('comp-schedule').innerText = scheduleComps.map(c => `${c.week}:${c.name}`).join(" | ");
// 显示学生的平均实际舒适度(包含 modifier 效果)
// 而不是仅显示全局舒适度,这样事件对舒适度的影响会被反映出来
const activeStudents = game.students.filter(s => s && s.active !== false);
let displayComfort = game.getComfort(); // 默认使用全局舒适度
if(activeStudents.length > 0){
// 计算学生的平均实际舒适度(考虑个体差异和modifier)
const avgStudentComfort = activeStudents.reduce((sum, s) => {
let personalComfort = game.getComfort();
// 应用天赋修正
if(s.talents && s.talents.has('天气敏感')){
const baseComfort = game.base_comfort;
const weatherEffect = personalComfort - baseComfort;
personalComfort = baseComfort + weatherEffect * 2;
personalComfort = Math.max(0, Math.min(100, personalComfort));
}
if(s.talents && s.talents.has('美食家')){
const canteenBonus = 3 * (game.facilities.canteen - 1);
personalComfort += canteenBonus;
personalComfort = Math.max(0, Math.min(100, personalComfort));
}
// 应用事件产生的临时修正值
if(typeof s.comfort_modifier === 'number'){
personalComfort += s.comfort_modifier;
personalComfort = Math.max(0, Math.min(100, personalComfort));
}
return sum + personalComfort;
}, 0) / activeStudents.length;
displayComfort = avgStudentComfort;
}
const comfortEl = $('comfort-val');
if(comfortEl) comfortEl.innerText = Math.floor(displayComfort);
$('fac-computer').innerText = game.facilities.computer;
$('fac-library').innerText = game.facilities.library;
$('fac-ac').innerText = game.facilities.ac;
$('fac-dorm').innerText = game.facilities.dorm;
$('fac-canteen').innerText = game.facilities.canteen;
$('fac-maint').innerText = game.facilities.getMaintenanceCost();
// 同步更新设施状态显示区域(只读)
const displayEls = {
'fac-computer-display': game.facilities.computer,
'fac-library-display': game.facilities.library,
'fac-ac-display': game.facilities.ac,
'fac-dorm-display': game.facilities.dorm,
'fac-canteen-display': game.facilities.canteen,
'fac-maint-display': game.facilities.getMaintenanceCost()
};
for(let id in displayEls) {
const el = $(id);
if(el) el.innerText = displayEls[id];
}
// 存储学生列表容器引用以便后续清理
const studentListEl = $('student-list');
let out = '';
for(let s of game.students){
if(s && s.active === false) continue;
let pressureLevel = s.pressure < 35 ? "低" : s.pressure < 65 ? "中" : "高";
let pressureClass = s.pressure < 35 ? "pressure-low" : s.pressure < 65 ? "pressure-mid" : "pressure-high";
// 检查是否有退队倾向
let hasTendency = (s.quit_tendency_weeks && s.quit_tendency_weeks > 0);
// 获取下一场比赛的晋级状态
let qualificationInfo = getStudentQualificationStatus(s);
let talentsHtml = '';
if(s.talents && s.talents.size > 0){
const talentArray = Array.from(s.talents);
talentsHtml = talentArray.map(talentName => {
const talentInfo = window.TalentManager ? window.TalentManager.getTalentInfo(talentName) : { name: talentName, description: '暂无描述', color: '#2b6cb0' };
return `<span class="talent-tag" data-talent="${talentName}" style="background-color: ${talentInfo.color}20; color: ${talentInfo.color}; border-color: ${talentInfo.color}40;">
${talentName}
<span class="talent-tooltip">${talentInfo.description}</span>
</span>`;
}).join('');
}
out += `<div class="student-box">
<button class="evict-btn" data-idx="${game.students.indexOf(s)}" title="劝退">劝退</button>
<div class="student-header">
<div class="student-name">
${s.name}
${s.sick_weeks > 0 ? '<span class="warn" title="训练效率下降,压力累计加速" aria-label="训练效率下降,压力累计加速">[生病]</span>' : ''}
${hasTendency ? '<span class="warn">[退队倾向]</span>' : ''}
${qualificationInfo.html}
</div>
<div class="student-status">
<span class="label-pill ${pressureClass}">压力: ${pressureLevel}</span>
</div>
</div>
<div class="student-details" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
<div style="display:flex;align-items:center;gap:6px;">
<span style="font-size:12px;color:#718096;font-weight:600;">知识</span>
<div class="knowledge-badges">
<span class="kb" title="数据结构: ${Math.floor(Number(s.knowledge_ds||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.knowledge_ds||0)))}">
DS ${getLetterGradeAbility(Math.floor(Number(s.knowledge_ds||0)))}
</span>
<span class="kb" title="图论: ${Math.floor(Number(s.knowledge_graph||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.knowledge_graph||0)))}">
图论 ${getLetterGradeAbility(Math.floor(Number(s.knowledge_graph||0)))}
</span>
<span class="kb" title="字符串: ${Math.floor(Number(s.knowledge_string||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.knowledge_string||0)))}">
字符串${getLetterGradeAbility(Math.floor(Number(s.knowledge_string||0)))}
</span>
<span class="kb" title="数学: ${Math.floor(Number(s.knowledge_math||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.knowledge_math||0)))}">
数学 ${getLetterGradeAbility(Math.floor(Number(s.knowledge_math||0)))}
</span>
<span class="kb" title="动态规划: ${Math.floor(Number(s.knowledge_dp||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.knowledge_dp||0)))}">
DP ${getLetterGradeAbility(Math.floor(Number(s.knowledge_dp||0)))}
</span>
<span class="kb ability" title="思维: ${Math.floor(Number(s.thinking||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.thinking||0)))}">思维${getLetterGradeAbility(Math.floor(Number(s.thinking||0)))}</span>
<span class="kb ability" title="代码: ${Math.floor(Number(s.coding||0))}" data-grade="${getLetterGradeAbility(Math.floor(Number(s.coding||0)))}">代码${getLetterGradeAbility(Math.floor(Number(s.coding||0)))}</span>
</div>
</div>
${talentsHtml ? `<div style="display:flex;align-items:center;gap:6px;"><span style="font-size:12px;color:#718096;font-weight:600;">天赋</span><div class="student-talents">${talentsHtml}</div></div>` : ''}
</div>
</div>`;
}
if(out==='') out = '<div class="muted">目前没有活跃学生</div>';
// 清理旧的DOM节点和事件监听器
if(studentListEl){
// 移除旧的事件监听器
const oldButtons = studentListEl.querySelectorAll('.evict-btn');
oldButtons.forEach(btn => {
const clonedBtn = btn.cloneNode(true);
if(btn.parentNode){
btn.parentNode.replaceChild(clonedBtn, btn);
}
});
// 更新内容
studentListEl.innerHTML = out;
}
// 重新绑定事件(使用事件委托减少监听器数量)
if(studentListEl && !studentListEl._evictDelegated){
studentListEl._evictDelegated = true;
studentListEl.addEventListener('click', function(e){
const btn = e.target.closest('.evict-btn');
if(!btn) return;
const idx = parseInt(btn.dataset.idx,10);
if(isNaN(idx)) return;
if(game.reputation < EVICT_REPUTATION_COST){ alert('声誉不足,无法劝退'); return; }
if(!confirm(`确认劝退 ${game.students[idx].name}?将消耗声誉 ${EVICT_REPUTATION_COST}`)) return;
evictSingle(idx);
});
}
renderEventCards();
try{
const pending = hasPendingRequiredEvents();
const actionCards = Array.from(document.querySelectorAll('.action-card'));
if(pending){
actionCards.forEach(ac => {
ac.classList.add('disabled');
ac.setAttribute('aria-disabled', 'true');
ac.setAttribute('tabindex', '-1');
try{
if(typeof ac._origOnclickFn === 'undefined'){
ac._origOnclickFn = ac.onclick || null;
}
}catch(e){}
ac.onclick = (e) => { e && e.stopPropagation && e.stopPropagation(); e && e.preventDefault && e.preventDefault();
const msg = '存在未处理的事件卡片,请先在右侧事件区域选择处理后再进行行动。';
if(window.toastManager && typeof window.toastManager.show === 'function') window.toastManager.show(msg, 'warning'); else try{ alert(msg); }catch(e){}
const container = $('event-cards-container');
if(container){
const firstPending = container.querySelector('.event-card.event-required');
if(firstPending){
try{ firstPending.scrollIntoView({ behavior: 'smooth', block: 'center' }); }catch(e){}
firstPending.classList.add('highlight-pending');
setTimeout(()=>{ firstPending.classList.remove('highlight-pending'); }, 1800);
}
}
};
});
const container = $('event-cards-container');
if(container){
const firstPending = container.querySelector('.event-card.event-required');
if(firstPending){ try{ firstPending.scrollIntoView({ behavior: 'smooth', block: 'center' }); }catch(e){}; firstPending.classList.add('highlight-pending'); setTimeout(()=>{ firstPending.classList.remove('highlight-pending'); }, 1800); }
}
} else {
actionCards.forEach(ac => {
ac.classList.remove('disabled');
ac.removeAttribute('aria-disabled');
ac.setAttribute('tabindex', '0');
try{
if(typeof ac._origOnclickFn !== 'undefined'){
try{ ac.onclick = ac._origOnclickFn; }catch(e){}
try{ delete ac._origOnclickFn; }catch(e){}
} else {
if(ac.onclick && ac.onclick.toString && ac.onclick.toString().includes('存在未处理的事件卡片')){
ac.onclick = null;
}
}
}catch(e){}
});
}
}catch(e){ /* ignore UI assist failures */ }
let compNow = null;
const sortedComps = Array.isArray(competitions) ? competitions.slice().sort((a,b)=>a.week - b.week) : [];
for (let comp of sortedComps) {
if (comp.week === currWeek()) {
const half = (currWeek() > WEEKS_PER_HALF) ? 1 : 0;
const key = `${half}_${comp.name}_${comp.week}`;
if (!game.completedCompetitions || !game.completedCompetitions.has(key)) {
compNow = comp;
}
break;
}
}
const actionContainer = document.querySelector('.action-cards');
if (compNow) {
if (!document.getElementById('comp-only-action')) {
const compCard = document.createElement('div');
compCard.className = 'action-card comp-highlight';
compCard.id = 'comp-only-action'; compCard.setAttribute('role','button'); compCard.tabIndex = 0;
compCard.innerHTML = `<div class="card-title">参加比赛【${compNow.name}】</div>`;
compCard.onclick = () => {
if(typeof window.holdCompetitionModalNew === 'function'){
window.holdCompetitionModalNew(compNow);
} else {
holdCompetitionModal(compNow);
}
};
const eventContainer = document.getElementById('event-cards-container');
if(eventContainer && actionContainer.contains(eventContainer)){
actionContainer.insertBefore(compCard, eventContainer);
} else {
actionContainer.appendChild(compCard);
}
}
document.body.classList.add('comp-week');
} else {
document.body.classList.remove('comp-week');
const compCard = document.getElementById('comp-only-action');
if (compCard) compCard.remove();
}
// 如果需要使用繁体中文,转换所有动态生成的内容
try {
if (window.ChineseConverter && window.ChineseConverter.shouldUseTraditionalChinese()) {
window.ChineseConverter.convertElementToTraditional(document.body);
}
} catch (e) {
console.error('renderAll 繁体转换失败:', e);
}
}
function showModal(html){
const root = $('modal-root');
if(!root) return;
root.innerHTML = `<div class="modal"><div class="dialog">${html}</div></div>`;
const dialog = root.querySelector('.dialog');
if(!dialog) return;
const actions = dialog.querySelector('.modal-actions');
if(actions){
const panel = document.createElement('div');
panel.className = 'modal-action-panel';
while(actions.firstChild){ panel.appendChild(actions.firstChild); }
actions.remove();
dialog.appendChild(panel);
const guard = document.createElement('div'); guard.className = 'modal-action-guard';
dialog.insertBefore(guard, dialog.firstChild);
const buttons = panel.querySelectorAll('button');
buttons.forEach((b, idx) => {
b.classList.add('modal-btn');
if(!b.hasAttribute('tabindex')) b.setAttribute('tabindex', '0');
if(idx === 0) b.classList.add('btn-primary');
});
const primary = panel.querySelector('button.btn-primary') || panel.querySelector('button');
if(primary) primary.focus();
}
function keyHandler(e){
if(e.key === 'Escape'){
closeModal();
}else if(e.key === 'Enter'){
let targetBtn = null;
const panelBtn = dialog.querySelector('.modal-action-panel button:not(.btn-ghost):not(:disabled)');
if(panelBtn) targetBtn = panelBtn;
else targetBtn = dialog.querySelector('button:not(.btn-ghost):not(:disabled)') || dialog.querySelector('button:not(:disabled)');
if(targetBtn){
try{ targetBtn.click(); }catch(e){}
}
}
}
root._modalKeyHandler = keyHandler;
window.addEventListener('keydown', keyHandler);
// 如果需要使用繁体中文,转换模态框内容
try {
if (window.ChineseConverter && window.ChineseConverter.shouldUseTraditionalChinese()) {
window.ChineseConverter.convertElementToTraditional(dialog);
}
} catch (e) {
console.error('showModal 繁体转换失败:', e);
}
}
function closeModal(){
const root = $('modal-root');
if(!root) return;
// 清理事件监听器
if(root._modalKeyHandler){
try{ window.removeEventListener('keydown', root._modalKeyHandler); }catch(e){}
root._modalKeyHandler = null;
}
// 清理DOM内的所有按钮事件监听器
const allButtons = root.querySelectorAll('button');
allButtons.forEach(btn => {
const clone = btn.cloneNode(true);
if(btn.parentNode) btn.parentNode.replaceChild(clone, btn);
});
// 清空内容
root.innerHTML = '';
}
function trainStudentsUI(){
// 从 game 对象读取本周的题目(在周推进时已选好)
// 如果没有本周题目(例如游戏刚开始),则现场选择
let tasks = game.weeklyTasks;
if (!tasks || !Array.isArray(tasks) || tasks.length === 0) {
tasks = selectRandomTasks(7);
game.weeklyTasks = tasks;
}
const taskCards = tasks.map((task, idx) => {
const boostStr = task.boosts.map(b => `${b.type}+${b.amount}`).join(' ');
const diffTag = renderDifficultyTag(task.difficulty);
return `
<div class="prov-card option-card task-card" data-idx="${idx}" style="min-width:200px;padding:12px;border-radius:6px;cursor:pointer;border:2px solid #ddd;">
<div class="card-title" style="font-weight:600;margin-bottom:4px">${task.name}</div>
<div class="small" style="margin:4px 0">难度: ${diffTag}</div>
<div class="card-desc small muted">${boostStr}</div>
</div>
`;
}).join('');
const intensityHtml = `
<div style="margin-top:8px;padding:0 4px;text-align:center;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;max-width:220px;margin-left:auto;margin-right:auto;">
<span class="small" style="color:#666;">轻度</span>
<span id="intensity-value" style="font-weight:700;font-size:16px;color:var(--accent);">中度</span>
<span class="small" style="color:#666;">重度</span>
</div>
<input type="range" id="intensity-slider" min="1" max="3" value="2" step="1"
style="width:220px;display:block;margin:0 auto;height:8px;border-radius:4px;outline:none;-webkit-appearance:none;appearance:none;background:linear-gradient(to right, #48bb78 0%, #ecc94b 50%, #f56565 100%);">
</div>
<div id="intensity-warning" style="margin-top:12px;font-weight:700;text-align:center;display:none;"></div>
<div class="small muted" style="margin-top:6px;text-align:center;">强度影响压力和训练效果</div>
`;
showModal(`<h3>选择训练题目</h3>
<div class="small muted" style="margin-bottom:10px">从下方7道题目中选择一道进行训练。题目提升效果受学生能力与难度匹配度影响。</div>
<label class="block">可选题目</label>
<div id="train-task-grid" style="display:flex;gap:12px;flex-wrap:wrap;margin-top:8px;overflow-x:auto;max-height:300px;overflow-y:auto;">${taskCards}</div>
<div id="train-task-helper" class="small muted" style="margin-top:6px;display:none;color:#c53030;font-weight:700"></div>
<label class="block" style="margin-top:14px">训练强度</label>
${intensityHtml}
<div class="modal-actions" style="margin-top:16px">
<button class="btn btn-ghost" onclick="closeModal()">取消</button>
<button class="btn" id="train-confirm">开始训练(1周)</button>
</div>`);
// 题目选择逻辑
const tCards = Array.from(document.querySelectorAll('#train-task-grid .task-card'));
if(tCards.length > 0) tCards[0].classList.add('selected');
tCards.forEach(c => {
c.onclick = () => {
tCards.forEach(x => { x.classList.remove('selected'); x.classList.remove('shake'); });
c.classList.add('selected');
const helper = $('train-task-helper'); if(helper){ helper.style.display='none'; helper.innerText=''; }
const grid = $('train-task-grid'); if(grid) grid.classList.remove('highlight-required');
updateIntensityWarning();
};
});
// 滑块控制逻辑
const slider = document.getElementById('intensity-slider');
const valueDisplay = document.getElementById('intensity-value');
// 自定义滑块样式(适配不同浏览器)
const style = document.createElement('style');
style.textContent = `
#intensity-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: white;
cursor: pointer;
border: 2px solid var(--accent);
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
#intensity-slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: white;
cursor: pointer;
border: 2px solid var(--accent);
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
#intensity-slider::-webkit-slider-track {
height: 8px;
border-radius: 4px;
}
#intensity-slider::-moz-range-track {
height: 8px;
border-radius: 4px;
}
`;
document.head.appendChild(style);
function updateIntensityWarning() {
const intensity = parseInt(slider.value);
const intensityNames = ['', '轻度', '中度', '重度'];
valueDisplay.textContent = intensityNames[intensity];
const taskBtn = document.querySelector('#train-task-grid .task-card.selected');
if(!taskBtn) return;
const taskIdx = parseInt(taskBtn.dataset.idx);
const selectedTask = tasks[taskIdx];
// 预计算压力变化
const warningDiv = document.getElementById('intensity-warning');
const result = calculateTrainingPressure(selectedTask, intensity);
warningDiv.style.display = 'block';
// 仅使用彩色文本展示简单状态(不显示背景或额外描述)
if(result.hasQuitRisk) {
warningDiv.style.color = '#c53030';
warningDiv.innerText = '压力过大';
} else if(result.hasHighPressure) {
warningDiv.style.color = '#d97706';
warningDiv.innerText = '压力略大';
} else {
warningDiv.style.color = '#2f855a';
warningDiv.innerText = '压力尚可';
}
}
slider.addEventListener('input', updateIntensityWarning);
updateIntensityWarning();
$('train-confirm').onclick = () => {
let taskBtn = document.querySelector('#train-task-grid .task-card.selected');
if(!taskBtn) {
const helper = $('train-task-helper'); if(helper){ helper.style.display='block'; helper.innerText='请先选择一道训练题目以开始训练'; }
const grid = $('train-task-grid'); if(grid) grid.classList.add('highlight-required');
const first = document.querySelector('#train-task-grid .task-card');
if(first){ first.classList.add('shake'); setTimeout(()=>first.classList.remove('shake'), 900); try{ first.scrollIntoView({ behavior: 'smooth', block: 'center' }); }catch(e){} }
return;
}
let taskIdx = parseInt(taskBtn.dataset.idx);
let selectedTask = tasks[taskIdx];
let intensity = parseInt(slider.value);
closeModal();
trainStudentsWithTask(selectedTask, intensity);
let nextComp = competitions.find(c => c.week > currWeek());
let weeksToComp = nextComp ? (nextComp.week - currWeek()) : Infinity;
let advance = Math.min(1, weeksToComp);
safeWeeklyUpdate(advance);
renderAll();
};
}
function holdMockContestUI(){
const officialContestOptions = COMPETITION_SCHEDULE.map((comp, idx) =>
`<option value="${idx}">${comp.name} (难度${comp.difficulty}, ${comp.numProblems}题)</option>`
).join('');
const onlineContestOptions = ONLINE_CONTEST_TYPES.map((type, idx) =>
`<option value="${idx}">${type.displayName} (${type.numProblems}题)</option>`
).join('');
let kpHtml = KP_OPTIONS.map(k=>`<label style="margin-right:8px"><input type="checkbox" class="kp-option" value="${k.name}"> ${k.name}</label>`).join("<br/>");
showModal(`<h3>配置模拟赛(1周)</h3>
<div><label class="block">比赛类型</label>
<select id="mock-purchase">
<option value="0">网赛(免费)</option>
<option value="1">付费比赛(可选难度和tag)</option>
</select>
</div>
<div id="mock-difficulty-container" style="margin-top:8px;display:none;">
<label class="block">比赛难度</label>
<select id="mock-difficulty">${officialContestOptions}</select>
</div>
<div id="mock-online-container" style="margin-top:8px;">
<label class="block">网赛类型</label>
<select id="mock-contest-type" style="display:none">${onlineContestOptions}</select>
<div id="mock-contest-type-grid" style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap"></div>
</div>
<div id="mock-questions-container" style="margin-top:8px">
</div>
<div class="modal-actions" style="margin-top:10px">
<button class="btn btn-ghost" onclick="closeModal()">取消</button>
<button class="btn" id="mock-submit">开始模拟赛(1周)</button>
</div>`);
function updateQuestions(){
const isPurchased = $('mock-purchase').value === "1";
if(isPurchased){
$('mock-difficulty-container').style.display = 'block';
$('mock-online-container').style.display = 'none';
const diffIdx = parseInt($('mock-difficulty').value);
const comp = COMPETITION_SCHEDULE[diffIdx];
const numProblems = comp.numProblems;
let questionsHtml = '<div class="small">为每题选择 1 或多个 知识点 标签:</div>';
for(let i = 1; i <= numProblems; i++){
questionsHtml += `<div style="margin-top:6px"><strong>第 ${i} 题</strong><br/>${kpHtml}</div>`;
}
$('mock-questions-container').innerHTML = questionsHtml;
} else {
$('mock-difficulty-container').style.display = 'none';
$('mock-online-container').style.display = 'block';
const typeIdx = parseInt($('mock-contest-type').value);
const contestType = ONLINE_CONTEST_TYPES[typeIdx];
$('mock-questions-container').innerHTML = `<div class="small">网赛共 ${contestType.numProblems} 题</div>`;
}
}
updateQuestions();
$('mock-purchase').onchange = updateQuestions;
$('mock-difficulty').onchange = updateQuestions;
$('mock-contest-type').onchange = updateQuestions;
function renderMockContestTypeGrid(){
const grid = document.getElementById('mock-contest-type-grid');
const hidden = document.getElementById('mock-contest-type');
if(!grid || !hidden) return;
grid.innerHTML = '';
ONLINE_CONTEST_TYPES.forEach((t, idx) => {
const card = document.createElement('div');
card.className = 'option-card';
card.dataset.val = idx;
card.style.padding = '10px';
card.style.border = '1px solid #e6e6e6';
card.style.borderRadius = '8px';
card.style.cursor = 'pointer';
card.style.minWidth = '120px';
card.innerHTML = `<div style="font-weight:600">${t.displayName}</div><div class="small muted">${t.numProblems}题</div>`;
card.addEventListener('click', ()=>{
grid.querySelectorAll('.option-card.selected').forEach(c=>c.classList.remove('selected'));
card.classList.add('selected');
hidden.value = ''+idx;
try{ hidden.onchange && hidden.onchange(); }catch(e){}
});
grid.appendChild(card);
});
const initial = hidden.value || '0';
const chosen = grid.querySelector(`.option-card[data-val='${initial}']`);
if(chosen) chosen.classList.add('selected');
}
try{ renderMockContestTypeGrid(); }catch(e){ console.error('渲染网赛类型网格失败', e); }
$('mock-submit').onclick = ()=>{
const isPurchased = $('mock-purchase').value === "1";
let difficultyConfig, numProblems, questionTagsArray = [];
if(isPurchased){
const diffIdx = parseInt($('mock-difficulty').value);
const comp = COMPETITION_SCHEDULE[diffIdx];
difficultyConfig = {
type: 'official',
difficulty: comp.difficulty,
name: comp.name,
numProblems: comp.numProblems
};
numProblems = comp.numProblems;
let kpOptions = Array.from(document.querySelectorAll('.kp-option'));
let groupSize = KP_OPTIONS.length;
for(let q = 0; q < numProblems; q++){
let tags = [];
for(let k = 0; k < groupSize; k++){
let idx = q * groupSize + k;
if(kpOptions[idx] && kpOptions[idx].checked) tags.push(kpOptions[idx].value);
}
questionTagsArray.push(tags);
}
} else {
const typeIdx = parseInt($('mock-contest-type').value);
const contestType = ONLINE_CONTEST_TYPES[typeIdx];
difficultyConfig = {
type: 'online',
typeIdx: typeIdx,
difficulty: contestType.difficulty,
name: contestType.displayName,
onlineContestType: contestType.name,
numProblems: contestType.numProblems
};
numProblems = contestType.numProblems;
const allTags = ["数据结构", "图论", "字符串", "数学", "动态规划"];