xxxxxxxxxx
86
let snake;
let apple;
let size = 25;
function setup() {
let canvas = createCanvas(650, 650);
canvas.center("horizontal");
frameRate(1);
snake = new Snake();
DrawAppleRandomPos();
}
function draw() {
background(242);
for (let x = 0; x < width; x += size) { // made grid lines increment in size
for (let y = 0; y < height; y += size) {
stroke(100, 100, 100);
strokeWeight(0.5);
line(x, 0, x, height);
line(0, y, width, y);
}
}
snake.Move();
snake.Show();
if (snake.Eat(apple)) {
DrawAppleRandomPos();
}
fill(255, 100, 0);
rect(apple.x, apple.y, size, size);
}
const DrawAppleRandomPos = () => {
let cols = floor(width / size);
let rows = floor(height / size);
apple = createVector(floor(random(cols)), floor(random(rows)));
apple.mult(size);
}
function keyPressed() {
if (keyCode === UP_ARROW || key === "w") {
snake.Direction(0, -1);
} else if (keyCode === DOWN_ARROW || key === "s") {
snake.Direction(0, 1);
} else if (keyCode === LEFT_ARROW || key === "a") {
snake.Direction(-1, 0);
} else if (keyCode === RIGHT_ARROW || key === "d") {
snake.Direction(1, 0);
}
}
function Snake() {
this.vec = createVector(0, 0);
this.movex = 1;
this.movey = 0;
this.w = 25;
this.h = 25;
this.speed = size; // made speed = size (moves in size increments)
this.Move = () => {
this.vec.x += this.movex * this.speed;
this.vec.y += this.movey * this.speed;
this.vec.x = constrain(this.vec.x, 0, width - this.w);
this.vec.y = constrain(this.vec.y, 0, height - this.h);
}
this.Show = () => {
fill(200, 20, 230);
rect(this.vec.x, this.vec.y, this.w, this.h);
}
this.Direction = (x, y) => {
this.movex = x;
this.movey = y;
}
this.Eat = (position) => {
let distance = dist(this.vec.x, this.vec.y, position.x, position.y);
if (distance < 10) {
console.log("ate");
return true;
} else {
return false;
}
}
}