forked from hczhcz/telegram-kuso-bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.core.js
95 lines (74 loc) · 1.86 KB
/
hangman.core.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
'use strict';
const GraphemeSplitter = require('grapheme-splitter');
const splitter = new GraphemeSplitter();
const length = (str) => {
const arr = splitter.splitGraphemes(str);
return arr.length;
};
const dictInit = () => {
return {
list: [],
charset: {},
charsetSize: 0,
};
};
const dictAdd = (dict, str) => {
dict.list.push(str);
const arr = splitter.splitGraphemes(str);
for (const i in arr) {
if (!dict.charset[arr[i]]) {
dict.charset[arr[i]] = true;
dict.charsetSize += 1;
}
}
};
const dictSelect = (dict) => {
return dict.list[Math.floor(Math.random() * dict.list.length)];
};
const makeKeyboard = (dict, str, size) => {
const arr = splitter.splitGraphemes(str);
const keyboard = {};
let keyboardSize = 0;
let remain = dict.charsetSize;
for (const i in arr) {
if (!keyboard[arr[i]]) {
keyboard[arr[i]] = true;
keyboardSize += 1;
if (dict.charset[arr[i]]) {
remain -= 1;
}
}
}
for (const i in dict.charset) {
if (!keyboard[i]) {
if (Math.random() * remain < size - keyboardSize) {
keyboard[i] = true;
keyboardSize += 1;
}
remain -= 1;
}
}
if (remain) {
// never reach
throw Error();
}
return Object.keys(keyboard).sort();
};
const guess = (str, strH, char) => {
const arr = splitter.splitGraphemes(str);
const arrH = splitter.splitGraphemes(strH);
for (const i in arr) {
if (arr[i] === char) {
arrH[i] = char;
}
}
return arrH.join('');
};
module.exports = {
length: length,
dictInit: dictInit,
dictAdd: dictAdd,
dictSelect: dictSelect,
makeKeyboard: makeKeyboard,
guess: guess,
};