2. Check created correctly. Explain variables. Case is important
constcanvas=document.getElementById('canvas');constctx=canvas.getContext('2d');constwidth=400;constheight=400;// other way of declaring variable is let. will explain laterctx.fillStyle ="white";ctx.fillRect(0,0, width, height);ctx.strokeStyle ="black";ctx.strokeRect(0,0, width, height);
Explain for loop (instead of manually typing, computer count) and arrays
let snake; // let as will changefunctioncreateSnake() {let length =5; //Length of the snake snake_array = []; //Empty array to start withfor(let i = length-1; i>=0; i--) {//This will create a horizontal snake starting from the top leftsnake_array.push({x: i, y:0}); } }
6. Draw snake
functiondrawSnake(){for(let i=0; i<snake.length; i++) {paintCell(snake[i].x, snake[i].y); }}// add to paintdrawSnake();
7. Lets make the snake move
let dir;let game_loop;functionmoveSnake(){ var newX = snake[0].x;var newY = snake[0].y;if(dir =="right") newX++;elseif(dir =="left") newX--;elseif(dir =="up") newY--;elseif(dir =="down") newY++;var tail =snake.pop(); //pops out the last celltail.x = newX; tail.y = newY;snake.unshift(tail); //puts back the tail as the first cell}functionpaint(){drawBoard();moveSnake();paint_cell(food.x,food.y);drawSnake();}functioninit(){createSnake(); dir ="right";if(typeof game_loop !="undefined") clearInterval(game_loop); game_loop =setInterval(paint,200);}init();
8. Lets make the snake move in different directions
functionchangeDirection(event){constkey=event.keyCode;//We will add another clause to prevent reverse gearif(key =="37"&& dir !="right"){ dir ="left"; } elseif(key =="38"&& dir !="down"){ dir ="up"; } elseif(key =="39"&& dir !="left"){ dir ="right"; } elseif(key =="40"&& dir !="up"){ dir ="down"; }}document.addEventListener("keydown", changeDirection);
9. Lets End the game if you hit a boundary
There are two cases in which the game can end:
The head of the snake collides with its body.
The head of the snake collides with the canvas boundary.