-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhangman.js
817 lines (686 loc) · 21.8 KB
/
hangman.js
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
'use strict';
const fs = require('fs');
const config = require('./config');
const bot = require('./bot.' + config.bot)(config.hangmanToken);
const multiplayer = require('./multiplayer')();
const resource = require('./hangman.resource');
const play = require('./hangman.play');
const fd = fs.openSync('log_hangman', 'a');
const log = (head, body) => {
fs.write(fd, '[' + Date() + '] ' + head + ' ' + body + '\n', () => {
// nothing
});
};
const event = (handler, atIndex) => {
return (msg, match) => {
if (!match[atIndex] || match[atIndex] === '@' + config.hangmanUsername) {
log(
msg.chat.id + '@' + (msg.chat.username || '')
+ ':' + msg.from.id + '@' + (msg.from.username || ''),
match[0]
);
// notice: take care of the inline query event
if (!config.ban[msg.from.id]) {
handler(msg, match);
}
}
};
};
const playerLine = (player) => {
if (player) {
return '\n'
+ '\n'
+ (
player.username
? '@' + player.username
: player.first_name
) + ' 轮到你啦';
}
return '';
};
const playerInfo = (list) => {
let info = '玩家列表:\n';
let total = 0;
for (let i = 0; i < list.length; i += 1) {
info += (list[i].username || list[i].first_name) + '\n';
total += 1;
}
info += '(总共' + total + '人)';
return info;
};
const playerUpdate = (msg, list) => {
if (list.update) {
list.update = () => {
playerUpdate(msg, list);
};
return;
}
list.update = () => {
// nothing
};
bot.editMessageText(
playerInfo(list) + '\n'
+ '\n'
+ '/hang@' + config.hangmanUsername + ' 开始新游戏',
{
chat_id: msg.chat.id,
message_id: msg.message_id,
reply_to_message_id: msg.reply_to_message.message_id,
reply_markup: {
inline_keyboard: [[{
text: '加入',
callback_data: JSON.stringify(['join']),
}, {
text: '离开',
callback_data: JSON.stringify(['flee']),
}, {
text: '清空',
callback_data: JSON.stringify(['clear']),
}]],
},
}
).finally(() => {
setTimeout(() => {
const update = list.update;
delete list.update;
update();
}, config.multiplayerUpdateDelay);
});
};
const messageUpdate = (msg, game, win) => {
if (game.update) {
game.update = () => {
messageUpdate(msg, game, win);
};
return;
}
game.update = () => {
// nothing
};
// dict info
const dictInfo = game.dictSettings()[0];
// keyboard
const matrix = [];
const lineCount = Math.ceil(game.keyboard.length / 8);
const keyPerLine = Math.floor(game.keyboard.length / lineCount);
const keyRemain = game.keyboard.length - keyPerLine * lineCount;
for (let i = 0; i < lineCount; i += 1) {
matrix.push([]);
const begin = i * keyPerLine + Math.min(i, keyRemain);
const end = (i + 1) * keyPerLine + Math.min(i + 1, keyRemain);
for (let j = begin; j < end; j += 1) {
matrix[i].push({
text: dictInfo.upperCase
? (game.keyboard[j] || '⨯').toLocaleUpperCase()
: game.keyboard[j] || '⨯',
callback_data: JSON.stringify(['guess', j]),
});
}
}
// game history
let totCorrect = 0;
let totError = 0;
let lives = 9;
let first = true;
let text = '';
const createFace = (guess, correct) => {
const face = [' ', 'w', '・'];
if (lives < 3 && lives >= 0) {
face[0] = '!';
} else if (lives < 0 && lives >= -3) {
face[0] = '*';
}
if (lives >= 0) {
if (guess && !correct) {
face[1] = '_';
}
} else if (correct) {
face[1] = 'A';
} else {
face[1] = '皿';
}
if (win) {
if (totError === 0) {
face[2] = '≖';
} else if (totError === 9) {
face[0] = '!';
face[2] = '☆';
} else if (game.history.length === game.keyboard.length) {
face[0] = '*';
face[2] = '◉';
}
}
return face;
};
const createLMR = (guess, correct) => {
const lmr = [' ', '||', ' '];
if (!guess) {
lmr[1] = 'ひ';
}
if (first) {
lmr[0] = '╰';
lmr[2] = '╯';
}
if (lives === -1 && !correct) {
lmr[0] = '✄';
if (guess) {
lmr[1] = '██';
}
}
return lmr;
};
const appendLine = (guess, correct) => {
if (!correct) {
lives -= 1;
}
const face = createFace(guess, correct);
text += '( ' + face[0] + face[2] + face[1] + face[2] + ')';
const lmr = createLMR(guess, correct);
text += lmr[0] + lmr[1] + lmr[2];
if (guess) {
text += ' [ ' + (
dictInfo.upperCase
? guess.toLocaleUpperCase()
: guess
) + ' ]';
}
text += '\n';
first = false;
};
for (const i in game.history) {
if (game.history[i][2]) {
totCorrect += 1;
} else {
totError += 1;
}
}
for (const i in game.history) {
appendLine(game.history[i][1], game.history[i][2]);
}
appendLine(null, null);
// game info
let hint = null;
let endText = null;
if (win) {
hint = (
dictInfo.upperCase
? game.answer.toLocaleUpperCase()
: game.answer
).split('\x01').join('.');
endText = '\n';
if (totError < 9) {
endText += '回答正确~撒花~';
} else if (totError === 9) {
endText += '回答正确~真是好险呢~';
} else if (game.history.length === game.keyboard.length) {
endText += '卧…卧槽?!';
} else {
endText += '虽然 JJ 已经被 bot 切掉了,但是回答正确~';
}
endText += '\n'
+ '\n'
+ '正确 ' + totCorrect + ' / 错误 ' + totError + '\n'
+ '键盘消耗率 ' + Math.round(100 * totError / (game.keyboard.length - totCorrect) | 0) + '%\n'
+ '\n'
+ '统计:\n';
const stat = {};
for (const i in game.history) {
stat[game.history[i][0]] = stat[game.history[i][0]] || [0, 0];
if (game.history[i][2]) {
stat[game.history[i][0]][1] += 1;
} else {
stat[game.history[i][0]][0] += 1;
}
}
for (const i in stat) {
const name = game.nameMap()[i]
.replace('&', '&')
.replace('<', '<')
.replace('>', '>');
endText += name + ' - 正确 ' + stat[i][1] + ' / 错误 ' + stat[i][0] + '\n';
}
const lastName = game.nameMap()[game.history[game.history.length - 1][0]]
.replace('&', '&')
.replace('<', '<')
.replace('>', '>');
endText += '\n'
+ lastName + ' 猜对啦!\n'
+ '\n';
if (dictInfo.url) {
endText += '所以…<a href="' + encodeURI(dictInfo.url + game.answer) + '">' + hint + '是什么呢?好吃吗?</a>\n'
+ '\n';
}
endText += '/hang@' + config.hangmanUsername + ' 开始新游戏\n'
+ '/diao@' + config.hangmanUsername + ' 多人模式';
} else {
hint = (
dictInfo.upperCase
? game.hint.toLocaleUpperCase()
: game.hint
).split('\x01').join('.');
endText = playerLine(multiplayer.get(msg.chat.id));
}
bot.editMessageText(
'<pre>'
+ text + '\n'
+ '[ ' + dictInfo.title + ' - ' + game.dictSettings()[1] + ' ]\n'
+ '[ ' + hint + ' ]\n'
+ '[ 剩余生命 ' + (9 - totError) + ' ]\n'
+ '</pre>' + endText,
{
chat_id: msg.chat.id,
message_id: msg.message_id,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: matrix,
},
}
).finally(() => {
setTimeout(() => {
const update = game.update;
delete game.update;
update();
}, config.hangmanUpdateDelay);
});
};
bot.onText(/^\/hang(@\w+)?(?: (\d+))?$/, event((msg, match) => {
const lines = [];
// note: telegram's limit
const keyboardSize = Math.min(parseInt(match[2], 10) || 32, 100);
for (const i in config.hangmanDict) {
const dictInfo = config.hangmanDict[i];
lines.push([{
text: dictInfo.title,
callback_data: JSON.stringify(['dict', dictInfo.id, null, keyboardSize]),
}]);
if (dictInfo.limit.length) {
const line = [];
for (const j in dictInfo.limit) {
line.push({
text: dictInfo.limit[j],
callback_data: JSON.stringify(['dict', dictInfo.id, dictInfo.limit[j], keyboardSize]),
});
}
lines.push(line);
}
}
bot.sendMessage(
msg.chat.id,
'请选择词典\n'
+ '\n'
+ '数字表示的是缩减版哦',
{
reply_to_message_id: msg.message_id,
reply_markup: {
inline_keyboard: lines,
},
}
);
}, 1));
bot.onText(/^\/diao(@\w+)?$/, event((msg, match) => {
multiplayer.add(
msg.chat.id,
msg.from,
(list) => {
// added
bot.sendMessage(
msg.chat.id,
'一大波玩家正在赶来……',
{
reply_to_message_id: msg.message_id,
reply_markup: {
inline_keyboard: [[{
text: '加入',
callback_data: JSON.stringify(['join']),
}, {
text: '离开',
callback_data: JSON.stringify(['flee']),
}, {
text: '清空',
callback_data: JSON.stringify(['clear']),
}]],
},
}
).then((sentmsg) => {
playerUpdate(
sentmsg,
list
);
});
},
(list) => {
// player exist
bot.sendMessage(
msg.chat.id,
'一大波玩家正在赶来……',
{
reply_to_message_id: msg.message_id,
reply_markup: {
inline_keyboard: [[{
text: '加入',
callback_data: JSON.stringify(['join']),
}, {
text: '离开',
callback_data: JSON.stringify(['flee']),
}, {
text: '清空',
callback_data: JSON.stringify(['clear']),
}]],
},
}
).then((sentmsg) => {
playerUpdate(
sentmsg,
list
);
});
},
(list) => {
// list full
bot.sendMessage(
msg.chat.id,
'玩家列表满啦',
{
reply_to_message_id: msg.message_id,
}
);
}
);
}, 1));
bot.onText(/^\/help(@\w+)?$/, event((msg, match) => {
bot.sendMessage(
msg.chat.id,
'猜单词游戏\n'
+ '\n'
+ '命令列表:\n'
+ '/hang 开始新游戏\n'
+ '/hang <keyboard size> 指定键盘大小开始新游戏\n'
+ '/diao 多人模式\n'
+ '/help 显示帮助\n'
+ '/status 查看 bot 状态\n'
+ '\n'
+ '备注:\n'
+ 'inline 查询将触发喵喵模式\n'
+ '\n'
+ '源码:\n'
+ 'https://github.com/hczhcz/telegram-kuso-bots'
);
}, 1));
bot.onText(/^\/status(@\w+)?$/, event((msg, match) => {
bot.sendMessage(
msg.chat.id,
'当前活跃游戏 ' + play.count(),
{
reply_to_message_id: msg.message_id,
}
);
}, 1));
bot.on('callback_query', (query) => {
const msg = query.message;
if (!msg || config.ban[query.from.id]) {
return;
}
const info = JSON.parse(query.data);
if (info[0] === 'join') {
log(
msg.chat.id + '@' + (msg.chat.username || '')
+ ':callback:' + query.from.id + '@' + (query.from.username || ''),
'join'
);
multiplayer.add(
msg.chat.id,
query.from,
(list) => {
// added
playerUpdate(
msg,
list
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
(list) => {
// player exist
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
(list) => {
// list full
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
} else if (info[0] === 'flee') {
log(
msg.chat.id + '@' + (msg.chat.username || '')
+ ':callback:' + query.from.id + '@' + (query.from.username || ''),
'flee'
);
multiplayer.remove(
msg.chat.id,
query.from,
(list) => {
// removed
playerUpdate(
msg,
list
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
() => {
// player not exist
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
} else if (info[0] === 'clear') {
log(
msg.chat.id + '@' + (msg.chat.username || '')
+ ':callback:' + query.from.id + '@' + (query.from.username || ''),
'clear'
);
multiplayer.clear(
msg.chat.id,
() => {
// cleared
playerUpdate(
msg,
[]
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
() => {
// not multiplayer
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
} else if (info[0] === 'dict') {
if (typeof info[2] !== 'number' && info[2] !== null || typeof info[3] !== 'number') {
throw Error(JSON.stringify(query));
}
log(
msg.chat.id + '_' + msg.message_id + '@' + (msg.chat.username || '')
+ ':callback:' + query.from.id + '@' + (query.from.username || ''),
'dict ' + info[1] + ' ' + info[2] + ' ' + info[3]
);
resource.load(
info[1],
info[2],
(dictInfo, dict) => {
// loaded
play.init(
msg.chat.id + '_' + msg.message_id,
query.from.id,
dict,
info[3],
(game) => {
// game init
game.dictSettings = () => {
return [dictInfo, info[2] || dict.list.length];
};
const nameMap = {};
game.nameMap = () => {
return nameMap;
};
game.nameMap()[msg.from.id] = msg.from.username || msg.from.first_name;
messageUpdate(
msg,
game,
false
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
() => {
// game exist
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
},
() => {
// not valid
// never reach
throw Error(JSON.stringify(query));
}
);
} else if (info[0] === 'guess') {
if (typeof info[1] !== 'number') {
throw Error(JSON.stringify(query));
}
log(
msg.chat.id + '_' + msg.message_id + '@' + (msg.chat.username || '')
+ ':callback:' + query.from.id + '@' + (query.from.username || ''),
'guess ' + info[1]
);
multiplayer.verify(
msg.chat.id,
query.from,
() => {
// valid
play.click(
msg.chat.id + '_' + msg.message_id,
query.from.id,
info[1],
(game) => {
// game continue
game.nameMap()[query.from.id] = query.from.username || query.from.first_name;
messageUpdate(
msg,
game,
false
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
(game) => {
// game win
game.nameMap()[query.from.id] = query.from.username || query.from.first_name;
fs.write(fd, JSON.stringify(game) + '\n', () => {
// nothing
});
messageUpdate(
msg,
game,
true
);
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
() => {
// not valid
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
},
() => {
// game not exist
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
},
() => {
// not valid
bot.answerCallbackQuery(query.id).catch((err) => {
// nothing
});
}
);
}
});
bot.on('inline_query', (query) => {
if (!query.query) {
bot.answerInlineQuery(
query.id,
[],
{
cache_time: 0,
is_personal: true,
}
);
} else if (config.ban[query.from.id]) {
bot.answerInlineQuery(
query.id,
[{
type: 'article',
id: 'banned',
title: 'hang喵',
input_message_content: {
message_text: '该用户因存在恶意使用 bot 的报告,已被列入黑名单',
},
}],
{
cache_time: 0,
is_personal: true,
}
);
} else {
bot.answerInlineQuery(
query.id,
[{
type: 'article',
id: 'playmeow',
title: 'hang喵',
input_message_content: {
message_text: (
query.from.username
? '@' + query.from.username
: query.from.first_name
) + ' 喵喵模式已装载!\n'
+ '\n'
+ '/hang@' + config.hangmanUsername + ' 开始新游戏\n'
+ '/diao@' + config.hangmanUsername + ' 多人模式',
},
}],
{
cache_time: 0,
is_personal: true,
}
);
}
});
bot.on('chosen_inline_result', (chosen) => {
log(
'inline:' + chosen.from.id + '@' + (chosen.from.username || ''),
chosen.result_id + ' ' + chosen.query
);
if (chosen.result_id === 'playmeow') {
play.meowInit(chosen.from.id, chosen.query);
}
});