-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.js
69 lines (56 loc) · 1.67 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
const objectList = ['chair', 'desk', 'lamp', 'pen', 'table'];
const placeList = ['beach', 'cave', 'desert', 'forest', 'mountain'];
const animalList = ['dog', 'cat', 'bird', 'fish', 'mouse'];
// Pick a random word list
const wordList = [objectList, placeList, animalList][Math.floor(Math.random() * 3)];
// Pick a random word from the list
const word = wordList[Math.floor(Math.random() * wordList.length)];
// Create an array of underscores the same length as the word
let underscores = [];
for (let i = 0; i < word.length; i++) {
underscores.push('_');
}
let lives = 6;
// The main game loop
while (lives > 0) {
// Clear the console
console.clear();
// Print a series of dashes
for (let i = 0; i < 4; i++) {
console.log('----------');
}
// Print a message indicating the word list
if (wordList === objectList) {
console.log('Word list: objects');
} else if (wordList === placeList) {
console.log('Word list: places');
} else if (wordList === animalList) {
console.log('Word list: animals');
}
// Print the current state of the game
console.log(underscores.join(' '));
console.log(`Lives: ${lives}`);
// Get a letter from the user
const letter = prompt('Guess a letter:');
// Check if the letter is in the word
let correct = false;
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) {
underscores[i] = letter;
correct = true;
}
}
// If the letter is not in the word, subtract a life
if (!correct) {
lives--;
}
// Check if the player has won
if (underscores.join('') === word) {
console.log('You win!');
break;
}
}
// The player has lost
if (lives === 0) {
console.log('You lose!');
}