下面,我创建了一个函数,该函数在我通过javascript和DOM操作创建的游戏中使用炸弹,在游戏的每次迭代中事件堆叠在一起存在一个错误,因此我的解决方案是每次清除事件迭代,我该怎么做呢?
function bombUse() {
document.addEventListener("keydown", function(event) {
if (event.code === 'space') {
if (game.bombs > 0) {
game.timer = 3000
game.bombs -= 1
console.log(`there are ${game.bombs} bombs left`)
let getBombs = document.querySelector("#bombs")
let numberOfBombs = getBombs.children
console.log(`there are ${numberOfBombs.length} bomb images`)
if (numberOfBombs.length > 0) {
getBombs.removeChild(getBombs.childNodes[0])
console.log(`there are only ${numberOfBombs.length} bomb images left`)
}
let enemyList = document.querySelectorAll('.pixelcat')
enemyDeathSound()
game.points += enemyList.length
for (let i = 0; i < enemyList.length; i++) {
enemyList[i].removeEventListener('click', clickEnemy)
enemyList[i].src = 'assets/spaceexplosion.gif'
game.totalEnemies -= 1
enemyList[i].remove()
let pointsUpdate = document.querySelector("#points")
pointsUpdate.innerHTML = `${game.points} CAT DESTRUCTIONS`
}
}
}})
}