diff --git a/assets/game.mp3 b/assets/game.mp3 new file mode 100644 index 0000000..5c6a605 Binary files /dev/null and b/assets/game.mp3 differ diff --git a/script.js b/script.js index 56e0ab4..f903a93 100644 --- a/script.js +++ b/script.js @@ -55,11 +55,13 @@ function randInt(min, max) { * Play an audio file * * @param {String} url The URL of the audio file to play + * @returns {HTMLAudioElement} Generated audio element */ function playAudio(url) { const audio = document.createElement("audio"); audio.src = url audio.play(); + return audio; } // Get elements @@ -99,6 +101,10 @@ async function startGame(gameID) { return; } + // Start audio + const audioEl = playAudio("/assets/game.mp3") + audioEl.loop = true; + // Create & apply the canvas const canvas = document.createElement("canvas"); canvas.width = cell_width * level.dimensions[1]; @@ -149,8 +155,10 @@ async function startGame(gameID) { function step() { // Check if a game was destroyed - if(!canvas.isConnected) + if(!canvas.isConnected) { + audioEl.pause(); return; + } // Move the snake if required if(key) { @@ -287,6 +295,7 @@ async function startGame(gameID) { * Call this function once the user loose the game */ function gameOver() { + audioEl.pause(); playAudio("assets/gameOver.mp3"); alert("Game over !!!"); location.href = "#"; @@ -297,8 +306,11 @@ async function startGame(gameID) { if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key)) key = ev.key; - if(ev.key == "p") + if(ev.key == "p") { + audioEl.pause() alert("Game paused. Close this dialog to resume"); + audioEl.play() + } }); // Automatically generate new map element if required