From 21e1763e3dd2e6b6d82612de55821831156d8f61 Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Mon, 23 Mar 2020 15:37:56 +0100 Subject: [PATCH] V0 is working --- levels/1.json | 3 +- levels/2.json | 4 +-- script.js | 81 +++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 82 insertions(+), 6 deletions(-) diff --git a/levels/1.json b/levels/1.json index d91f5e7..a226939 100644 --- a/levels/1.json +++ b/levels/1.json @@ -10,6 +10,7 @@ ], "snake": [ [4,2], [4,1], [3,1], [2,1] - ] + ], + "firstKey": "ArrowRight" } \ No newline at end of file diff --git a/levels/2.json b/levels/2.json index 13904ff..4f34203 100644 --- a/levels/2.json +++ b/levels/2.json @@ -13,6 +13,6 @@ [6,6], [6,5], [6,4] - ] - + ], + "firstKey": "ArrowRight" } \ No newline at end of file diff --git a/script.js b/script.js index ac805dd..e8f3986 100644 --- a/script.js +++ b/script.js @@ -113,6 +113,8 @@ async function startGame(gameID) { snake.push([s[0]-1, s[1]-1]); }) + // Initialize pressed key + let key = level.firstKey; /** * Step function @@ -122,10 +124,69 @@ async function startGame(gameID) { */ let interval = setInterval(() => step(), level.delay); function step() { - console.log("render") - + + // Check if a game was destroyed if(!canvas.isConnected) clearInterval(interval) + + // Move the snake if required + if(key) { + let newHead = Array.from(snake[snake.length-1]); + let increaseSize = false; + + // Make the snake move + switch(key) { + case "ArrowDown": + newHead[0]++; + break; + + case "ArrowUp": + newHead[0]--; + break; + + case "ArrowLeft": + newHead[1]--; + break; + + case "ArrowRight": + newHead[1]++; + break; + } + + + if(newHead[0] < 0 || newHead[1] < 0 || + newHead[0] >= level.dimensions[0] || newHead[1] >= level.dimensions[1]) { + gameOver(); + return; + } + + // Trigger appropriate action + switch(map[newHead[0]][newHead[1]]) { + + case FOOD: + increaseSize = true; + break; + + case WALL: + gameOver(); + break; + + } + + // Push new snake position + snake.push(newHead); + map[newHead[0]][newHead[1]] = SNAKE + + // Remove the end of the snake if he has not eaten anything + if(!increaseSize) { + const oldPos = snake.shift() + map[oldPos[0]][oldPos[1]] = EMPTY + } + + } + + + // Redraw screen ctx.clearRect(0, 0, canvas.width, canvas.height) @@ -174,7 +235,6 @@ async function startGame(gameID) { 0, // startAngle 2*Math.PI) // End angle ctx.fill(); - console.log(x, y) } @@ -186,6 +246,21 @@ async function startGame(gameID) { } } } + + /** + * Call this function once the user loose the game + */ + function gameOver() { + clearInterval(interval); + alert("Game over !!!"); + location.href = "#"; + } + + // Listen for key press events + document.body.addEventListener("keydown", (ev) => { + if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key)) + key = ev.key; + }); } /**