xxxxxxxxxx
127
// @AminAhmadAhmadi
// Coding Challenge #3: The Snake Game
// https://youtu.be/AaGK-fj-BAM
var s; //snake
var food;
var scl = 40; //pixel size
var score = 0;
var Hscore = 0;
var lvl = 5; //level
var boxW, boxH;
var ox, oy, nx, ny;
function setup() {
createCanvas(scl * floor(windowWidth / scl), scl * floor(windowHeight / scl));
boxW = width - 2 * scl;
boxH = height - 3 * scl;
s = new snake();
strokeWeight(scl * 0.15);
picklocation();
}
function draw() {
frameRate(lvl);
background(200);
drawGrid();
drawFood();
//draw snake
s.update();
s.show();
s.death();
strokeWeight(scl * 0.15);
drawGame();
}
function picklocation() {
let cols = floor(boxW / scl);
let rows = floor(boxH / scl);
food = createVector(1 + floor(random(cols)), 2 + floor(random(rows)));
food.mult(scl);
for (let i = 0; i < s.tail.length; i++) {
if (s.tail[i] == food) {
picklocation()
}
}
}
function keyPressed() {
if (keyCode == UP_ARROW) {
s.dir(0, -1);
} else if (keyCode == DOWN_ARROW) {
s.dir(0, 1);
} else if (keyCode == LEFT_ARROW) {
s.dir(-1, 0);
} else if (keyCode == RIGHT_ARROW) {
s.dir(1, 0);
}
}
function drawGrid() {
fill(190);
stroke(200);
for (let i = scl; i < width - scl; i += scl) {
for (let j = 2 * scl; j < height - scl; j += scl) {
rect(i, j, scl, scl)
}
}
}
function drawGame() {
// draw game box
noFill();
stroke(51)
rect(scl, 2 * scl, boxW, boxH)
//draw score
fill(51);
noStroke()
textSize(0.7 * scl);
text('Score: ' + score, scl, 0.8 * scl)
text('High Score: ' + Hscore, scl, 1.55 * scl)
}
function drawFood() {
if (s.eat(food)) {
lvl += (1 / lvl);
score += floor(lvl);
if (score > Hscore) {
Hscore = score;
}
picklocation();
}
fill(255, 0, 0);
ellipse(food.x + scl * 0.5, food.y + scl * 0.5, scl, scl);
}
function touchStarted() {
ox = mouseX;
oy = mouseY;
}
function touchEnded() {
nx = mouseX;
ny = mouseY;
if (abs((nx - ox) / (ny - oy)) > 1.5) {
if (ox > nx) {
s.dir(-1, 0);
} else {
s.dir(1, 0);
}
} else if (abs((ny - oy) / (nx - ox)) > 1.5) {
if (oy < ny) {
s.dir(0, 1);
} else {
s.dir(0, -1);
}
}
}