xxxxxxxxxx
57
class Snake {
constructor(){
this.body = [];
this.body[0] = createVector(0,0);
this.xdir = 1;
this.ydir = 0;
}
update(){
let head = this.body[this.body.length-1].copy();
this.body.shift();
head.x += this.xdir;
head.y += this.ydir;
this.body.push(head);
}
display(){
for(var i = 0; i< this.body.length;i++){
rect(this.body[i].x,this.body[i].y,1,1);
}
}
setDir(x,y){
this.xdir = x;
this.ydir = y;
}
grow(){
let head = this.body[this.body.length-1].copy();
this.body.push(head);
}
eat(pos){
let x = this.body[this.body.length-1].x;
let y = this.body[this.body.length-1].y;
if(x == pos.x && y == pos.y) {
this.grow();
return true;
}
return false;
}
endGame(){
let x = this.body[this.body.length-1].x;
let y = this.body[this.body.length-1].y
if(x > wh || x < 0 || y < 0 || y > wh){
return true;
}
for(let i = 0; i < this.body.length-1; i++){
let part = this.body[i];
if(part.x == x && part.y == y){
return true;
}
}
return false
}
}