function init(){
var canvas=document.getElementById(‘mycanvas’);
W=canvas.width=1000;
H=canvas.height=463;
pen=canvas.getContext(‘2d’);
cs=66;
snake={
init_length:2,
color:“blue”,
cells:[],
direction:“right”,
createsnake:function(){
for(var i=this.init_length;i>0;i–){//jitni length utna coordinates x main
this.cells.push({x:i,y:0});
}
},
drawsnake:function(){
for(var i=0;i<this.cells.length;i++){
pen.fillStyle=this.color;
pen.fillRect(this.cells[i].xcs,this.cells[i].ycs,cs-3,cs-3)
}
},
updatesnake:function(){
this.cells.pop();
var headX=this.cells[0].x;
var headY=this.cells[0].y;
var nextX,nextY;
if(this.direction=="right"){
nextX=headX+1;
nextY=headY;
}
else if(this.direction=="left"){
nextX=headX-1;
nextY=headY;
}
else if(this.direction=="up"){
nextX=headX;
nextY=headY+1;
}
else if(this.direction=="down"){
nextX=headX;
nextY=headY-1;
}
this.cells.unshift({x: nextX,y: nextY});//pichla utha kr aage dala
}
};
snake.createsnake();
function keypressed(e){
if(e.key==“ArrowRight”){
snake.direction=“right”;
}
else if(e.key==“ArrowLeft”){
snake.direction=“left”;
}
else if(e.key==“ArrowDown”){
snake.direction=“down”;
}
else if(e.key==“ArrowUp”){
snake.direction=“up”;
}
console.log(“key pressed”)
}
//add event listner on document object
document.addEventListener(‘keydown’,keypressed);
}
function draw(){
snake.drawsnake();
}
function update(){
snake.updatesnake();
}
function gameloop(){
draw();
update();
}
init();
var f = setInterval(gameloop,100);