Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Created November 11, 2018 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev001hajipro/ad202fe3a24a1ddf43a289c02cb76923 to your computer and use it in GitHub Desktop.
Save dev001hajipro/ad202fe3a24a1ddf43a289c02cb76923 to your computer and use it in GitHub Desktop.
p5.js_snakegame.js
// https://www.youtube.com/watch?v=AaGK-fj-BAM
const scale = 20;
class Snake {
constructor() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;
this.total = 0;
this.tail = [];
}
update() {
if (this.total === this.tail.length) {
for (let i = 0; i < this.tail.length-1; i++) {
this.tail[i] = this.tail[i+1]; // shift
}
}
this.tail[this.total-1] = createVector(this.x, this.y);
this.x += (this.xspeed * scale);
this.y += (this.yspeed * scale);
this.x = constrain(this.x, 0, width-scale);
this.y = constrain(this.y, 0, height-scale);
}
show() {
fill(255);
for (let i = 0; i < this.tail.length; i++) {
rect(this.tail[i].x, this.tail[i].y, scale, scale);
}
rect(this.x, this.y, scale, scale);
}
direction(x, y) {
this.xspeed = x;
this.yspeed = y;
}
eat(food) {
let d = dist(this.x, this.y, food.pos.x, food.pos.y);
if (d < 1) {
this.total++;
return true;
}
return false;
}
}
class Food {
constructor() {
this.renew();
}
renew() {
let cols = floor(width / scale);
let rows = floor(height / scale);
this.pos = createVector(
floor(random(cols)),
floor(random(rows)));
this.pos.mult(scale);
}
update() {
}
show() {
fill(255, 0, 100);
rect(this.pos.x, this.pos.y, scale, scale);
}
}
let snake;
let food;
function setup() {
createCanvas(600, 600);
frameRate(10);
snake = new Snake();
food = new Food();
}
function draw() {
background(51);
snake.update();
snake.show();
if (snake.eat(food)) {
food.renew();
}
food.show();
}
function keyPressed() {
if (keyCode == UP_ARROW) {
snake.direction(0, -1);
} else if (keyCode == DOWN_ARROW) {
snake.direction(0, 1);
} else if (keyCode == RIGHT_ARROW) {
snake.direction(1, 0);
} else if (keyCode == LEFT_ARROW) {
snake.direction(-1, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment