-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman.js
84 lines (72 loc) · 2.1 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
var hangman = this;
if($ === undefined){
var $ = require('jquery');
var http = require('http');
hangman.exports = hangman;
}
if(typeof exports === 'undefined'){
var exports = this['hangman'] = {};
}
exports.matchLetterInWord = function(word, letter){
var indexesOfOccurrences = [];
for(var i = 0; i < word.length; i++){
if (word[i].toUpperCase() === letter) indexesOfOccurrences.push(i);
}
return indexesOfOccurrences;
}
exports.guessLetter = function(word, letter, guessedLetters){
guessedLetters[letter] = hangman.exports.matchLetterInWord(word, letter);
return guessedLetters[letter];
}
exports.startGame = function(){
var guessedLetters = {};
return guessedLetters;
}
exports.numberOfWrongGuesses = function(guessedLetters){
var numberOfIncorrectGuesses = 0;
for(letter in guessedLetters){
if(guessedLetters[letter].toString() === ''){
numberOfIncorrectGuesses++;
}
}
return numberOfIncorrectGuesses;
}
exports.isGameWon = function(word, guessedLetters){
var correctlyGuessedLetters = [];
for(letter in guessedLetters){
if(guessedLetters[letter].toString() !== ''){
correctlyGuessedLetters.push(letter);
}
}
function isBigEnough(element, index, array) {
if(correctlyGuessedLetters.indexOf(element) === -1){
return false;
}
return true;
}
return word.toUpperCase().split('').every(isBigEnough);
}
exports.splitWordListIntoWords = function(listOfWords){
var splitWords = [];
var notAnEmptyWord = function(word){
if(word !== ''){
return true;
}
return false;
}
splitWords = listOfWords.split(/\n|\r/g).filter(notAnEmptyWord);
var filterOutInvalidCharacters = function(invalidCharacters, wordArray){
var replaceInvalidCharacters = function(word, index){
var removeInvalidCharacter = function(characterToRemove){
if(word.indexOf(characterToRemove) !== -1){
var regex = new RegExp('\\' + characterToRemove, 'g');
wordArray[index] = word.replace(regex, '');
}
}
invalidCharacters.forEach(removeInvalidCharacter);
}
wordArray.forEach(replaceInvalidCharacters);
}
filterOutInvalidCharacters(['-', '*', ' '], splitWords);
return splitWords;
}