xxxxxxxxxx
116
let snake;
let apple;
let intersecting;
let gameOver = false,
paused = false,
newHS = false;
let score = 0,
highscore = 0;
let EASY = 0,
MEDIUM = 1,
HARD = 2;
let mode = HARD;
let size = 5;
function setup() {
createCanvas(400, 400);
if (mode == HARD) {
size = 3;
}
snake = new Snake(width / 2, height / 2);
apple = createVector(random(20, width - 20), random(20, height - 20));
}
function draw() {
background(96, 175, 56);
push();
textAlign(LEFT, TOP);
textSize(20);
text("Score: " + score, 10, 10);
pop();
if (!gameOver) {
intersecting = circlesIntersect(snake.pos, size, apple, size);
if (!paused) {
snake.update();
}
snake.show();
if (intersecting) {
changeApplePos();
}
push();
ellipseMode(CENTER);
noStroke();
fill(255, 0, 0);
circle(apple.x, apple.y, size * 2);
pop();
}
if (score > highscore) {
highscore = score;
newHS = true;
}
if (paused) {
push();
rectMode(CORNER);
noFill();
stroke(0);
strokeWeight(3);
rect(5, 5, 30, 30);
line(15, 12.5, 15, 27.5);
line(25, 12.5, 25, 27.5);
pop();
}
snake.checkGameOver();
}
function changeApplePos() {
apple = createVector(random(20, width - 20), random(20, height - 20));
for (let p of snake.prevPos) {
if (circlesIntersect(apple, size, p, size)) {
changeApplePos();
}
}
}
function keyPressed() {
if ((key == "r" || key == "R") && gameOver) {
gameOver = false;
paused = false;
newHS = false;
snake.pos = createVector(width / 2, height / 2);
snake.angle = 0;
snake.prevPos = [];
snake.len = 15;
score = 0;
}
if ((key == "p" || key == "P") & !gameOver) {
paused = !paused;
}
}
function circlesIntersect(c1, r1, c2, r2) {
let dist = p5.Vector.dist(c1, c2);
if (dist < r1 + r2) {
return true;
}
return false;
}
function GameOver() {
background(96, 175, 56);
gameOver = true;
fill(0);
noStroke();
textSize(50);
textAlign(CENTER);
text("GAME OVER", width / 2, height / 2);
textSize(25);
text("Score: " + score, width / 2, 2 * height / 3);
text("Highscore: " + highscore, width / 2, 3 * height / 4);
if (newHS) {
text("NEW HIGHSCORE!", width / 2, 5 * width / 6);
}
// noLoop();
}