// create an array of words
const words = ['javascript','cascading', 'language','coding','amazing','tree','letter'];
let word = words[Math.floor(Math.random() * words.length)];// pick a ranndom word from the words array
let wordContainer = document.getElementById("words-container");
let answerLetters = word.split('');
console.log('answerLetters: ',answerLetters);
let lettersInput = document.querySelectorAll(".letters button");// variable which represents all buttons
let pressedLetters = [];
let correctLetters = [];
let wrongLetters = [];
let lives = 10;
let showLives = document.querySelector('.lives');
let messageWinner = "Congrats! You won!";
let messageLoser = "You lost! Please try again!"
// created a span for each char in the random word
for(let i = 0; i < word.length;i++){
let letter = document.createElement('span');
letter.innerText = '_ ';
wordContainer.appendChild(letter);
}
let wordContainnerSpans = document.querySelectorAll('.words-container span');
// handle user input with event listener
for(let i = 0; i < lettersInput.length; i++){
lettersInput[i].addEventListener("click", function(){
console.log('button pressed is: ',lettersInput[i].innerHTML);
pressedLetters.push(lettersInput[i].innerHTML);
checkMatchAndUpdate(lettersInput[i].innerHTML);
})
}
function checkMatchAndUpdate(guessedLetter){
let guess = answerLetters.indexOf(guessedLetter);
while (guess != -1) {
correctLetters.push(guess);
guess = answerLetters.indexOf(guessedLetter, guess + 1);
}
console.log(correctLetters);
for(let i = 0; i < correctLetters.length;i++){
wordContainnerSpans[correctLetters[i]].innerText = guessedLetter;
}
correctLetters = [];
}
我有checkmatch和update功能,但我在创建生命计数器时遇到问题,我希望玩家有10条生命,然后在玩家输赢时显示。如果有人能帮忙,那就太好了。非常感谢。
1条答案
按热度按时间h9vpoimq1#
生命是一个规则变量,您需要为设置/检查/添加/删除生命创建一些函数。
在您的代码中,我没有看到任何用于检查或编辑生活的代码,您尝试了什么?
简单的例子:
在这之后,你可以检查
如果是真的-还活着,如果是假的-做一些像游戏结束一样的事情。