Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·2489 lines (2391 loc) · 101 KB
/
Copy pathserver.js
File metadata and controls
executable file
·2489 lines (2391 loc) · 101 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
// ========== 全局错误保护(记录致命异常并交给进程管理器重启)==========
process.on('uncaughtException', function (err) {
console.error('[FATAL] uncaughtException:', err);
// 未捕获异常可能已经破坏进程状态;继续运行会让 systemd/pm2 误判服务健康。
// 退出码交给进程管理器处理,尤其要正确暴露 EADDRINUSE 等启动错误。
process.exit(1);
});
process.on('unhandledRejection', function (reason, promise) {
console.error('[FATAL] unhandledRejection:', reason);
});
const express = require('express'),
app = express(),
http = require('http').Server(app),
io = require('socket.io')(http, {
// CF 橙云代理下,单 WS 连接 100 秒无流量会被切断,缩短心跳避免被切
pingInterval: 25000,
pingTimeout: 20000,
});
// ========== 配置文件(推荐方式)==========
// 在项目根目录创建 config.json(已在 .gitignore),格式:
// {
// "PORT": 8002,
// "JWT_SECRET": "与论坛 DISCUZ_SSO_SECRET 完全一致的字符串",
// "DB_HOST": "127.0.0.1",
// "DB_PORT": 3306,
// "DB_USER": "zwwx_dz",
// "DB_PASSWORD": "数据库密码",
// "DB_NAME": "zwwx_discuz",
// "DB_TABLE_PREFIX": "pre_",
// "SCORE_BASE": 1
// }
// 读取顺序:环境变量 > config.json > 默认值;并把 config.json 中的值塞回 process.env,
// 使下游模块(db.js 等)也能用 process.env.* 读到。
(function loadConfig() {
try {
const fs = require('fs');
const path = require('path');
const f = path.join(__dirname, 'config.json');
if (!fs.existsSync(f)) return;
const cfg = JSON.parse(fs.readFileSync(f, 'utf8'));
Object.keys(cfg).forEach(function (k) {
if (cfg[k] === null || cfg[k] === undefined) return;
// 环境变量优先,已设的不覆盖
if (process.env[k] !== undefined && process.env[k] !== '') return;
process.env[k] = String(cfg[k]);
});
console.log('[config] 已加载 config.json');
} catch (e) {
console.error('[config] config.json 解析失败:', e && e.message);
}
})();
app.use((req, res, next) => {
if (req.method === 'GET' && (req.path === '/' || req.path === '/index.html')) {
db.recordSiteStat('page_views').catch(() => {});
}
next();
});
app.use(express.static(`${__dirname}/static`));
app.get('/', function (req, res) {
res.sendFile(`${__dirname}/index.html`);
});
const Game = require('./game.js');
const GuandanGame = require('./guandan-game.js');
const MahjongGame = require('./mahjong-game.js');
const AISuggest = require('./static/js/ai-suggest.js').AISuggest;
const GuandanSuggest = require('./static/js/guandan-suggest.js').GuandanSuggest;
const SmartAI = require('./static/js/smart-ai.js').SmartAI;
const MahjongAI = require('./static/js/mahjong-ai.js').MahjongAI;
const AiDifficulty = require('./ai-difficulty.js');
const db = require('./db.js');
// 运营统计的历史回填说明只供服务端/维护脚本使用,公开接口只返回正常业务指标,
// 避免把“估算、来源、恢复时间”等内部数据质量字段带到用户界面。
function publicSiteStats(stats) {
const snapshot = Object.assign({}, stats || {});
delete snapshot.dataQuality;
delete snapshot.backfilledAt;
return snapshot;
}
// 站点运营数据有变化时主动推送给所有在线页面;前端统计弹窗无需手动刷新。
db.subscribeSiteStats(stats => {
io.emit('SITE_STATS_UPDATE', publicSiteStats(stats));
});
// 底分(每分对应多少积分)。可通过环境变量调整。
const SCORE_BASE = Number(process.env.SCORE_BASE || 1);
const DOU_DIZHU_PLAY_TIMEOUT = 30;
const DOU_DIZHU_STEP_TIMEOUT = 15;
const GUANDAN_PLAY_TIMEOUT = 45;
const MAHJONG_PLAY_TIMEOUT = 30;
const GAME_PAUSE_GRACE_MS = 60 * 1000;
// ========== 安全加固:API 防滥用 ==========
// 设计原则:所有"加分/扣分"都只能由服务端 socket 流程里的 game.getResult() 触发,
// 任何 HTTP 写入接口一律不存在;下方中间件确保即使将来误添加也不会被利用。
//
// 1) 任何非 GET 的 /api/* 请求一律拒绝(白名单只允许 GET)。
// 这就把 `POST /api/scores`、`POST /api/score/...`、`PUT /api/...` 等全部封死。
app.use('/api', (req, res, next) => {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return res.status(405).type('application/json').send(JSON.stringify({
error: 'method_not_allowed',
message: '本服务的积分写入只能由对局结算在服务端触发,不接受任何 HTTP 写入请求。'
}));
}
// 不挂 body parser,确保任何 JSON body 都不会被解析或使用
next();
});
function jwtVerifyOptions(token) {
const options = { algorithms: ['HS256'] };
const issuer = String(process.env.JWT_ISSUER || '').trim();
const audience = String(process.env.JWT_AUDIENCE || '').trim();
if (issuer) options.issuer = issuer;
if (audience) options.audience = audience;
// 兼容 issuer/audience 加固前已经签发、但签名仍由同一 JWT_SECRET
// 生成的旧 token。新 token 只要带有 iss/aud,仍然严格校验这两项。
// 这样不会把旧登录态误判成“签名不匹配”,用户也不必被强制清空全部会话。
if (token && (issuer || audience)) {
const claims = require('jsonwebtoken').decode(token);
if (!claims || typeof claims !== 'object') {
delete options.issuer;
delete options.audience;
} else {
if (issuer && !Object.prototype.hasOwnProperty.call(claims, 'iss')) delete options.issuer;
if (audience && !Object.prototype.hasOwnProperty.call(claims, 'aud')) delete options.audience;
}
}
return options;
}
function verifySsoToken(token) {
if (!token) throw new Error('missing token');
const jwt = require('jsonwebtoken');
return verifyCompatibleJwt(token, proto.JWT_SECRET, jwt);
}
function verifyCompatibleJwt(token, secret, jwt) {
// jwtVerifyOptions 已经对缺少 iss/aud 的旧 token 做了兼容:缺失时不启用
// 对应约束;但 token 明确携带错误 iss/aud 时必须让 verify 失败,不能再
// 退回到“只验签名”的路径,否则 JWT_ISSUER/JWT_AUDIENCE 形同虚设。
return jwt.verify(token, secret, jwtVerifyOptions(token));
}
// 2) /api/* 简单速率限制(按 IP,每 10 秒 30 次),抵御暴力探测/扫表。
const __apiHits = new Map();
app.use('/api', (req, res, next) => {
const ip = (req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress || '').toString().split(',')[0].trim();
const now = Date.now();
const winMs = 10 * 1000;
const max = 30;
const arr = (__apiHits.get(ip) || []).filter(t => now - t < winMs);
arr.push(now);
__apiHits.set(ip, arr);
// 顺手清理太久没活动的 IP,避免内存膨胀
if (__apiHits.size > 5000) {
for (const [k, v] of __apiHits) {
if (!v.length || now - v[v.length - 1] > 5 * 60 * 1000) __apiHits.delete(k);
}
}
if (arr.length > max) {
return res.status(429).type('application/json').send(JSON.stringify({ error: 'rate_limited' }));
}
next();
});
// HTTP:查询自己积分(需 ?token=JWT)
app.get('/api/score/me', (req, res) => {
const token = req.query.token || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
const gameType = normalizeGameType(req.query.gameType);
if (!token) return res.status(401).json({ error: 'no token' });
try {
const payload = verifySsoToken(token);
db.getUserScore(payload.uid, gameType).then(row => res.json(Object.assign({ gameType }, row || {}))).catch(() => res.status(500).json({ error: 'db_error' }));
} catch (e) {
return res.status(401).json({ error: 'invalid token' });
}
});
// HTTP:积分榜
app.get('/api/score/top', (req, res) => {
const requestedLimit = Number(req.query.limit || 20);
const limit = Number.isFinite(requestedLimit) ? Math.min(100, Math.max(1, Math.floor(requestedLimit))) : 20;
const gameType = normalizeGameType(req.query.gameType);
db.getTopScores(limit, gameType).then(rows => res.json(rows || [])).catch(() => res.json([]));
});
function historyViewerFromRequest(req) {
const viewer = {
uid: '',
username: '',
guestId: String(req.query.guestId || req.headers['x-cardroom-guest'] || '').trim().slice(0, 128),
};
const token = req.query.token || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
if (token) {
try {
const payload = verifySsoToken(token);
if (payload && payload.uid) {
viewer.uid = String(payload.uid);
viewer.username = String(payload.username || viewer.username || '').slice(0, 64);
}
} catch (e) {}
}
return viewer;
}
// 历史战局:公开房所有人可看;私密房只允许本局参与者查看。
app.get('/api/history', (req, res) => {
const requestedGame = String(req.query.gameType || '').trim();
const gameType = requestedGame && requestedGame !== 'all' ? normalizeGameType(requestedGame) : '';
db.listHistory({
gameType,
limit: req.query.limit,
offset: req.query.offset,
viewer: historyViewerFromRequest(req),
}).then(data => res.json(data)).catch(() => res.status(500).json({ error: 'history_error' }));
});
app.get('/api/history/:id', (req, res) => {
db.getHistory(req.params.id, historyViewerFromRequest(req)).then(record => {
if (!record) return res.status(404).json({ error: 'history_not_found' });
res.json(record);
}).catch(() => res.status(500).json({ error: 'history_error' }));
});
app.get('/api/site-stats', (req, res) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
db.getSiteStats().then(stats => res.json(publicSiteStats(stats))).catch(() => res.status(500).json({ error: 'stats_error' }));
});
// HTTP:SSO 配置健康检查。公开响应只返回布尔配置状态,不暴露密钥长度、
// 来源或可用于离线比对候选密钥的指纹;详细密钥核对请在服务器本地完成。
app.get('/api/sso/health', (req, res) => {
const s = proto.JWT_SECRET || '';
const isDefault = (s === 'change_this_in_production');
res.json({
hasSecret: !!s && !isDefault,
issuerConfigured: !!String(process.env.JWT_ISSUER || '').trim(),
audienceConfigured: !!String(process.env.JWT_AUDIENCE || '').trim(),
queryTokenAccepted: process.env.ALLOW_QUERY_TOKEN === '1' || process.env.ALLOW_QUERY_TOKEN === 'true',
warning: isDefault ? 'JWT_SECRET 未配置,使用占位串' : null
});
});
// 3) /api/* 兜底 404:任何未在上方显式声明的 /api/* GET 路径,统一返回 JSON 404。
// 例如:GET /api/scores、GET /api/admin 等。
app.all(/^\/api(\/.*)?$/, (req, res) => {
res.status(404).type('application/json').send(JSON.stringify({ error: 'not_found' }));
});
const BOT_NAMES = ['玉狐', '青龙', '白鹭', '墨鸢', '朱雀', '碧波', '苍髯'];
const GAME_TYPES = {
doudizhu: { label: '斗地主', seats: 3 },
guandan: { label: '掼蛋', seats: 4 },
mahjong: { label: '麻将', seats: 4 },
};
function normalizeGameType(gameType) {
return GAME_TYPES[gameType] ? gameType : 'doudizhu';
}
function createPositions(count) {
const positions = [];
for (let j = 0; j < count; j++) {
positions.push({
posId: j,
state: 0,
userName: '',
avatarUrl: '',
isBot: false,
pendingSocketId: '',
});
}
return positions;
}
function roomCode() {
return String(Math.floor(100000 + Math.random() * 900000));
}
function rankLabel(value) {
if (value === 11) return 'J';
if (value === 12) return 'Q';
if (value === 13) return 'K';
if (value === 14) return 'A';
if (value === 15) return '2';
return String(value);
}
function advanceRank(value, delta) {
const order = [15, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
const idx = Math.max(0, order.indexOf(value));
return order[Math.min(order.length - 1, idx + delta)];
}
function discuzAvatarUrl(uid) {
if (!uid) return '';
const base = String(process.env.DISCUZ_AVATAR_BASE || 'https://zwwx.club/uc_server/avatar.php?uid={uid}&size=middle');
if (!base) return '';
if (base.indexOf('{uid}') >= 0) return base.replace(/\{uid\}/g, encodeURIComponent(uid));
return base + (base.indexOf('?') >= 0 ? '&' : '?') + 'uid=' + encodeURIComponent(uid) + '&size=middle';
}
function sortByCard(cards) {
return cards.slice(0).sort((a, b) => {
if (a.value !== b.value) return a.value - b.value;
if (a.type !== b.type) return a.type - b.type;
return (a.deck || 0) - (b.deck || 0);
});
}
function groupCardsByValue(cards) {
const groups = {};
cards.forEach(card => {
if (!groups[card.value]) groups[card.value] = [];
groups[card.value].push(card);
});
Object.keys(groups).forEach(k => { groups[k] = sortByCard(groups[k]); });
return groups;
}
function pushCandidate(candidates, game, posId, cards) {
if (!cards || !cards.length) return;
const ret = game.validate(posId, cards);
if (ret && ret.status) {
candidates.push({ cards: cards.slice(0), ret });
}
}
function getGuandanCandidates(game, posId, leadOnly) {
const hand = sortByCard((game.getCardsByPosId(posId) || []).slice(0));
const groups = groupCardsByValue(hand);
const values = Object.keys(groups).map(Number).sort((a, b) => a - b);
const candidates = [];
values.forEach(v => pushCandidate(candidates, game, posId, [groups[v][0]]));
values.forEach(v => { if (groups[v].length >= 2) pushCandidate(candidates, game, posId, groups[v].slice(0, 2)); });
values.forEach(v => { if (groups[v].length >= 3) pushCandidate(candidates, game, posId, groups[v].slice(0, 3)); });
values.forEach(tv => {
if (groups[tv].length < 3) return;
values.forEach(pv => {
if (pv === tv || groups[pv].length < 2) return;
pushCandidate(candidates, game, posId, groups[tv].slice(0, 3).concat(groups[pv].slice(0, 2)));
});
});
for (let start = 3; start <= 10; start++) {
const seq = [];
for (let v = start; v < start + 5; v++) {
if (groups[v] && groups[v].length) seq.push(groups[v][0]);
}
if (seq.length === 5) pushCandidate(candidates, game, posId, seq);
}
for (let start = 3; start <= 12; start++) {
const pairs = [];
for (let v = start; v < start + 3; v++) {
if (groups[v] && groups[v].length >= 2) pairs.push(...groups[v].slice(0, 2));
}
if (pairs.length === 6) pushCandidate(candidates, game, posId, pairs);
}
values.forEach(v => {
if (groups[v].length >= 4) pushCandidate(candidates, game, posId, groups[v].slice(0, 4));
});
const jokers = hand.filter(c => c.value >= 16);
if (jokers.length >= 4) pushCandidate(candidates, game, posId, jokers.slice(0, 4));
return candidates
.filter(item => leadOnly || item.ret.len)
.sort((a, b) => {
const bombA = a.ret.bomb ? 1 : 0;
const bombB = b.ret.bomb ? 1 : 0;
if (bombA !== bombB) return bombA - bombB;
if (a.cards.length !== b.cards.length) return a.cards.length - b.cards.length;
return (a.ret.key || 0) - (b.ret.key || 0);
});
}
function evaluateDoudizhuHand(cards) {
const groups = groupCardsByValue(cards || []);
const values = Object.keys(groups).map(Number);
let power = 0;
values.forEach(v => {
const n = groups[v].length;
if (v >= 16) power += 4;
else if (v === 15) power += 3 * n;
else if (v >= 13) power += 1.5 * n;
if (n >= 4) power += 7;
else if (n === 3) power += 2;
});
if (groups[16] && groups[17]) power += 8;
return power;
}
function shouldCallDoudizhuScore(cards, ctxScore) {
if (!ctxScore || !ctxScore.length) return 0;
const maxScore = Math.max.apply(null, ctxScore);
const power = evaluateDoudizhuHand(cards);
if (power >= 22 && ctxScore.indexOf(3) >= 0) return 3;
if (power >= 16 && ctxScore.indexOf(2) >= 0) return 2;
if (power >= 11 && ctxScore.indexOf(1) >= 0) return 1;
return (power >= 20 && maxScore) ? maxScore : 0;
}
function time() {
return (new Date()).toLocaleTimeString();
}
var guid = function () {
var n = 0;
return function () {
return ++n;
}
}();
function GameServer(port) {
this.clients = [];
this.port = port;
this.desks = [];
this.gameDatas = {};
this.botTimers = {};
this.pauseTimers = {};
this.mahjongClaimTimers = {};
this.roundHistories = {};
this.nextRoomId = 1;
}
const proto = {
// JWT secret used to validate tokens issued by Discuz (or other auth provider)
// 优先级:环境变量 JWT_SECRET > sso-secret.txt 文件内容 > 占位串
JWT_SECRET: (function () {
if (process.env.JWT_SECRET) return process.env.JWT_SECRET;
try {
const fs = require('fs');
const path = require('path');
const f = path.join(__dirname, 'sso-secret.txt');
if (fs.existsSync(f)) {
const s = fs.readFileSync(f, 'utf8').trim();
if (s) return s;
}
} catch (e) {}
return 'change_this_in_production';
})(),
broadCastHouse(event, data, socket) {
socket = socket === undefined ? null : socket;
this.clients.forEach((client, index) => {
if (client.deskId === '') {
client.socket.emit(event, data);
}
});
},
refreshLobby(socket) {
const list = this.getLobbyRooms();
if (socket) {
socket.emit('REFRESH_LIST', list);
return;
}
this.broadCastHouse('REFRESH_LIST', list);
},
createRoom(options) {
options = options || {};
const gameType = normalizeGameType(options.gameType);
const meta = GAME_TYPES[gameType];
let code = roomCode();
while (this.desks.some(room => room.roomCode === code)) code = roomCode();
const room = {
deskId: this.nextRoomId++,
roomId: '',
roomCode: code,
state: 0,
gameType,
gameLabel: meta.label,
seatCount: meta.seats,
isPrivate: !!options.isPrivate,
ownerName: options.ownerName || '',
aiDifficulty: AiDifficulty.normalizeAiDifficulty(options.aiDifficulty),
pauseInfo: null,
// 断线回归凭据只保存在服务端内存中,不下发给客户端;
// 玩家/观众在短窗口内可以用原身份恢复原桌状态。
reconnectSlots: {},
createdAt: Date.now(),
positions: createPositions(meta.seats),
guandanLevelRank: 15,
guandanLevelLabel: '2',
};
room.roomId = room.deskId;
this.desks.push(room);
return room;
},
getLobbyRooms() {
return this.desks
.filter(room => !room.isPrivate)
.map(room => ({
deskId: room.deskId,
roomId: room.roomId,
roomCode: room.roomCode,
state: room.state,
gameType: room.gameType,
gameLabel: room.gameLabel,
seatCount: room.seatCount,
isPrivate: room.isPrivate,
ownerName: room.ownerName,
aiDifficulty: room.aiDifficulty,
aiDifficultyLabel: AiDifficulty.aiDifficultyLabel(room.aiDifficulty),
botCount: room.positions.filter(pos => pos.isBot).length,
paused: !!room.pauseInfo,
pauseExpiresAt: room.pauseInfo ? room.pauseInfo.expiresAt : 0,
guandanLevelLabel: room.guandanLevelLabel,
positions: room.positions.map(p => ({
posId: p.posId,
state: p.state,
userName: p.userName,
avatarUrl: p.avatarUrl || '',
isBot: !!p.isBot,
})),
}));
},
findRoomByCode(code) {
code = String(code || '').trim();
return this.desks.find(room => room.roomCode === code || String(room.deskId) === code) || null;
},
getFirstOpenPos(room) {
if (!room) return null;
return room.positions.find(pos => pos.state === 0 && !pos.pendingSocketId && !this.getPlayerReconnectSlot(room, pos.posId)) || null;
},
getRandomBotPos(room) {
if (!room) return null;
const bots = room.positions.filter(pos => pos.isBot && !pos.pendingSocketId);
if (!bots.length) return null;
return bots[Math.floor(Math.random() * bots.length)];
},
reservePosition(room, posId, socket) {
if (!room || !socket) return;
const pos = this.getPosition(room, posId);
if (!pos || (pos.state !== 0 && !pos.isBot) || pos.pendingSocketId) return;
pos.pendingSocketId = socket.id;
setTimeout(() => {
if (pos.pendingSocketId === socket.id && (pos.state === 0 || pos.isBot)) {
pos.pendingSocketId = '';
}
}, 5000);
},
reconnectIdentity(client) {
if (!client) return '';
if (client.uid) return 'uid:' + String(client.uid);
if (client.guestId) return 'guest:' + String(client.guestId);
return 'name:' + String(client.userName || '');
},
reconnectSlotMatches(slot, client) {
if (!slot || !client) return false;
if (slot.uid) return String(client.uid || '') === String(slot.uid);
if (slot.guestId) return String(client.guestId || '') === String(slot.guestId);
return !!slot.userName && String(client.userName || '') === String(slot.userName);
},
getPlayerReconnectSlot(room, posId) {
if (!room || !room.reconnectSlots) return null;
const key = 'player:' + String(Number(posId));
const slot = room.reconnectSlots[key];
if (!slot) return null;
if (Number(slot.expiresAt || 0) <= Date.now()) {
delete room.reconnectSlots[key];
return null;
}
return slot;
},
clearPlayerReconnectSlot(room, posId) {
if (!room || !room.reconnectSlots) return;
delete room.reconnectSlots['player:' + String(Number(posId))];
},
findSpectatorReconnectSlot(room, client) {
if (!room || !room.reconnectSlots || !client) return null;
const now = Date.now();
for (const key of Object.keys(room.reconnectSlots)) {
const slot = room.reconnectSlots[key];
if (!slot || slot.kind !== 'spectator') continue;
if (Number(slot.expiresAt || 0) <= now) {
delete room.reconnectSlots[key];
continue;
}
if (this.reconnectSlotMatches(slot, client)) return { key, slot };
}
return null;
},
pruneReconnectSlots(room) {
if (!room || !room.reconnectSlots) return;
const now = Date.now();
Object.keys(room.reconnectSlots).forEach(key => {
const slot = room.reconnectSlots[key];
if (!slot || Number(slot.expiresAt || 0) <= now) delete room.reconnectSlots[key];
});
},
hasActivePlayerReconnectSlot(room) {
this.pruneReconnectSlots(room);
return !!(room && room.reconnectSlots && Object.keys(room.reconnectSlots).some(key => key.indexOf('player:') === 0));
},
rememberReconnectSlot(deskId, posId, client, kind) {
const room = this.getDesk(deskId);
if (!room || !client) return null;
const slotKind = kind === 'spectator' ? 'spectator' : 'player';
const expiresAt = Date.now() + GAME_PAUSE_GRACE_MS;
const slot = {
kind: slotKind,
posId: slotKind === 'player' ? Number(posId) : 'spec',
uid: client.uid ? String(client.uid) : '',
guestId: client.guestId ? String(client.guestId) : '',
userName: String(client.userName || ''),
avatarUrl: client.avatarUrl || '',
expiresAt,
};
const key = slotKind === 'player'
? 'player:' + String(Number(posId))
: 'spectator:' + this.reconnectIdentity(client);
room.reconnectSlots[key] = slot;
const timer = setTimeout(() => {
const currentRoom = this.getDesk(deskId);
if (!currentRoom || !currentRoom.reconnectSlots || currentRoom.reconnectSlots[key] !== slot) return;
if (Number(slot.expiresAt || 0) <= Date.now()) {
delete currentRoom.reconnectSlots[key];
this.refreshLobby();
this.cleanupRoomIfEmpty(deskId);
}
}, GAME_PAUSE_GRACE_MS + 150);
if (timer && typeof timer.unref === 'function') timer.unref();
return slot;
},
cleanupRoomIfEmpty(deskId) {
const room = this.getDesk(deskId);
if (!room) return;
this.pruneReconnectSlots(room);
const hasHuman = this.clients.some(c => c.deskId === deskId && c.posId !== 'spec');
if (hasHuman) return;
// 对局暂停窗口内保留房间和牌局,给房主/回归玩家一分钟处理时间。
if (room.pauseInfo) return;
// 等待阶段没有 pauseInfo,也要给刚断线的玩家留下回归窗口。
if (this.hasActivePlayerReconnectSlot(room)) return;
this.removeAllBots(deskId);
this.clearBotTimer(deskId);
this.clearPauseTimer(deskId);
this.clearMahjongClaimTimer(deskId);
if (this.gameDatas[deskId]) {
this.gameDatas[deskId].init();
delete this.gameDatas[deskId];
}
const index = this.desks.findIndex(r => r.deskId === deskId);
if (index >= 0) this.desks.splice(index, 1);
this.refreshLobby();
},
applyGuandanResult(deskId, result) {
const room = this.getDesk(deskId);
if (!room || room.gameType !== 'guandan' || !result) return;
room.guandanLevelRank = advanceRank(room.guandanLevelRank || 15, result.rankDelta || 1);
room.guandanLevelLabel = rankLabel(room.guandanLevelRank);
result.nextLevelRank = room.guandanLevelRank;
result.nextLevelLabel = room.guandanLevelLabel;
},
broadCastRoom(event, deskId, data, socket) {
socket = socket === undefined ? null : socket;
this.clients.forEach((client, index) => {
if (client.deskId === deskId && client.socket !== socket) {
client.socket.emit(event, data);
}
});
},
getDesk(deskId) {
for (let i = 0, len = this.desks.length; i < len; i++) {
let desk = this.desks[i];
if (desk.deskId == deskId || desk.roomCode == deskId) {
return desk;
}
}
return null;
},
getOtherPosInfo(deskId, posId) {
let desk = this.getDesk(deskId);
if (desk) {
let positions = desk.positions;
return positions.filter(function (pos) {
return pos.posId !== posId;
})
}
return [];
},
updateOtherPosStatus(deskId, posId, state) {
let desk = this.getDesk(deskId);
if (desk) {
let positions = desk.positions;
positions.forEach(function (pos) {
if (pos.posId !== posId) {
pos.state = state;
}
}.bind(this));
}
},
getPosition(desk, posId) {
for (let i = 0, len = desk.positions.length; i < len; i++) {
let position = desk.positions[i];
if (position.posId == posId) {
return position;
}
}
return null;
},
isEmptyPos(deskId, posId) {
const desk = this.getDesk(deskId);
if (!desk) {
return false;
}
const position = this.getPosition(desk, posId);
return position && position.state === 0;
},
updatePosStatus(deskId, posId, state, userName, avatarUrl) {
const desk = this.getDesk(deskId);
if (desk) {
const position = this.getPosition(desk, posId);
if (position) {
position.state = state;
if (userName === '' || userName) {
position.userName = userName;
}
if (avatarUrl === '' || avatarUrl) {
position.avatarUrl = avatarUrl;
}
if (state === 0) {
position.avatarUrl = '';
}
}
}
},
updateRoomStatus(deskId, state) {
const desk = this.getDesk(deskId);
if (desk) {
desk.state = state;
return true;
}
return false;
},
removeClient(socket) {
for (let i = 0, len = this.clients.length; i < len; i++) {
if (this.clients[i].socket === socket) {
this.clients.splice(i, 1);
break;
}
}
},
addClient(socket, data) {
this.clients.push({ userName: data.userName, uid: data.uid || 0, guestId: data.guestId || '', avatarUrl: data.avatarUrl || '', socket: socket, deskId: '', posId: '' });
},
getClient(socket) {
for (let i = 0, len = this.clients.length; i < len; i++) {
let client = this.clients[i];
if (client.socket == socket) {
return client;
}
}
return null;
},
updateClientState(socket, deskId, posId) {
let client = this.getClient(socket)
if (client) {
client.deskId = deskId !== undefined ? deskId : '';
client.posId = posId !== undefined ? posId : '';
}
},
getUserName(socket) {
for (let i = 0, len = this.clients.length; i < len; i++) {
if (this.clients[i].socket == socket) {
return this.clients[i].userName;
}
}
return null;
},
getUserAvatar(socket) {
for (let i = 0, len = this.clients.length; i < len; i++) {
if (this.clients[i].socket == socket) {
return this.clients[i].avatarUrl || '';
}
}
return '';
},
checkUserName(userName) {
for (let i = 0, len = this.clients.length; i < len; i++) {
if (this.clients[i].userName === userName) {
return false;
}
}
return true;
},
checkPrepareAll(deskId) {
const desk = this.getDesk(deskId);
if (desk) {
const positions = desk.positions;
for (let i = 0; i < positions.length; i++) {
if (positions[i].state !== 2) {
return false;
}
}
return true;
}
return false;
},
createRoundHistory(deskId) {
const room = this.getDesk(deskId);
if (!room) return;
const players = room.positions.filter(p => p.state > 0).map(p => {
const client = this.clients.find(c => c.deskId === deskId && Number(c.posId) === Number(p.posId));
return {
posId: Number(p.posId),
uid: client && client.uid ? String(client.uid) : '',
guestId: client && client.guestId ? String(client.guestId) : '',
username: String((client && client.userName) || p.userName || `玩家${Number(p.posId) + 1}`),
isBot: !!p.isBot,
};
});
this.roundHistories[deskId] = {
roomCode: room.roomCode,
deskId: room.deskId,
gameType: room.gameType,
gameLabel: room.gameLabel,
isPrivate: !!room.isPrivate,
aiDifficulty: room.aiDifficulty,
aiDifficultyLabel: AiDifficulty.aiDifficultyLabel(room.aiDifficulty),
startedAt: Date.now(),
endedAt: 0,
players,
moves: [],
result: {},
};
db.recordSiteStat('game_starts', 1, room.gameType);
db.recordSiteStat('player_rounds', players.filter(p => !p.isBot).length, room.gameType);
},
recordRoundMove(deskId, move) {
const record = this.roundHistories[deskId];
if (!record || !move) return;
const copy = Object.assign({}, move, {
seq: record.moves.length + 1,
at: Date.now(),
});
if (Array.isArray(move.cards)) {
copy.cards = move.cards.map(card => ({ value: Number(card.value), type: Number(card.type), ...(card.deck == null ? {} : { deck: Number(card.deck) }) }));
}
if (move.card) {
copy.card = { value: Number(move.card.value), type: Number(move.card.type), ...(move.card.deck == null ? {} : { deck: Number(move.card.deck) }) };
}
if (move.meld && Array.isArray(move.meld.cards)) {
copy.meld = Object.assign({}, move.meld, { cards: move.meld.cards.map(card => ({ value: Number(card.value), type: Number(card.type), ...(card.deck == null ? {} : { deck: Number(card.deck) }) })) });
}
record.moves.push(copy);
},
finishRoundHistory(deskId, result) {
const record = this.roundHistories[deskId];
if (!record) return;
record.endedAt = Date.now();
record.result = result || {};
const gameType = record.gameType;
delete this.roundHistories[deskId];
db.recordSiteStat('games_completed', 1, gameType);
db.saveHistory(record).catch(err => console.error('[history] 保存失败:', err && err.message));
},
startGame(deskId) {
const room = this.getDesk(deskId);
if (!room) return;
room.pauseInfo = null;
this.clearPauseTimer(deskId);
if (this.gameDatas[deskId] === undefined) {
this.gameDatas[deskId] = room.gameType === 'guandan'
? new GuandanGame({ levelRank: room.guandanLevelRank || 15 })
: (room.gameType === 'mahjong' ? new MahjongGame() : new Game());
}
const game = this.gameDatas[deskId];
game.init();
const cards = game.start().getCards();
this.createRoundHistory(deskId);
this.updateRoomStatus(deskId, 2);
this.refreshLobby();
if (room.gameType === 'guandan') {
this.broadCastRoom('GAME_START', deskId, {
cards,
gameType: room.gameType,
aiDifficulty: room.aiDifficulty,
aiDifficultyLabel: AiDifficulty.aiDifficultyLabel(room.aiDifficulty),
ctxPos: game.getContextPosId(),
levelLabel: game.getLevelLabel(),
levelRank: game.levelRank,
});
this.broadCastRoom('CTX_PLAY_CHANGE', deskId, {
ctxData: { len: 0, key: '', type: '', cards: [], posId: game.getContextPosId() },
posId: game.getContextPosId(),
timeout: GUANDAN_PLAY_TIMEOUT,
isPass: false,
trickReset: true,
});
this.scheduleBotAction(deskId);
} else if (room.gameType === 'mahjong') {
this.broadCastRoom('GAME_START', deskId, {
cards,
gameType: room.gameType,
aiDifficulty: room.aiDifficulty,
aiDifficultyLabel: AiDifficulty.aiDifficultyLabel(room.aiDifficulty),
ctxPos: game.getContextPosId(),
mahjong: game.getPublicState(),
});
this.broadcastMahjongState(deskId, { timeout: MAHJONG_PLAY_TIMEOUT });
this.scheduleBotAction(deskId);
} else {
this.broadCastRoom('GAME_START', deskId, {
cards,
gameType: room.gameType,
aiDifficulty: room.aiDifficulty,
aiDifficultyLabel: AiDifficulty.aiDifficultyLabel(room.aiDifficulty),
});
this.broadCastRoom('CTX_USER_CHANGE', deskId, { ctxPos: game.getContextPosId(), ctxScore: game.getContextScore(), timeout: DOU_DIZHU_STEP_TIMEOUT });
this.scheduleBotAction(deskId);
}
},
// ===== AI 机器人 =====
hasHumanAtDesk(deskId) {
return this.clients.some(c => c.deskId === deskId && c.posId !== 'spec');
},
seatBot(deskId, posId) {
const desk = this.getDesk(deskId);
if (!desk) return;
const pos = this.getPosition(desk, posId);
if (!pos) return;
// AI 接管后,原玩家的回归凭据立即失效,避免同一座位被二次恢复。
this.clearPlayerReconnectSlot(desk, posId);
const used = desk.positions.map(x => String(x.userName || '').replace(/\s*〔AI〕$/, '')).filter(Boolean);
const name = (BOT_NAMES.find(n => !used.includes(n)) || '清客') + ' 〔AI〕';
pos.state = 2; pos.userName = name; pos.avatarUrl = ''; pos.isBot = true;
this.broadCastRoom('POS_STATUS_CHANGE', deskId, { posId, state: 2, userName: name, avatarUrl: '', isBot: true });
this.broadCastHouse('STATUS_CHANGE', { deskId, posId, state: 2 });
},
removeBot(deskId, posId) {
const desk = this.getDesk(deskId);
if (!desk) return null;
const pos = this.getPosition(desk, posId);
if (!pos || !pos.isBot) return null;
const name = pos.userName;
pos.state = 0; pos.userName = ''; pos.avatarUrl = ''; pos.isBot = false;
this.broadCastRoom('POS_STATUS_CHANGE', deskId, { posId, state: 0, userName: '', avatarUrl: '' });
this.broadCastHouse('STATUS_CHANGE', { deskId, posId, state: 0 });
return name;
},
removeAllBots(deskId) {
const desk = this.getDesk(deskId);
if (!desk) return;
desk.positions.forEach(p => { if (p.isBot) this.removeBot(deskId, p.posId); });
},
isBotPos(deskId, posId) {
const desk = this.getDesk(deskId);
if (!desk) return false;
const p = this.getPosition(desk, posId);
return !!(p && p.isBot);
},
handleDisconnectedClient(client) {
if (!client || client._disconnectHandled) return;
client._disconnectHandled = true;
const { deskId, posId } = client;
if (!deskId) return;
const userName = client.userName || '';
// 观战者不占座位、不暂停牌局,但保留短暂的原桌回归窗口,
// 私密房也只能由原观战身份恢复。
if (posId === 'spec') {
this.rememberReconnectSlot(deskId, 'spec', client, 'spectator');
this.broadCastRoom('USER_MESSAGE', deskId, {
type: 'SYS', posId: 'spec', msg: `观众[${userName || '观众'}]离开房间`, id: guid(), time: time()
});
console.log('观战者断开连接 %s', time());
return;
}
const desk = this.getDesk(deskId);
const game = this.gameDatas[deskId];
const inProgress = !!(game && game.getStatus && game.getStatus() > 0 && game.getStatus() < 3);
// 先记住原身份,再按原有逻辑释放显示座位;RESUME_ROOM 会在窗口内重新占回它。
this.rememberReconnectSlot(deskId, posId, client, 'player');
this.updatePosStatus(deskId, posId, 0, '');
this.broadCastRoom('POS_STATUS_CHANGE', deskId, {
posId, state: 0, userName: '', avatarUrl: '', reconnecting: true
}, client.socket);
this.broadCastHouse('STATUS_CHANGE', { deskId, posId, state: 0 });
if (inProgress) {
this.updateOtherPosStatus(deskId, posId, 1);
this.broadCastRoom('POS_STATUS_RESET', deskId, { pos: this.getOtherPosInfo(deskId, posId), state: 1 }, client.socket);
this.pauseGameForMissingPlayer(deskId, posId, userName || '玩家');
} else {
this.updateRoomStatus(deskId, 0);