V0 is working

This commit is contained in:
Pierre HUBERT 2020-03-23 15:37:56 +01:00
parent ddaad26374
commit 21e1763e3d
3 changed files with 82 additions and 6 deletions

View File

@ -10,6 +10,7 @@
],
"snake": [
[4,2], [4,1], [3,1], [2,1]
]
],
"firstKey": "ArrowRight"
}

View File

@ -13,6 +13,6 @@
[6,6],
[6,5],
[6,4]
]
],
"firstKey": "ArrowRight"
}

View File

@ -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,11 +124,70 @@ 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;
});
}
/**