Я пытался добавить звук моей ракеты в созданную мной игру, но я не уверен, как вызвать звук в обратном вызове onClick
, поэтому он воспроизводится каждый раз, когда я нажимаю, чтобы выстрелить в лодку. .
Вот мой код:
console.log(JSON.stringify(gameBoard));
// set event listener for all elements in gameboard, run fireTorpedo function when square is clicked
gameBoardContainer.addEventListener('click', fireTorpedo, false);
// initial code via http://www.kirupa.com/html5/handling_events_for_many_elements.htm:
function fireTorpedo(e) {
// if item clicked (e.target) is not the parent element on which the event listener was set (e.currentTarget)
if (e.target !== e.currentTarget) {
// extract row and column # from the HTML element's id
const row = e.target.id.substring(1, 2);
const col = e.target.id.substring(2, 3);
//alert("Clicked on row " + row + ", col " + col);
// if player clicks a square with no ship, change the color and change square's value
if (gameBoard[row][col] === 0) {
e.target.style.background = '#bbb';
// set this square's value to 3 to indicate that they fired and missed
gameBoard[row][col] = 7;
totalClicks++;
addClick();
console.log(totalClicks);
// if player clicks a square with a ship, change the color and change square's value
} else if (gameBoard[row][col] === 1 ||
gameBoard[row][col] === 2 || gameBoard[row][col] === 3 || gameBoard[row][col] === 4 || gameBoard[row][col] === 5) {
e.target.style.background = 'red';
// set this square's value to 2 to indicate the ship has been hit
gameBoard[row][col] = 8;
// increment hitCount each time a ship is hit
hitCount++;
totalClicks++;
}
}
}
}