xxxxxxxxxx
82
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/AaGK-fj-BAM
function Snake() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;
this.total = 1;
this.tail = [];
this.eat = function(pos) {
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.total++;
return true;
} else {
return false;
}
}
this.dir = function(x, y) {
if ((this.yspeed != y || this.xspeed != x * -1) && (this.xspeed != x || this.yspeed != y * -1)) {
this.xspeed = x;
this.yspeed = y;
}
}
this.death = function() {
for (var i = 0; i < this.tail.length; i++) {
var pos = this.tail[i];
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
background(0);
fill(255);
noStroke();
textAlign(CENTER, CENTER);
textSize(60);
text("Score: " + str(this.total + 1), width / 2, height / 2);
noLoop();
}
}
}
this.update = function() {
for (var i = 0; i < this.tail.length - 1; i++) {
this.tail[i] = this.tail[i + 1];
}
if (this.total >= 1) {
this.tail[this.total - 1] = createVector(this.x, this.y);
}
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.show = function() {
fill(89, 152, 47);
noStroke();
for (var i = 0; i < this.tail.length; i++) {
rect(this.tail[i].x, this.tail[i].y, scl, scl);
}
const angle = createVector(this.xspeed, this.yspeed).heading();
push();
ellipseMode(CENTER);
translate(this.x + scl / 2, this.y + scl / 2);
rotate(angle);
rect(-scl / 2, -scl / 2, scl * 1.5, scl, 0, 10, 10, 0);
fill(255);
ellipse(scl / 5, scl / 3, 10);
ellipse(scl / 5, -scl / 3, 10);
fill(0);
ellipse(scl / 5, scl / 3, 5);
ellipse(scl / 5, -scl / 3, 5);
pop();
}
}