Skip to content

Instantly share code, notes, and snippets.

@huahualeetcode
Last active October 21, 2020 04:47
Show Gist options
  • Save huahualeetcode/7f12dcab422734f76b33210d75ae4c97 to your computer and use it in GitHub Desktop.
Save huahualeetcode/7f12dcab422734f76b33210d75ae4c97 to your computer and use it in GitHub Desktop.
// Author: Huahua (https://www.youtube.com/user/xxfflower)
// p5 web editor: https://editor.p5js.org
var rows = 25;
var cols = 25;
var a = 20;
var s;
var f;
function Snake() {
this.x = 12;
this.y = 12;
this.sx = 0;
this.sy = 0;
this.body = [[this.x, this.y]];
this.ss = 1;
this.dead = false;
this.isDead = function() {
return this.dead;
}
this.len = function() {
return this.body.length;
}
this.update = function() {
this.x = constrain(this.x + this.sx, -1, cols);
this.y = constrain(this.y + this.sy, -1, rows);
if (this.x < 0 || this.y < 0 || this.x == cols || this.y == rows) {
this.dead = true;
return;
}
if (this.contains(createVector(this.x, this.y), 3)) {
this.dead = true;
return;
}
this.body.pop();
this.body.unshift([this.x, this.y]);
}
this.dir = function(dx, dy) {
if (this.len() > 1) {
if (dx !== 0 && dx === -this.sx ||
dy !== 0 && dy === -this.sy) return;
}
this.sx = dx;
this.sy = dy;
}
this.draw = function() {
fill(255);
for (var i = 1; i < this.body.length; ++i) {
rect(this.body[i][0] * a, this.body[i][1] * a, a, a);
}
fill(0, 0, 255);
rect(this.body[0][0] * a, this.body[0][1] * a, a, a);
}
this.canEat = function(v) {
return (this.x === v.x && this.y === v.y);
}
this.eat = function() {
this.body.push([this.x, this.y]);
}
this.contains = function(v, s) {
for (var i = s || 0; i < this.body.length; ++i) {
if (this.body[i][0] === v.x &&
this.body[i][1] === v.y) return true;
}
return false;
}
}
function setup() {
createCanvas(cols * a, rows * a);
frameRate(10);
s = new Snake();
generateFood();
}
function draw() {
background(30);
if (!s.isDead()) {
s.update();
if (s.canEat(f)) {
s.eat(f);
generateFood();
}
frameRate(10 + s.len() / 2);
}
s.draw();
fill(255, 0, 0);
rect(f.x * a, f.y * a, a, a);
if (s.isDead()){
textSize(32);
textAlign(CENTER);
fill(255, 0, 255);
text('Game Over!', cols * a / 2, rows * a /2);
textSize(16);
fill(255, 255, 0);
text('Press enter to restart', cols * a / 2, rows * a / 2 + 2 * a);
}
}
function generateFood() {
while (true) {
f = createVector(floor(random()*cols), floor(random()*rows));
if (!s.contains(f)) break;
}
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
s.dir(-1, 0);
} else if (keyCode == RIGHT_ARROW) {
s.dir(1, 0);
} else if (keyCode == UP_ARROW) {
s.dir(0, -1);
} else if (keyCode == DOWN_ARROW) {
s.dir(0, 1);
} else if (keyCode == ENTER) {
if (s.isDead()) {
setup();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment