我创建了一个小应用,该应用的button
每次用户单击时都会播放不同的声音,如果他们猜对了正确的动物,则分数计数器会升高。
但是,如果他按两次enter
,计数器仍会得分,这会使他作弊。
我该如何做,以便如果他猜到了,计数器将增加一,但是如果他再次按下Enter键并且他们猜到了声音,计数器将保持不变?我尝试使用像isEntered逻辑这样的布尔值,但是它不起作用,我尝试将shuffle逻辑封装在一个函数中,并在每次他猜测时都调用它,但是没有产生期望的结果,这是我的代码:
var sounds = [
{
animalType: 'horse',
sound: new Audio('../sounds/Horse-neigh.mp3')
},
{
animalType: 'bear',
sound: new Audio('../sounds/grizzlybear.mp3')
},
{
animalType: 'goat',
sound: new Audio('../sounds/Goat-noise.mp3'),
},
{
animalType: 'cat',
sound: new Audio('../sounds/cat.mp3')
},
{
animalType: 'dog',
sound: new Audio('../sounds/dog-bark.mp3')
},
{
animalType: 'sheep',
sound: new Audio('../sounds/sheep.mp3')
},
{
animalType: 'rooster',
sound: new Audio('../sounds/rooster.mp3')
},
{
animalType: 'lion',
sound: new Audio('../sounds/lion.mp3')
},
{
animalType: 'hen',
sound: new Audio('../sounds/hen.mp3')
}
]
var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');
var errorMessage = document.getElementById('error-message');
var wrongAnswerSound = new Audio('../sounds/Wrong-answer-sound-effect.mp3');
var isEntered = false;
function startGame() {
var currentSound;
player.addEventListener('click', function() {
var sound = sounds[Math.floor(Math.random()*sounds.length)];
currentSound = sound.animalType;
sound['sound'].play();
})
enteredWord.addEventListener('keyup', function() {
if(event.key === 'Enter') {
if(enteredWord.value.toLowerCase() === currentSound) {
isEntered = true;
counter.textContent ++;
errorMessage.style.display = 'none';
enteredWord.classList.remove('input-error-border');
} else {
isEntered = false;
errorMessage.style.display = 'inline-block';
enteredWord.classList.add('input-error-border');
wrongAnswerSound.play();
}
}
})
}
startGame();
和我的html:
<div class="help">
<p class="question-mark trigger">?</p>
<div class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h1> Click on the note icon to hear a sound, then try to guess it by typing the animals name.</h1>
</div>
</div>
</div>
<div class="input">
<div id="player"><img src="../images/note.png"></div>
<input type="text" autofocus id="entered-word" placeholder="Guess the animal sound" >
</div>
<div id="counter">Score:<span id="counter-score"> 0</span> </div>
答案 0 :(得分:1)
您应在事件监听器中检查isEntered
变量,如下所示:
enteredWord.addEventListener('keyup', function() {
if(event.key === 'Enter') {
if(enteredWord.value.toLowerCase() === currentSound && isEntered === false) {
isEntered = true;
counter.textContent ++;
errorMessage.style.display = 'none';
enteredWord.classList.remove('input-error-border');
} else {
isEntered = false;
errorMessage.style.display = 'inline-block';
enteredWord.classList.add('input-error-border');
wrongAnswerSound.play();
}
}
})