Repository navigation
Expand file tree
/
Copy pathui.js
More file actions
401 lines (344 loc) · 12.7 KB
/
Copy pathui.js
File metadata and controls
401 lines (344 loc) · 12.7 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
// 狼人杀模拟面板 - UI逻辑
import { WerewolfGame } from './game.js';
import { AIPlayerManager, GameController } from './ai-player.js';
import { GAME_CONFIG } from './config.js';
class WerewolfUI {
constructor() {
this.game = new WerewolfGame();
this.ai = new AIPlayerManager();
this.controller = new GameController(this.game, this.ai);
this.autoScroll = true;
this.isInitialized = false;
}
init() {
if (this.isInitialized) return;
this.isInitialized = true;
this.bindEvents();
this.renderPlayerSeats();
this.updateStatus();
// 设置控制器回调
this.controller.setCallbacks({
onUpdate: (state) => this.updateState(state),
onLog: (message) => this.addLog(message),
onSpeech: (player, content) => this.addSpeech(player, content)
});
}
bindEvents() {
const startBtn = document.getElementById('btnStart');
const pauseBtn = document.getElementById('btnPause');
const resumeBtn = document.getElementById('btnResume');
const stopBtn = document.getElementById('btnStop');
const resetBtn = document.getElementById('btnReset');
const speedBtns = document.querySelectorAll('.btn-speed');
const apiKeyInput = document.getElementById('apiKeyInput');
const apiKeyBtn = document.getElementById('apiKeyBtn');
if (startBtn) startBtn.addEventListener('click', () => this.startGame());
if (pauseBtn) pauseBtn.addEventListener('click', () => this.pauseGame());
if (resumeBtn) resumeBtn.addEventListener('click', () => this.resumeGame());
if (stopBtn) stopBtn.addEventListener('click', () => this.stopGame());
if (resetBtn) resetBtn.addEventListener('click', () => this.resetGame());
if (speedBtns) {
speedBtns.forEach(btn => {
btn.addEventListener('click', () => {
speedBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const speed = parseInt(btn.dataset.speed);
this.controller.setSpeed(speed);
});
});
}
if (apiKeyBtn) {
apiKeyBtn.addEventListener('click', () => {
const key = apiKeyInput?.value?.trim();
if (key) {
this.ai.setApiKey(key);
this.addLog('info', '🔑 GLM API密钥已设置,将使用真实API调用');
} else {
this.ai.setApiKey(null);
this.addLog('info', '📝 已切换为Mock模式');
}
});
}
}
// 开始游戏
async startGame() {
this.game = new WerewolfGame();
this.ai = new AIPlayerManager(this.ai.apiKey);
this.controller = new GameController(this.game, this.ai);
this.controller.setCallbacks({
onUpdate: (state) => this.updateState(state),
onLog: (message) => this.addLog(message),
onSpeech: (player, content) => this.addSpeech(player, content)
});
this.clearLogs();
this.clearSpeeches();
this.removeGameOver();
this.updateButtonState('running');
try {
await this.controller.start();
} catch (error) {
console.error('游戏运行错误:', error);
this.addLog('error', `❌ 游戏运行错误: ${error.message}`);
}
}
pauseGame() {
this.controller.pause();
this.updateButtonState('paused');
this.addLog('info', '⏸️ 游戏已暂停');
}
resumeGame() {
this.controller.resume();
this.updateButtonState('running');
this.addLog('info', '▶️ 游戏已继续');
}
stopGame() {
this.controller.pause();
this.updateButtonState('stopped');
this.addLog('info', '⏹️ 游戏已停止');
}
resetGame() {
this.controller.pause();
this.game = new WerewolfGame();
this.controller = new GameController(this.game, this.ai);
this.controller.setCallbacks({
onUpdate: (state) => this.updateState(state),
onLog: (message) => this.addLog(message),
onSpeech: (player, content) => this.addSpeech(player, content)
});
this.clearLogs();
this.clearSpeeches();
this.removeGameOver();
this.renderPlayerSeats();
this.updateStatus();
this.updateButtonState('idle');
this.addLog('info', '🔄 游戏已重置');
}
// 更新按钮状态
updateButtonState(state) {
const startBtn = document.getElementById('btnStart');
const pauseBtn = document.getElementById('btnPause');
const resumeBtn = document.getElementById('btnResume');
const stopBtn = document.getElementById('btnStop');
if (startBtn) startBtn.disabled = (state === 'running' || state === 'paused');
if (pauseBtn) pauseBtn.disabled = (state !== 'running');
if (resumeBtn) resumeBtn.disabled = (state !== 'paused');
if (stopBtn) stopBtn.disabled = (state === 'idle' || state === 'stopped');
}
// 渲染玩家座位
renderPlayerSeats(players = null) {
const container = document.getElementById('playerSeats');
if (!container) return;
if (!players) {
players = Array.from({ length: 12 }, (_, i) => ({
seat: i + 1,
name: '',
alive: true,
role: null,
personality: null
}));
}
container.innerHTML = players.map(p => {
const roleInfo = p.role ? GAME_CONFIG.roles[p.role] : null;
return `
<div class="player-seat ${p.alive ? 'alive' : 'dead'} ${p.role ? this.getRoleClass(p.role) : ''}"
data-seat="${p.seat}"
data-role="${p.role || ''}"
data-player-id="${p.id || ''}">
<div class="seat-number">${p.seat}号</div>
<div class="seat-emoji">${roleInfo ? roleInfo.emoji : '❓'}</div>
<div class="seat-name">${p.name || '等待中'}</div>
<div class="seat-role">${roleInfo ? roleInfo.name : ''}</div>
${p.personality ? `<div class="seat-personality">${p.personality.name}</div>` : ''}
${!p.alive ? '<div class="death-mark">💀</div>' : ''}
</div>
`;
}).join('');
}
getRoleClass(role) {
const classMap = {
'WEREWOLF': 'wolf',
'SEER': 'village',
'WITCH': 'village',
'HUNTER': 'village',
'GUARD': 'village',
'VILLAGER': 'village'
};
return classMap[role] || '';
}
// 更新游戏状态
updateState(state) {
this.renderPlayerSeats(state.players);
this.updateStatus(state);
this.updateVoteResults(state);
// 检查游戏结束
if (state.winner) {
this.showGameOver(state);
}
}
// 更新状态栏
updateStatus(state = null) {
const roundEl = document.getElementById('roundNumber');
const phaseEl = document.getElementById('phaseText');
const wolfCountEl = document.getElementById('wolfCount');
const villageCountEl = document.getElementById('villageCount');
const aliveCountEl = document.getElementById('aliveCount');
if (state) {
if (roundEl) roundEl.textContent = state.round;
if (phaseEl) {
const phaseNames = {
'night': '🌙 夜晚',
'day_discuss': '☀️ 白天讨论',
'day_vote': '🗳️ 投票',
'game_over': '🎮 游戏结束'
};
phaseEl.textContent = phaseNames[state.phase] || state.phase;
}
if (wolfCountEl) wolfCountEl.textContent = state.aliveCount.wolves;
if (villageCountEl) villageCountEl.textContent = state.aliveCount.villagers;
if (aliveCountEl) aliveCountEl.textContent = state.aliveCount.total;
} else {
if (roundEl) roundEl.textContent = '0';
if (phaseEl) phaseEl.textContent = '等待开始';
if (wolfCountEl) wolfCountEl.textContent = '4';
if (villageCountEl) villageCountEl.textContent = '8';
if (aliveCountEl) aliveCountEl.textContent = '12';
}
}
// 更新投票结果
updateVoteResults(state) {
const container = document.getElementById('voteResults');
if (!container) return;
const currentRoundVotes = this.game.voteResults[state.round] || [];
if (currentRoundVotes.length === 0) {
container.innerHTML = '<div style="color: var(--text-muted); text-align: center; padding: 20px;">暂无投票数据</div>';
return;
}
// 统计投票
const voteCount = {};
currentRoundVotes.forEach(v => {
if (!voteCount[v.targetId]) {
voteCount[v.targetId] = {
seat: v.targetSeat,
count: 0,
voters: []
};
}
voteCount[v.targetId].count++;
voteCount[v.targetId].voters.push(v.voterSeat);
});
const maxVotes = Math.max(...Object.values(voteCount).map(v => v.count), 1);
container.innerHTML = Object.values(voteCount)
.sort((a, b) => b.count - a.count)
.map(v => `
<div class="vote-bar">
<div class="vote-target">${v.seat}号</div>
<div class="vote-count">${v.count}票</div>
<div class="vote-bar-track">
<div class="vote-bar-fill" style="width: ${(v.count / maxVotes) * 100}%"></div>
</div>
<div style="font-size: 0.75em; color: var(--text-muted);">来自: ${v.voters.join('号、')}号</div>
</div>
`).join('');
}
// 添加发言
addSpeech(player, content) {
const container = document.getElementById('speechList');
if (!container) return;
const roleInfo = GAME_CONFIG.roles[player.role];
const speechItem = document.createElement('div');
speechItem.className = 'speech-item';
speechItem.innerHTML = `
<div class="speech-header">
<span class="speaker-name">${player.seat}号 ${player.name} ${roleInfo.emoji}</span>
<span>第${this.game.round}轮</span>
</div>
<div class="speech-content">${content}</div>
`;
container.appendChild(speechItem);
if (this.autoScroll) {
container.scrollTop = container.scrollHeight;
}
}
// 添加日志
addLog(message, type = 'info') {
const container = document.getElementById('logList');
if (!container) return;
const logClass = this.getLogClass(message);
const logItem = document.createElement('div');
logItem.className = `log-item ${logClass}`;
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
logItem.innerHTML = `<span style="color: var(--text-muted); font-size: 0.8em;">[${time}]</span> ${message}`;
container.appendChild(logItem);
if (this.autoScroll) {
container.scrollTop = container.scrollHeight;
}
}
getLogClass(message) {
if (message.includes('🌙') || message.includes('夜晚')) return 'night';
if (message.includes('☀️') || message.includes('白天')) return 'day';
if (message.includes('💀') || message.includes('死亡')) return 'death';
if (message.includes('🗳️') || message.includes('投票')) return 'vote';
return 'info';
}
// 清除日志
clearLogs() {
const container = document.getElementById('logList');
if (container) {
container.innerHTML = '';
}
}
// 清除发言
clearSpeeches() {
const container = document.getElementById('speechList');
if (container) {
container.innerHTML = '';
}
}
// 显示游戏结束
showGameOver(state) {
this.removeGameOver();
const villageWon = state.winner === 'village';
const overlay = document.createElement('div');
overlay.className = 'game-over-overlay';
overlay.id = 'gameOverOverlay';
overlay.innerHTML = `
<div class="game-over-card">
<div class="winner-emoji">${villageWon ? '🏆' : '🐺'}</div>
<div class="winner-text">${villageWon ? '好人阵营获胜!' : '狼人阵营获胜!'}</div>
<div class="winner-detail">
<p>游戏在第${state.round}轮结束</p>
<p>存活狼人: ${state.aliveCount.wolves} | 存活好人: ${state.aliveCount.villagers}</p>
<p>GLM能力测试完成!查看发言记录和投票数据评估AI表现</p>
</div>
<button onclick="this.closest('.game-over-overlay').remove()">关闭</button>
<button onclick="window.werewolfUI.resetGame()" style="margin-left: 10px; background: var(--success);">再来一局</button>
</div>
`;
document.body.appendChild(overlay);
this.updateButtonState('stopped');
}
removeGameOver() {
const overlay = document.getElementById('gameOverOverlay');
if (overlay) {
overlay.remove();
}
}
// 导出游戏数据
exportGameData() {
const data = this.game.exportGame();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `werewolf-game-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
this.addLog('info', '📁 游戏数据已导出');
}
}
// 全局实例
window.werewolfUI = new WerewolfUI();
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
window.werewolfUI.init();
});