let snake;
let food;
let w = 20; // width of each square
let speed = 5;
function setup() {
createCanvas(500, 500);
snake = new Snake();
foodLocation();
}
function draw() {
background(51);
if (snake.eat(food)) {
foodLocation();
}
snake.update();
snake.show();
ellipse(food.x, food.y, w, w);
}
function foodLocation() {
food = createVector(floor(random(width/w))*w,
floor(random(height/w))*w);
}
class Snake {
constructor() {
this.x = 0;
this.y = 0;
this.xspeed = w;
this.yspeed = 0;
this.total = 0;
this.tail = [];
}
update() {
this.x += this.xspeed;
this.y += this.yspeed;
this.tail.push(createVector(this.x,this.y));
this.total++;
if (this.tail.length > this.total) {
this.tail.shift();
}
}
eat(pos) {
let d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.total++;
return true;
} else {
return false;
}
}
show() {
fill(255);
for (let i = 0; i < this.tail.length; i++) {
ellipse(this.tail[i].x, this.tail[i].y, w,w);
}
}
}
This will show a snake that can grow by eating food, and uses a tail array to keep track of its body parts. You can add keyboard controls, collision detection, and a scoreboard to make it a more complete Snake game!