xxxxxxxxxx
79
// Connie Hu
// Sources used
// Coding Challenge #115: Snake Game Redux by Daniel Shiffman
// https://youtu.be/OMoVcohRgZA
let snake;
let rez = 20;
let food;
let w;
let h;
// set up canvas
function setup() {
createCanvas(400, 400);
w = floor(width / rez);
h = floor(height / rez);
frameRate(5);
snake = new Snake();
foodLocation();
}
function foodLocation() {
let x = floor(random(w));
let y = floor(random(h));
food = createVector(x, y);
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
snake.setDir(-1, 0);
} else if (keyCode === RIGHT_ARROW) {
snake.setDir(1, 0);
} else if (keyCode === DOWN_ARROW) {
snake.setDir(0, 1);
} else if (keyCode === UP_ARROW) {
snake.setDir(0, -1);
} else if (key == ' ') {
snake.grow();
}
}
function draw() {
scale(rez);
background('Yellow');
if (snake.eat(food)) {
foodLocation();
}
snake.update();
snake.show();
// Display stats and game over when game ends!
if (snake.endGame()) {
textSize(2);
background('Purple');
print("You Died!") // prints to Console!
fill('white');
text('GAME OVER', 3, 9);
text("Your snake length: ", 2, 11)
text(snake.body.length, 10,13)
noLoop();
return;
}
// spawn food and color
noStroke();
fill("Green"); // green because vegetables are good for you
rect(food.x, food.y, 1, 1);
// display score count!
strokeWeight(0.5)
stroke('Black')
textSize(2);
fill('White');
text(snake.body.length, 18, 3);
}