-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.js
115 lines (96 loc) · 2.25 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
'use strict';
function Hangman(word) {
this.word = word.trim();
this.wordLow = this.word.toLowerCase();
this.myTry = [...(this.word.replace(/\w/g, '_'))];
this.trys = 6;
this.letters = [];
this.won = false;
this.lost = false;
}
Hangman.prototype.console = function() {
console.log(
`${this.myTry.join('')} | ${this.letters.join('')} | left: ${this.trys}`
)
};
Hangman.prototype.isWon = function() {
if (this.won) {
console.log(`You have already won! The word was ${this.word}`)
return true;
}
};
Hangman.prototype.isLost = function() {
if (this.lost) {
console.log(`You have already lost! The word was ${this.word}`)
return true;
}
};
Hangman.prototype.winer = function() {
this.won = true;
console.log(`You won! The word was ${this.word}`)
};
Hangman.prototype.looser = function() {
this.lost = true;
console.log(`You lost. :( The word was ${this.word}`)
};
Hangman.prototype.guess = function(char) {
if ( this.isWon() || this.isLost() || char==" ") {
return
}
char = char.toLowerCase();
if ( this.letters.indexOf(char) != -1 || this.myTry.indexOf(char) != -1){
console.log('You have already entered this letter')
return this
}
let idx = this.wordLow.indexOf(char);
if (idx == -1) {
this.letters.push(char);
this.trys--;
if (this.trys < 0){
this.looser();
return;
}
this.console();
return;
}
while (idx !== -1) {
this.myTry[idx] = this.word[idx];
idx = this.wordLow.indexOf(char, idx + 1);
}
if (this.myTry.join('')==this.word){
this.winer()
return
}
this.console();
};
const fr = new Hangman('Frontend Raccoon');
/*
* We need to create a readline interface.
* The interface takes 2 streams.
* The input field points to the readable input stream
* and the output field to the writable output stream.
*/
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function nodeJs() {
rl.question('\nPlease write your letter: ', function (name) {
if (name){
fr.guess(name);
nodeJs();
} else {
rl.question('\nFor exit type "y" ', function (ans) {
if (ans =="y"){
console.log('goodbay');
rl.close();
process.stdin.destroy();
} else {
nodeJs();
}
})
}
});
}
nodeJs();