Can win game

This commit is contained in:
Pierre HUBERT 2020-03-25 16:10:51 +01:00
parent ee16d4cf41
commit b052fe7f63
2 changed files with 23 additions and 0 deletions

BIN
assets/win.mp3 Normal file

Binary file not shown.

View File

@ -114,6 +114,7 @@ async function startGame(gameID) {
const ctx = canvas.getContext('2d');
// Initialize the map & snake arrays
/** @type {Array<Array<Number>>} */
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))