-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhangman.js
More file actions
59 lines (53 loc) · 1.56 KB
/
hangman.js
File metadata and controls
59 lines (53 loc) · 1.56 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
String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
class hangman {
constructor(word) {
this.word = word;
this.lives = 6;
this.progress = hangman.hyphenString(word.length);
this.remaining = word.length;
this.misses = [];
this.status = "in progress";
}
static hyphenString(n) {
let str = "";
for (let i = 0; i < n; ++i) {
str += "-";
}
return str;
}
guess(c) {
if (this.progress.includes(c)) {
--this.lives;
} else if (this.word.includes(c)) {
for (let i = 0; i < this.word.length; ++i) {
if (this.word[i] === c) {
this.progress = this.progress.replaceAt(i, this.word[i]);
--this.remaining;
}
}
} else {
if (!this.misses.includes(c)) {
this.misses.push(c);
}
--this.lives;
}
if (this.lives == 0) {
this.status = "lost";
} else if (this.remaining == 0) {
this.status = "won";
}
return { status: this.status, progress: this.progress, misses: this.misses, lifes: this.lives };
}
guessAll(word) {
if (this.word === word) {
this.progress = this.word;
this.status = "won";
} else {
--this.lives;
}
return this.status === "won";
}
}
module.exports = hangman;