-
Notifications
You must be signed in to change notification settings - Fork 13
/
wordle.play.js
142 lines (105 loc) · 2.67 KB
/
wordle.play.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
'use strict';
const config = require('./config');
const enCore = require('./wordle.en.core');
const cnCore = require('./wordle.cn.core');
const games = {};
const init = (id, language, mode, onGameInit, onGameExist) => {
if (games[id]) {
return onGameExist();
}
games[id] = {
language: language,
mode: mode,
answer: null,
guess: {},
};
const game = games[id];
return onGameInit(game);
};
const end = (id, onGameEnd, onGameNotExist) => {
if (!games[id]) {
return onGameNotExist();
}
const game = games[id];
delete games[id];
return onGameEnd(game);
};
const get = (id, onDone, onGameNotExist) => {
if (!games[id]) {
return onGameNotExist();
}
const game = games[id];
return onDone(game);
};
const verify = (id, language, size, onValid, onNotValid, onGameNotExist) => {
if (!games[id]) {
return onGameNotExist();
}
const game = games[id];
if (game.language === language && (!game.answer || game.answer.length === size)) {
return onValid(game.mode);
}
return onNotValid();
};
const guess = (id, dict, word, onGuess, onGameEnd, onGuessDuplicated, onNotValid, onGameNotExist) => {
if (!games[id]) {
return onGameNotExist();
}
const core = {
en: enCore,
cn: cnCore,
}[dict.language];
const game = games[id];
const answer = game.answer || core.dictSelect(dict);
if (game.guess['#' + word]) {
return onGuessDuplicated();
}
const result = core.guess(dict, word, answer);
if (result === -1) {
return onNotValid();
}
game.answer = answer;
game.guess['#' + word] = result;
if (Object.keys(game.guess).length > config.wordleMaxGuess) {
for (const i in game.guess) {
// delete the first one
delete game.guess[i];
break;
}
}
if (word === game.answer) {
return end(id, onGameEnd, onGameNotExist);
}
return onGuess(game);
};
const say = (language, word, onSay, onNotValid) => {
const core = {
en: enCore,
cn: cnCore,
}[language];
const dict = core.dictInit();
core.dictAdd(dict, word, true);
const game = {
language: language,
answer: word,
guess: {},
};
const result = core.guess(dict, word, word);
if (result === -1) {
return onNotValid();
}
game.guess['#' + word] = result;
return onSay(game);
};
const count = () => {
return Object.keys(games).length;
};
module.exports = {
init: init,
end: end,
get: get,
verify: verify,
guess: guess,
say: say,
count: count,
};