xxxxxxxxxx
154
let Snake;
let rez = 20;
let food;
let w;
let h;
function setup() {
w = floor(width / rez);
h = floor(height / rez);
createCanvas(400, 400);
frameRate(10);
Snake = new snake();
Snake.foodLocation();
}
function draw() {
scale(rez);
background(220);
if (Snake.eat(food)) {
Snake.foodLocation();
}
Snake.update();
Snake.display();
if (Snake.endGame()) {
background(255, 0, 0);
noStroke();
noLoop();
}
noStroke();
fill(255, 0, 0);
rect(food.x, food.y, 1, 1);
}
function keyPressed() {
if (keyCode === LEFT_ARROW && Snake.xdir != 1) {
Snake.setDir(-1, 0);
} else if (keyCode === RIGHT_ARROW && Snake.xdir != -1) {
Snake.setDir(1, 0);
} else if (keyCode === UP_ARROW && Snake.ydir != 1) {
Snake.setDir(0, -1);
} else if (keyCode === DOWN_ARROW && Snake.ydir != -1) {
Snake.setDir(0, 1);
}
}
class snake {
constructor() {
this.len = 0;
this.body = [];
this.body[0] = createVector(0, 0);
this.xdir = 0;
this.ydir = 0;
}
setDir(x, y) {
this.xdir = x;
this.ydir = y;
}
grow() {
let head = this.body[this.body.length - 1].copy();
this.len++;
this.body.push(head);
}
foodLocationIsInsideSnake(fx, fy) {
let insideSnake = false;
for(let i=0; i<this.body.length-1; i++) {
let part = this.body[i];
if(part.x == fx) {
insideSnake = true;
}
if(part.y == fy) {
insideSnake = true;
}
}
return insideSnake;
}
foodLocation() {
let fx = floor(random(w));
let fy = floor(random(h));
// for (let i = 0; i < this.body.length - 1; i++) {
// let part = this.body[i];
// if (part.x == fx && part.y == fy) {
// fx = floor(random(w - fx));
// fy = floor(random(h - fy));
// }
// }
while(this.foodLocationIsInsideSnake(fx, fy)) {
fx = floor(random(w));
fy = floor(random(w));
}
food = createVector(fx, fy);
}
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();
print("Food Eaten");
return true;
}
return false;
}
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);
}
endGame() {
let x = this.body[this.body.length - 1].x;
let y = this.body[this.body.length - 1].y;
for (let i = 0; i < this.body.length - 1; i++) {
let part = this.body[i];
if (part.x == x && part.y == y) {
print("Game over!!");
return true;
}
}
return false;
}
display() {
for (let i = 0; i < this.body.length; i++) {
fill(0);
if (this.body[0].x > width) {
this.body[i].x = 0 - (i * 10);
} else if (this.body[0].y > height) {
this.body[0].y = 0 - (i * 10);
} else if (this.body[0].x < 0) {
this.body[0].x = width + (i * 10);
} else if (this.body[0].y < 0) {
this.body[0].x = height + (i * 10);
}
rect(this.body[i].x, this.body[i].y, 1, 1);
}
}
}