上学的第一天,我们应该做一个刽子手游戏。我一直在盯着我的while循环中的逻辑几个小时。我不能让我的循环说是,单词(newWord)确实包含猜测。我总是得到不正确的提示,然后一切都松了。我尝试了25种不同的方式。我知道现在所有这些都被破坏了,但如果有人能让我朝着正确的方向前进,我会永远感激不尽。
let words = ["skate", "guitar", "laugh", "party", "shirt"]
let wordValue = Math.floor(Math.random() * 4) + 1;
let newWord = words[wordValue];
let misses = 0;
let rightGuess = 0;
let wrongGuess = 0;
var answerLines = [];
for (let i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
let remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
let guess = prompt("Guess a letter, any letter!");
for(let j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
rightGuess++
}
else { wrongGuess++ }
if (rightGuess != 0) {
answerLines[j] = guess;
remainingLetters--;
}
else {
misses++
(alert("That was is incorrect. You have " + misses + " of 6 misses."));
答案 0 :(得分:0)
您处理猜测的逻辑有点偏差。试试这个:
var words = ["skate", "guitar", "laugh", "party", "shirt"]
var wordValue = Math.floor(Math.random() * 4) + 1;
var newWord = words[wordValue];
console.log("Word is: " + newWord);
var misses = 0;
var answerLines = [];
for (var i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
var remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
var guess = prompt("Guess a letter, any letter!");
var matchesNone = true; //boolean to track if guess matched any letters
for (var j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
answerLines[j] = guess;
remainingLetters--;
matchesNone = false; //the guess matched atleast one letter
}
}
if (matchesNone) { //the guess matched none of the letters
misses ++;
alert("That was is incorrect. You have " + misses + " of 6 misses.");
}
}
if(remainingLetters>0) {
alert("You failed to guess the word: " + newWord);
}else{
alert("You guessed the word! It was: " + newWord);
}