if条件未在我的代码中按预期执行。函数isPlaying由下面的eventListener调用时显示函数的状态为'播放'即使this.guesses变量= 0,并且在guesses = -1时更改为已完成或失败,这会导致额外的按键显示已完成或失败的消息。如果我将条件更改为this.guesses> 1状态立即更改。我很困惑。
const Hangman = function(word,guesses){
this.word = word.toLowerCase().split(''),
this.guesses = guesses,
this.guessedLetters = []
this.status = 'playing';
}
Hangman.prototype.isPlaying = function(){
const isWordMissing = this.wordPuzzle().includes('*');
if(this.guesses > 0 && isWordMissing){
this.status = 'playing';
}else if(this.guesses > 0.5 && !isWordMissing){
this.status = 'finished';
}
else if(this.guesses === 0){
this.status = 'failed';
}
}
Hangman.prototype.wordPuzzle = function(){
let puzzle = ''
this.word.forEach((letter) => {
if(this.guessedLetters.includes(letter) || letter === ' '){
puzzle += letter;
}else{
puzzle += '*';
}
})
return puzzle;
}
Hangman.prototype.guessLetters = function(letter){
guess = letter.toLowerCase();
const isUnique = !this.guessedLetters.includes(letter.toLowerCase());
const isBadGuess = !this.word.includes(letter.toLowerCase());
if(!this.guessedLetters.includes(letter.toLowerCase())){
this.guessedLetters.push(letter);
}
if(isUnique && isBadGuess){
this.guesses = this.guesses - 1;
}
}
game = new Hangman('fast',3);
const puzzleEl = document.querySelector('#word');
const guessEl = document.querySelector('#guess-left')
puzzleEl.textContent = game.wordPuzzle();
guessEl.textContent = `Guesses remaining: ${game.guesses}`;
console.log(game.status);
window.addEventListener('keypress', (e) => {
if(game.status !== 'playing'){
console.log(game.status)
}
else{
const guess = String.fromCharCode(e.charCode);
game.guessLetters(guess);
puzzleEl.textContent = game.wordPuzzle();
guessEl.textContent = `Guesses remaining: ${game.guesses}`
debugger;
game.isPlaying()
}
})