forked from gSchool/wdi-precourse-drills
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.html
71 lines (62 loc) · 2.02 KB
/
hangman.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hangman</title>
</head>
<body>
<h1>Lets play a game of Hangman</h1>
<p>You will enter your letter guesses in the prompt and we will see if they
are in the secret word</p>
<script>
var name = prompt("What's Your Name?");
alert("Hello " + name);
var pickWord = function () {
var words = ["bland","shadow","archery","garage","minty","August",
"sleeveless","madness","aloof","dancing","pizza"];
return words[Math.floor(Math.random() * words.length)]
};
var setupAnswerArray = function (word) {
var answerArray = [];
for (var i = 0; i < word.length; i++){
answerArray[i] = "_";
}
return answerArray;
};
var showPlayerProgress = function (answerArray) {
alert(answerArray.join(" "));
};
var getGuess = function () {
return prompt("Guess a letter, or click Cancel to stop playing.");
};
var updateGameState = function (guess, word, answerArray) {
var numOfTimes = 0;
for (var j = 0; j < word.length; j++){
if (word[j] === guess.toLowerCase() && answerArray[j] === "_"){
answerArray[j] = guess.toLowerCase();
numOfTimes++;
}
}
return numOfTimes;
};
var showAnswerAndCongratulatePlayer = function (answerArray) {
showPlayerProgress(answerArray);
alert("Good Job!! " + name +" the answer was " + answerArray.join(""));
};
var word = pickWord();
var answerArray = setupAnswerArray(word);
var remainingLetters = word.length;
while (remainingLetters > 0) { showPlayerProgress(answerArray); var guess = getGuess();
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
var correctGuesses = updateGameState(guess, word, answerArray);
remainingLetters -= correctGuesses;
}
}
showAnswerAndCongratulatePlayer(answerArray);
</script>
</body>
</html>