Render snake

This commit is contained in:
Pierre HUBERT 2020-03-23 15:17:50 +01:00
parent f9510900be
commit ddaad26374
3 changed files with 36 additions and 9 deletions

View File

@ -9,9 +9,7 @@
[20, 20] [20, 20]
], ],
"snake": [ "snake": [
[6,10], [4,2], [4,1], [3,1], [2,1]
[6,11],
[6,12]
] ]
} }

View File

@ -10,9 +10,9 @@
[10,12] [10,12]
], ],
"snake": [ "snake": [
[60,60], [6,6],
[60,59], [6,5],
[60,58] [6,4]
] ]
} }

View File

@ -122,7 +122,10 @@ async function startGame(gameID) {
*/ */
let interval = setInterval(() => step(), level.delay); let interval = setInterval(() => step(), level.delay);
function step() { function step() {
console.log("render")
if(!canvas.isConnected)
clearInterval(interval)
// Redraw screen // Redraw screen
ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.clearRect(0, 0, canvas.width, canvas.height)
@ -137,10 +140,11 @@ async function startGame(gameID) {
// Now draw the map // Now draw the map
for(let y = 0; y < map.length; y++) { for(let y = 1; y <= map.length; y++) {
for(let x = 0; x < map[y].length; x++) { for(let x = 1; x <= map[y-1].length; x++) {
switch(map[y][x]) { // Adapt rendering to the element to display
switch(map[y-1][x-1]) {
case WALL: case WALL:
ctx.fillStyle = "darkRed"; ctx.fillStyle = "darkRed";
@ -153,7 +157,28 @@ async function startGame(gameID) {
break; break;
case SNAKE: case SNAKE:
ctx.fillStyle = "orange"
ctx.fillRect(x*cell_width, y*cell_height, cell_width, cell_height)
// Check if it is the head of the snake
// If it is the case, we draw an eye to the snake
const headPos = snake[snake.length-1];
if(headPos[0] == y-1 && headPos[1] == x-1) {
ctx.fillStyle = "darkRed";
ctx.beginPath();
ctx.arc(
(x+0.5)*cell_width, // x
(y+0.5)*cell_height, // y
3, // width
0, // startAngle
2*Math.PI) // End angle
ctx.fill();
console.log(x, y)
}
break;
} }
@ -168,6 +193,10 @@ async function startGame(gameID) {
*/ */
function changeWindow() { function changeWindow() {
// Make sure there are not canvas left in the background (to make sure
// no interval is running for an old game)
canvasTarget.innerHTML = ""
// Try to get game ID // Try to get game ID
const gameID = Number(window.location.hash.substr(1)); const gameID = Number(window.location.hash.substr(1));