diff --git a/assets/win.mp3 b/assets/win.mp3 new file mode 100644 index 0000000..d60934a Binary files /dev/null and b/assets/win.mp3 differ diff --git a/script.js b/script.js index f903a93..ec53695 100644 --- a/script.js +++ b/script.js @@ -114,6 +114,7 @@ async function startGame(gameID) { const ctx = canvas.getContext('2d'); // Initialize the map & snake arrays + /** @type {Array>} */ let map = []; let snake = []; let score = 0; @@ -216,6 +217,17 @@ async function startGame(gameID) { map[oldPos[0]][oldPos[1]] = EMPTY } + // Check if the user has won + // Note : The user win the game if there is no food left + // So we search for a line in the map where there is food + // If none is found, it means that the user has won the game + // + // Optimization : We do it only if the user has just increazed its + // size => the snake has eaten a piece of food + if(increaseSize && map.find((row) => row.find((el) => el == FOOD) != undefined) == undefined) { + winGame() + return; + } } @@ -281,6 +293,7 @@ async function startGame(gameID) { } } + // Manage automated acceleration of snake if(level.hasOwnProperty("acceleration")) @@ -301,6 +314,16 @@ async function startGame(gameID) { location.href = "#"; } + /** + * Call this function when the user win the game + */ + function winGame() { + audioEl.pause(); + playAudio("assets/win.mp3"); + alert("You win !!!"); + location.href = "#"; + } + // Listen for key press events document.body.addEventListener("keydown", (ev) => { if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key))