Loop music

This commit is contained in:
Pierre HUBERT 2020-03-23 18:42:31 +01:00
parent 95b0f2ba19
commit ee16d4cf41
2 changed files with 14 additions and 2 deletions

BIN
assets/game.mp3 Normal file

Binary file not shown.

View File

@ -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