xxxxxxxxxx
62
function Snake(x, y) {
this.pos = createVector(x, y);
this.angle = 0;
this.prevPos = [];
this.len = 15;
this.update = function() {
this.controls();
const vel = p5.Vector.fromAngle(this.angle, 2);
if (intersecting) {
this.len += 10;
score++;
}
this.prevPos.push(this.pos.copy());
if (this.prevPos.length > this.len) {
this.prevPos.shift();
}
this.pos.add(vel);
};
this.controls = function() {
if (!paused) {
if (keyIsDown(37) || keyIsDown(65)) {
this.angle -= 0.1;
}
if (keyIsDown(39) || keyIsDown(68)) {
this.angle += 0.1;
}
}
};
this.show = function() {
push();
ellipseMode(CENTER);
noStroke();
fill(65, 105, 225);
for (let p of this.prevPos) {
circle(p.x, p.y, 10);
}
translate(this.pos.x, this.pos.y);
rotate(this.angle);
fill(255);
circle(-3, -4, 5);
circle(-3, 4, 5);
fill(0);
circle(-1.5, -4, 2.5);
circle(-1.5, 4, 2.5);
pop();
};
this.checkGameOver = function() {
if (this.pos.x < 5 || this.pos.x > width - 5 || this.pos.y < 5 || this.pos.y > height - 5) {
GameOver();
}
for (let i = 0; i < this.prevPos.length - 60; i++) {
const spos = this.prevPos[i];
if (circlesIntersect(spos, 5, this.pos, 5)) {
GameOver();
}
}
};
}