<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
background: black;
display: flex;
justify-content: center;
align-items: center;
}
#canvas{
background: white;
}
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="500"></canvas>
<script>
let canvas=document.getElementById('canvas')
let ctx=canvas.getContext('2d')
class retroSnaker{
constructor(arr,r){
this.arr=[]
this.defalts=arr
this.defalts.map((val)=>{
this.arr.push([val[0],val[1]])
})
this.pre=[]
this.r=r
this.newfoodpath()
this.boo=true
this.right()
// this.foods()
// this.bodys()
}
newfoodpath(){
this.foodpath=[Math.floor(Math.random()*100)*10+5,Math.floor(Math.random()*50)*10+5]
this.arr.map((val)=>{
if(val[0]===this.foodpath[0]&&val[1]===this.foodpath[1]){
return this.newfoodpath()
}
})
}
bodys(){
ctx.clearRect(0,0,1000,500)
this.arr.map((val)=>{
ctx.beginPath()
ctx.arc(val[0],val[1],this.r,0,Math.PI*2,true)
ctx.fill()
ctx.closePath()
})
this.foods()
}
move(boo,nums){
if(this.boo===boo){
clearInterval(this.times)
this.times=setInterval(()=>{
this.pre=[this.arr[this.arr.length-1][0],this.arr[this.arr.length-1][1]]
for(let i=this.arr.length-1;i>0;i--){
this.arr[i][0]=this.arr[i-1][0]
this.arr[i][1]=this.arr[i-1][1]
}
if(boo){
this.arr[0][0]+=nums
}else {
this.arr[0][1]+=nums
}
if(this.arr[0][0]===this.foodpath[0]&&this.arr[0][1]===this.foodpath[1]){
this.newfoodpath()
this.arr.push([this.pre[0],this.pre[1]])
}
if(this.arr[0][0]<=0||this.arr[0][0]>=1000||this.arr[0][1]<=0||this.arr[0][1]>=500){
this.deaths()
}else {
this.bodys()
}
},200)
this.boo=!boo
}
}
left(){
this.move(true,-5)
}
right(){
this.move(true,5)
}
top(){
this.move(false,-5)
}
down(){
this.move(false,5)
}
foods(){
ctx.beginPath()
ctx.arc(this.foodpath[0],this.foodpath[1],this.r,0,Math.PI*2,true)
ctx.fill()
ctx.closePath()
}
deaths(){
// clearInterval(this.times)
this.arr=[]
this.defalts.map((val)=>{
this.arr.push([val[0],val[1]])
})
alert('you death')
this.newfoodpath()
this.boo=true
this.right()
}
}
let snak=new retroSnaker([[15,5],[10,5],[5,5]],5)
document.onkeydown=function(ev){
let event=window.event||ev
let keycode=event.keyCode
// console.log(keycode);
if(keycode==37){
snak.left()
}else if(keycode==38){
snak.top()
}else if(keycode==39){
snak.right()
}else if(keycode==40){
snak.down()
}
}
// snak.bodys()
</script>
</body>
</html>