Last active
March 10, 2016 01:07
-
-
Save julien-sarazin/e8aaabe0b76f9edb85bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.replaceAt = function(index, character) { | |
return this.substr(0, index) + character + this.substr(index + character.length); | |
}; | |
function Hangman(word){ | |
this.lives = 7; | |
this.word = word; | |
this.try = this.try.bind(this); | |
this.characters = []; | |
this._buildProgress(); | |
}; | |
Hangman.STATUS = { | |
DIED: 'dead', | |
SAVED: 'saved' | |
} | |
Hangman.prototype = { | |
lives: NaN, | |
status: null, | |
word: null, | |
_progress: null, | |
characters: null | |
}; | |
Hangman.prototype._buildProgress = function(){ | |
if(typeof this.word !== 'string') | |
return undefined; | |
this._progress = ''; | |
for(var i=0; i<this.word.length; i++){ | |
this._progress+= "_"; | |
} | |
this.characters = this.word.split(''); | |
}; | |
Hangman.prototype.try = function(character){ | |
if (this.status === Hangman.STATUS.SAVED || this.status === Hangman.STATUS.DIED) | |
return undefined; | |
if(typeof character !== 'string') | |
return undefined; | |
var index = this.word.indexOf(character); | |
if(index !== -1 && this.characters.indexOf(character) !== -1){ | |
var indices = []; | |
for(var i=0; i<this.word.length; i++) { | |
if (this.word[i] === character) indices.push(i); | |
} | |
for (var i=0; i<indices.length; i++){ | |
this.characters.splice(this.characters.indexOf(character), 1); | |
this._progress = this._progress.replaceAt(indices[i], character); | |
} | |
if (this.characters.length === 0) | |
this.status = Hangman.STATUS.SAVED; | |
return true; | |
} | |
this.lives--; | |
if (this.lives === 0) | |
this.status = Hangman.STATUS.DIED; | |
return false; | |
}; | |
Hangman.prototype.progress = function(){ | |
return this._progress; | |
}; | |
Hangman.prototype.status = function(){ | |
return this._status; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment