var canvas =document.getElementById('game')
var ctx =canvas.getContext('2d')
var box =10
var snake =[]
var px =(canvas.width/2)
var py =(canvas.height/2)
var dir ='right'
var maxCell =10
function direction(){
document.addEventListener("keydown",function(e){
if(e.keyCode==37){
dir='left'
console.log('left')
}
else if(e.keyCode==38){
dir='up'
console.log('up')
}
else if(e.keyCode==39){
dir='right'
console.log('right')
}
else if(e.keyCode==40){
dir='down'
console.log('down')
}
})
if(dir=='right' && dir!=='left'){px+=box }
else if(dir=='left' && dir!=='right'){px-=box}
else if(dir=='up' && dir!=='down'){py-=box}
else if(dir=='down' &&dir!=='up'){py+=box}
}
function Snake(){
direction()
snake[0]={
x:px,
y:py,
}
if(px>canvas.width){
px=0
}
else if(px<0){
px=canvas.width
}
if(py>canvas.height){
py=0
}
else if(py<0){
py=canvas.height
}
snake.forEach( function(element, index) {
ctx.fillRect(px,py,box,box)
if(index==0){
ctx.fllStyle='red'
ctx.fillRect(px,py,box,box)
}
});
if(snake.length>maxCell){
snake.shift()
}
}
function loop(){
setInterval(()=>{
Snake()
},1000/60)
}
loop()