-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
656 lines (544 loc) · 19.2 KB
/
Copy pathserver.js
File metadata and controls
656 lines (544 loc) · 19.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
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
// server.js - WebSocket伺服器
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// 遊戲狀態
const gameState = {
players: {},
playerCount: 0,
currentRound: 0,
totalRounds: 19,
roundInProgress: false,
roundStartTime: null,
playersReady: new Set(),
playersInRound: new Set(),
roundDuration: 0,
gameStarted: false,
lastPlayerToRelease: null,
playerSessions: {}, // 儲存玩家 session 時間戳
playerButtonPressTime: {}, // 新增:儲存玩家按下按鈕的時間
readyCheckInterval: null, // 新增:檢查是否所有玩家都按住超過一秒的計時器
playerRoundStartTime: {} // 新增:記錄每位玩家開始參與當前回合的時間
};
// 格式化時間為 分:秒.1
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toFixed(1).padStart(4, '0')}`;
}
// 配置靜態檔案服務
app.use(express.static('public'));
// API 端點:獲取本機 IP 地址
app.get('/api/ips', (req, res) => {
const ips = getLocalIP();
res.json({ ips });
});
// WebSocket連線處理
wss.on('connection', (ws) => {
console.log('新連線建立');
ws.on('message', (message) => {
const data = JSON.parse(message);
switch (data.type) {
case 'register':
handlePlayerRegister(ws, data);
break;
case 'reconnect':
handlePlayerReconnect(ws, data);
break;
case 'removePlayer':
handlePlayerRemove(ws, data);
break;
case 'buttonDown':
handleButtonDown(ws, data);
break;
case 'buttonUp':
handleButtonUp(ws, data);
break;
case 'hostConnect':
handleHostConnect(ws);
break;
case 'updateSettings':
handleUpdateSettings(data);
break;
case 'startGame':
startGame();
break;
case 'endGame':
forceEndGame();
break;
case 'resetGame':
resetGame();
break;
}
});
ws.on('close', () => {
// 處理斷線
if (ws.playerId) {
const playerId = ws.playerId;
if (gameState.players[playerId]) {
gameState.players[playerId].connected = false;
gameState.playerSessions[playerId] = Date.now();
// 如果玩家在準備狀態,移除
gameState.playersReady.delete(playerId);
// 清除按鈕按下時間
delete gameState.playerButtonPressTime[playerId];
// 如果玩家在回合中,移除
gameState.playersInRound.delete(playerId);
// 清除回合開始時間記錄
delete gameState.playerRoundStartTime[playerId];
console.log(`玩家 ${gameState.players[playerId].name} 斷線`);
broadcastGameState();
}
}
});
});
// 處理設定更新
function handleUpdateSettings(data) {
if (!gameState.gameStarted) {
// 更新總回合數
if (data.totalRounds) {
gameState.totalRounds = data.totalRounds;
}
// 更新所有玩家的初始時間
if (data.initialTime) {
for (let playerId in gameState.players) {
gameState.players[playerId].timeRemaining = parseFloat(data.initialTime);
}
}
// 廣播更新的遊戲狀態
broadcastGameState();
}
}
// 處理玩家註冊
function handlePlayerRegister(ws, data) {
// 檢查是否有相同名字的離線玩家
const existingPlayer = Object.values(gameState.players)
.find(p => p.name === data.playerName && !p.connected);
if (existingPlayer) {
// 如果找到相同名字的離線玩家,直接重連
console.log(`發現相同名字的離線玩家 ${data.playerName},自動重連`);
handlePlayerReconnect(ws, {
playerId: existingPlayer.id,
playerName: data.playerName
});
return;
}
// 生成唯一的玩家ID
const playerId = `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// 使用當前設定的初始時間(如果沒有特別設定,預設10分鐘)
const currentInitialTime = Object.values(gameState.players).length > 0
? Object.values(gameState.players)[0].timeRemaining
: 600.0;
gameState.players[playerId] = {
id: playerId,
name: data.playerName,
timeRemaining: currentInitialTime, // 使用當前設定的時間
roundsWon: 0,
connected: true,
ws: ws,
joinOrder: gameState.playerCount++
};
gameState.playerSessions[playerId] = Date.now();
ws.playerId = playerId;
console.log(`新玩家 ${data.playerName} 加入遊戲`);
ws.send(JSON.stringify({
type: 'registered',
playerId: playerId,
playerData: gameState.players[playerId]
}));
broadcastGameState();
}
// 處理玩家重連
function handlePlayerReconnect(ws, data) {
const { playerId, playerName } = data;
// 檢查玩家是否存在
if (gameState.players[playerId]) {
// 更新 WebSocket 連線
gameState.players[playerId].ws = ws;
gameState.players[playerId].connected = true;
gameState.playerSessions[playerId] = Date.now();
ws.playerId = playerId;
console.log(`玩家 ${gameState.players[playerId].name} 重新連線`);
ws.send(JSON.stringify({
type: 'reconnected',
playerId: playerId,
playerData: gameState.players[playerId]
}));
broadcastGameState();
} else {
// 如果玩家不存在,當作新註冊
console.log(`重連失敗,玩家 ${playerName} 不存在,新註冊`);
handlePlayerRegister(ws, { playerName });
}
}
// 處理玩家主動移除
function handlePlayerRemove(ws, data) {
const { playerId } = data;
if (gameState.players[playerId]) {
const playerName = gameState.players[playerId].name;
// 從準備和回合中移除
gameState.playersReady.delete(playerId);
gameState.playersInRound.delete(playerId);
// 清除按鈕按下時間
delete gameState.playerButtonPressTime[playerId];
// 清除回合開始時間記錄
delete gameState.playerRoundStartTime[playerId];
// 刪除玩家資料
delete gameState.players[playerId];
delete gameState.playerSessions[playerId];
console.log(`玩家 ${playerName} 已主動退出遊戲`);
// 通知所有客戶端更新狀態
broadcastGameState();
}
}
// 處理主持人連線
function handleHostConnect(ws) {
ws.isHost = true;
ws.send(JSON.stringify({
type: 'hostConnected',
gameState: gameState
}));
}
// 處理按鈕按下
function handleButtonDown(ws, data) {
// 必須遊戲已經開始才處理按鈕事件
if (!gameState.gameStarted) {
return; // 直接返回,不發送任何訊息
}
const playerId = data.playerId;
const player = gameState.players[playerId];
if (!player || player.timeRemaining <= 0) return;
if (!gameState.roundInProgress) {
// 準備階段
gameState.playersReady.add(playerId);
// 記錄按下按鈕的時間
gameState.playerButtonPressTime[playerId] = Date.now();
// 開始定期檢查是否所有玩家都按住超過一秒
if (!gameState.readyCheckInterval) {
gameState.readyCheckInterval = setInterval(checkAllPlayersHeldOneSecond, 100);
}
}
broadcastGameState();
}
// 處理按鈕鬆開
function handleButtonUp(ws, data) {
// 必須遊戲已經開始才處理按鈕事件
if (!gameState.gameStarted) {
return; // 直接返回,不做任何處理
}
const playerId = data.playerId;
if (gameState.playersReady.has(playerId) && !gameState.roundInProgress) {
// 倒數階段鬆開
gameState.playersReady.delete(playerId);
// 清除按下時間記錄
delete gameState.playerButtonPressTime[playerId];
// 如果沒有玩家在準備了,停止檢查計時器
if (gameState.playersReady.size === 0 && gameState.readyCheckInterval) {
clearInterval(gameState.readyCheckInterval);
gameState.readyCheckInterval = null;
}
} else if (gameState.playersInRound.has(playerId)) {
// 回合進行中鬆開 - 手動放開按鈕
removePlayerFromRound(playerId, '手動放開');
}
broadcastGameState();
}
// 新增:將玩家從回合中移除的統一函數
function removePlayerFromRound(playerId, reason = '未知原因') {
if (!gameState.playersInRound.has(playerId)) return;
const player = gameState.players[playerId];
if (!player) return;
// 計算該玩家在回合中的累計時間
const playerStartTime = gameState.playerRoundStartTime[playerId] || gameState.roundStartTime;
const elapsedTime = (Date.now() - playerStartTime) / 1000;
// 扣除時間
player.timeRemaining -= elapsedTime;
// 確保時間不會變成負數
if (player.timeRemaining < 0) {
player.timeRemaining = 0;
}
console.log(`玩家 ${player.name} 因為${reason}退出回合,扣除時間 ${elapsedTime.toFixed(1)} 秒,剩餘 ${player.timeRemaining.toFixed(1)} 秒`);
// 判斷是否為最後一位放開的玩家
if (gameState.playersInRound.size === 1) {
// 這是最後一個玩家,記錄為獲勝者
gameState.lastPlayerToRelease = playerId;
}
// 從回合中移除玩家
gameState.playersInRound.delete(playerId);
delete gameState.playerRoundStartTime[playerId];
// 檢查回合是否結束(所有玩家都已放開)
if (gameState.playersInRound.size === 0) {
endRound();
}
}
// 新增:檢查是否所有玩家都按住按鈕超過一秒
function checkAllPlayersHeldOneSecond() {
const currentTime = Date.now();
const activePlayers = Object.values(gameState.players)
.filter(p => p.timeRemaining > 0 && p.connected);
// 如果沒有活躍玩家或沒有玩家在準備,返回
if (activePlayers.length === 0 || gameState.playersReady.size === 0) {
return;
}
// 檢查是否所有活躍玩家都在準備中
const allActivePlayersReady = activePlayers.every(p => gameState.playersReady.has(p.id));
if (!allActivePlayersReady) {
return;
}
// 檢查是否所有準備中的玩家都按住超過一秒
const allHeldOneSecond = Array.from(gameState.playersReady).every(playerId => {
const pressTime = gameState.playerButtonPressTime[playerId];
return pressTime && (currentTime - pressTime >= 1000);
});
if (allHeldOneSecond) {
// 停止檢查計時器
if (gameState.readyCheckInterval) {
clearInterval(gameState.readyCheckInterval);
gameState.readyCheckInterval = null;
}
// 開始倒數
startCountdown();
}
}
// 開始倒數
function startCountdown() {
let countdown = 5;
const countdownInterval = setInterval(() => {
broadcast({
type: 'countdown',
count: countdown
});
if (countdown === 0) {
clearInterval(countdownInterval);
startRound();
}
countdown--;
}, 1000);
}
// 開始回合
function startRound() {
gameState.currentRound++;
gameState.roundInProgress = true;
gameState.roundStartTime = Date.now();
gameState.playersInRound = new Set(gameState.playersReady);
gameState.playersReady.clear();
// 清除所有按鈕按下時間記錄
gameState.playerButtonPressTime = {};
// 記錄每位玩家開始參與回合的時間
gameState.playerRoundStartTime = {};
for (let playerId of gameState.playersInRound) {
gameState.playerRoundStartTime[playerId] = Date.now();
}
broadcast({
type: 'roundStart',
round: gameState.currentRound
});
// 開始計時更新
const timerInterval = setInterval(() => {
if (!gameState.roundInProgress) {
clearInterval(timerInterval);
return;
}
const elapsedTime = (Date.now() - gameState.roundStartTime) / 1000;
// 新增:檢查每位玩家的時間是否用完
checkPlayersTimeRemaining();
broadcast({
type: 'roundUpdate',
elapsedTime: formatTime(elapsedTime),
playersInRound: gameState.playersInRound.size
});
}, 100); // 每100ms更新一次
}
// 新增:檢查參與回合的玩家時間是否用完
function checkPlayersTimeRemaining() {
const currentTime = Date.now();
const playersToRemove = [];
// 檢查每位參與回合的玩家
for (let playerId of gameState.playersInRound) {
const player = gameState.players[playerId];
if (!player) continue;
// 計算該玩家在當前回合已使用的時間
const playerStartTime = gameState.playerRoundStartTime[playerId] || gameState.roundStartTime;
const elapsedTime = (currentTime - playerStartTime) / 1000;
// 如果已使用時間超過或等於剩餘時間,標記為需要移除
if (elapsedTime >= player.timeRemaining) {
playersToRemove.push(playerId);
}
}
// 移除時間用完的玩家
for (let playerId of playersToRemove) {
removePlayerFromRound(playerId, '時間耗盡');
}
// 如果有玩家被移除,更新遊戲狀態
if (playersToRemove.length > 0) {
broadcastGameState();
}
}
// 結束回合
function endRound() {
gameState.roundInProgress = false;
const roundDuration = (Date.now() - gameState.roundStartTime) / 1000;
let winner = null;
// 使用記錄的最後一位放開按鈕的玩家作為獲勝者
if (gameState.lastPlayerToRelease) {
winner = gameState.lastPlayerToRelease;
gameState.players[winner].roundsWon++;
console.log(`回合 ${gameState.currentRound} 結束,獲勝者:${gameState.players[winner].name}`);
}
broadcast({
type: 'roundEnd',
winner: winner ? gameState.players[winner].name : '無人獲勝',
duration: formatTime(roundDuration),
round: gameState.currentRound
});
// 清理狀態
gameState.playersInRound.clear();
gameState.playerRoundStartTime = {};
gameState.lastPlayerToRelease = null;
// 檢查遊戲是否結束
if (gameState.currentRound >= gameState.totalRounds) {
endGame();
}
broadcastGameState();
}
// 強制結束遊戲
function forceEndGame() {
if (gameState.gameStarted) {
// 清理進行中的回合
gameState.roundInProgress = false;
gameState.playersReady.clear();
gameState.playersInRound.clear();
gameState.playerRoundStartTime = {};
// 清理檢查計時器
if (gameState.readyCheckInterval) {
clearInterval(gameState.readyCheckInterval);
gameState.readyCheckInterval = null;
}
// 結束遊戲
endGame();
}
}
// 結束遊戲
function endGame() {
const results = Object.values(gameState.players)
.sort((a, b) => {
if (b.roundsWon !== a.roundsWon) {
return b.roundsWon - a.roundsWon;
}
return b.timeRemaining - a.timeRemaining;
});
broadcast({
type: 'gameEnd',
results: results
});
gameState.gameStarted = false;
}
// 開始遊戲
function startGame() {
gameState.gameStarted = true;
gameState.currentRound = 0;
broadcast({
type: 'gameStarted'
});
broadcastGameState();
}
// 重置遊戲
function resetGame() {
gameState.currentRound = 0;
gameState.roundInProgress = false;
gameState.gameStarted = false;
gameState.playersReady.clear();
gameState.playersInRound.clear();
gameState.lastPlayerToRelease = null;
gameState.playerButtonPressTime = {};
gameState.playerRoundStartTime = {};
// 清理檢查計時器
if (gameState.readyCheckInterval) {
clearInterval(gameState.readyCheckInterval);
gameState.readyCheckInterval = null;
}
// 重置每個玩家的狀態,但保留玩家
for (let playerId in gameState.players) {
gameState.players[playerId].timeRemaining = 600.0;
gameState.players[playerId].roundsWon = 0;
}
broadcast({
type: 'gameReset'
});
broadcastGameState();
}
// 廣播訊息
function broadcast(message) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
}
// 廣播遊戲狀態
function broadcastGameState() {
broadcast({
type: 'stateUpdate',
gameState: {
players: gameState.players,
currentRound: gameState.currentRound,
totalRounds: gameState.totalRounds,
roundInProgress: gameState.roundInProgress,
playersReady: Array.from(gameState.playersReady),
playersInRound: Array.from(gameState.playersInRound),
gameStarted: gameState.gameStarted
}
});
}
// 取得本機IP地址
const os = require('os');
function getLocalIP() {
const interfaces = os.networkInterfaces();
const addresses = [];
for (let k in interfaces) {
for (let k2 in interfaces[k]) {
const address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address);
}
}
}
return addresses;
}
// 定期清理離線過久的玩家(可選功能)
setInterval(() => {
const now = Date.now();
const TIMEOUT = 30 * 60 * 1000; // 30分鐘過期
for (let playerId in gameState.players) {
const player = gameState.players[playerId];
if (!player.connected &&
gameState.playerSessions[playerId] &&
now - gameState.playerSessions[playerId] > TIMEOUT) {
console.log(`清理長時間離線的玩家 ${player.name}`);
delete gameState.players[playerId];
delete gameState.playerSessions[playerId];
}
}
}, 60000); // 每分鐘檢查一次
// 啟動伺服器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
const localIPs = getLocalIP();
console.log('========================================');
console.log('時間競標遊戲伺服器已啟動!');
console.log('========================================');
console.log(`電腦端主控台: http://localhost:${PORT}/host.html`);
console.log('');
console.log('手機端玩家控制器:');
localIPs.forEach(ip => {
console.log(` http://${ip}:${PORT}/player.html`);
});
console.log('');
console.log('請確保所有設備都在同一個 WiFi 網路下');
console.log('========================================');
console.log('結束請按Ctrl+C,或關閉視窗');
});