这是刽子手游戏。对于初学者来说,这是一本来自js book的简单游戏。我尝试为用户输入的内容添加更多检查。如果有猜测的话,我会放一个其他的东西!==' string'但是没有用。
当我输入一个数字或一个符号#时,代码会进入另一个生命:guessesNr--,而不是处于警戒状态("请输入一个字母!");
请有人告诉我该怎么做,因为我不知道为何不能使用我的逻辑。
var words = [
"javascript",
"monkey",
"amazing",
"pancake"
];
var word = words[Math.floor(Math.random() * words.length)];
//create an empty array called answerArray and fill it
//with underscores (_) to match the number
//of letters in the word
var answerArray = [];
for( var i=0; i < word.length; i++) {
answerArray[i] = "_";
}
//every time the player guesses a
//correct letter, this value will
//be decremented (reduced) by 1
var remainingLetters = word.length;
var guessesNr = 4;
var isHit = false;
while((remainingLetters > 0) && (guessesNr > 0)) {
// Show the player their progress
alert("The word is from " + word.length + " letters " + answerArray.join(" "));
// Take input from player
var guess = prompt("Guess a letter");
// if the player clicks the Cancel button, then guess will be null
if(guess===null) {
// break to exit the loop
break;
//ensuring that guess is exactly one letter
} else if(guess.length !== 1) {
alert("Please enter a single letter!");
} else if(typeof guess !== 'string') {
alert("Please enter only letters!");
} else {
for(var j = 0; j < word.length; j++) {
if(word[j] === guess) {
// sets the element at index j, from word,
// of answerArray to guess
answerArray[j] = guess;
remainingLetters--;
isHit = true;
}
}
if(!isHit) {
guessesNr--;
alert("You have " + guessesNr + " more lives");
if(guessesNr === 0) {
alert("No more lives");
break;
}
}
}
}
//alert(answerArray.join(" "));
alert("Great job! The answer was " + word);
&#13;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
&#13;
答案 0 :(得分:2)
'prompt'的返回值是一个字符串。字符串几乎可以包含任何字符,包括字母,符号和数字。在您的情况下,您正在检查字符串,而不是字母。所以:
typeof 1234 == "number"
typeof "1234" == "string"
因此,您应该检查仅由字母组成的字符串。有很多种可能的方法,您可以使用正则表达式轻松完成,例如:
var letters = /^[A-Za-z]+$/;
if (!guess.match(letters)) alert("Please enter only letters!");
如果您只想要一个字母,请尝试使用:
var letters = /^[A-Za-z]$/;
正则表达式非常强大,我的建议是你阅读更多关于它们的内容。希望我帮助过!
答案 1 :(得分:0)
字母测试错误:
if(typeof guess !== 'string') {
这是一种数据类型测试,并且总是会失败,因为prompt
总是在null
时返回一个字符串。
相反,你可以这样做:
if(guess.toUpperCase() === guess.toLowerCase()) {
答案 2 :(得分:0)