-
Notifications
You must be signed in to change notification settings - Fork 13
/
hangman.play.js
79 lines (58 loc) · 1.6 KB
/
hangman.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
'use strict';
const core = require('./hangman.core');
const games = {};
const meows = {};
const meowInit = (meowId, answer) => {
meows[meowId] = answer;
};
const hint = (answer) => {
return '\x01'.repeat(core.length(answer));
};
const init = (id, meowId, dict, keyboardSize, onGameInit, onGameExist) => {
if (games[id]) {
return onGameExist();
}
let answer = null;
if (meows[meowId] && core.length(meows[meowId]) <= keyboardSize) {
answer = meows[meowId];
delete meows[meowId];
} else {
answer = core.dictSelect(dict);
}
games[id] = {
answer: answer,
hint: hint(answer),
keyboard: core.makeKeyboard(dict, answer, keyboardSize),
history: [],
};
return onGameInit(games[id]);
};
const click = (id, playerId, charIndex, onGameContinue, onGameWin, onNotValid, onGameNotExist) => {
if (!games[id]) {
return onGameNotExist();
}
const game = games[id];
const char = game.keyboard[charIndex];
const oldHint = game.hint;
if (char) {
game.hint = core.guess(game.answer, game.hint, char);
game.keyboard[charIndex] = null;
game.history.push([playerId, char, game.hint !== oldHint]);
if (game.hint === game.answer) {
delete game.hint;
delete games[id];
return onGameWin(game);
}
return onGameContinue(game);
}
return onNotValid();
};
const count = () => {
return Object.keys(games).length;
};
module.exports = {
meowInit: meowInit,
init: init,
click: click,
count: count,
};