我正在尝试使用HTML,CSS,JS创建一个基本的Hangman类型游戏。到目前为止,我已成功地从一个单词数组中创建一个随机单词,使用' _'为所有未猜到的字母显示在屏幕上,并填写用户键盘的正确猜测。登记/> 我无法弄清楚如何: - 当用户正确猜到单词时显示警报。 -detect并仅显示错误的用户猜测(现在显示所有键盘) 任何建议将不胜感激,谢谢!
- JS CODE :
var composers =["bach","mozart","beethoven","debussy","stravinsky"];
var randomComposer = composers[Math.floor(Math.random() *
composers.length)];
var guessComposer = [];
for (var i=0; i<randomComposer.length; i++){
guessComposer[i] = "-";
}
var el = document.getElementById('guessword');
el.innerHTML=guessComposer.join(" ");
var wrongGuesses = [];
// var eleme = document.getElementById('wrong');
// eleme.innerHTML=wrongGuesses;
var guessesLeft = 15;
var ele = document.getElementById('remaining');
ele.innerHTML=guessesLeft;
var wins = 0;
var elem = document.getElementById('numwins');
elem.innerHTML=wins;
document.onkeyup = function(event) {
var userGuess = event.key;
// el.innerHTML=guessComposer.join(" ");
for(var j=0; j<randomComposer.length; j++){
if(randomComposer[j]===userGuess){
guessComposer[j]=userGuess;
}
}
if (userGuess !== randomComposer[j]){
wrongGuesses.push(userGuess);
guessesLeft --;
var wg = document.getElementById('wrong');
wg.innerHTML=wrongGuesses;
}
if(guessComposer == randomComposer){
alert("Congratulations, You Won!");
wins++;
}
if(guessesLeft===0){
alert("You lost, study more music...");
}
var el = document.getElementById('guessword');
el.innerHTML=guessComposer.join(" ");
var ele = document.getElementById('remaining');
ele.innerHTML=guessesLeft;
console.log(randomComposer.length);
}
HTML CODE
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Famous Classical Composers Hangman Game</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="assets/css/reset.css">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<div class="header">
<h1>Famous Classical Composers Hangman Game</h1>
<h3>Press any key to start</h3>
</div>
<div class="wordguess" id="guessword">
</div>
<div class="wrong_guesses">
Wrong Guesses: <span id="wrong">
</span></div>
<div class="guesses_left" > Guesses Remaining: <span id="remaining">
</span>
</div>
<div class="wins">Number of Wins: <span id="numwins"></span>
</div>
<script type="text/javascript" src="assets/javascript/game.js">
</script>
</body>
</html>
答案 0 :(得分:0)
对于你的胜利检查代码,你正在比较数组,就好像它们是你不能做的字符串或整数:
if(guessComposer == randomComposer){
相反,您可以使用every
函数来测试每个数组元素的条件,这也可以使您的测试相对简单并且接近它的原样:
if (guessComposer.every((v,i)=>v === randomComposer[i]) ) {
这将测试v value
数组中的每个guessComposer
是否与randomComposer
数组中特定位置的相应项匹配。
至于显示错误的猜测,您只需要在警报中将数组显示为字符串。为此,您可以使用join
功能:
if (guessesLeft === 0) {
alert("You lost, study more music...\nWrong guesses:" + wrongGuesses.join(' '));
}
join
将字符串中每个元素之间的字符作为参数,我将其设置为空格' '
。
或者换句话说,你可以把它读作:取所有元素并将它们放入一个字符串中并用空格分隔。
另外,检查字母猜错是否错误也不正确:
if (userGuess !== randomComposer[j]){
检查userGuess
是否与当前所选作曲家的最后一个字母匹配。相反,您希望将任何现有字母与indexOf
匹配:
if (randomComposer.indexOf(userGuess) == -1) {