xxxxxxxxxx
let p1; // variable to store player 1
let food; // variable to store the food
let scl = 20; // Scale for the food
let scoreText; // Varibale to store score as text
// Sets the canvas and game up
function setup() {
createCanvas(600, 600); // Creates a canvas 600x600
background(0); // Sets colour of the background
frameRate(10); // Caps game to 10fps
p1 = new Player(); // Creates a new player
pickLocation(); // Spawns the food
}
// spawns the food in a random location
function pickLocation() {
let fCol = floor(width / scl); // maps out the screen using the size of the player/food
let fRow = floor(height / scl); // maps out the screen using the size of the player/food
food = createVector(floor(random(fCol)), floor(random(fRow))); // creates a random vector for the food
food.mult(scl); // multiples to the scale of the player/food
}
// draws the background and border
function drawBackground() {
background(0); // Sets the background colour
drawBorder(); // Draws border
}
// function to draw/create the border
function drawBorder() {
noFill(); // Removes inside
stroke(255); // Sets border colour
strokeWeight(5); // Sets border thickness
rect(0, 0, width, height); // Draws border
}
// function to draw the score
function drawScore(){
scoreText = textFont('Arial'); // assigning arial font to the text
textSize(26); // sets the text size for the score
textFont(scoreText); // creates the font
fill(255); // Sets the texts colour
noStroke(); // removes outline from the text
textAlign(RIGHT); // Gives the text right alignment
text("Score: " + p1.score, width*0.975, height*0.055);
}
// Draws everything in the game
function draw() {
drawBackground(); // Runs background function
drawScore(); // Draws the score
// if the player eats (food) then spawn a new food
if (p1.eat(food))
pickLocation();
p1.restart(); // adds restart mechanic
p1.update(); // Updates the players position
p1.show(); // Draws the player
fill(255, 0, 0, 100); // colours the food
rect(food.x, food.y, scl, scl); // Draws the food
}
// Takes key inputs and passes on the direction to player function
function keyPressed() {
if (keyCode === UP_ARROW) // Move the player up
p1.dir(0, -1);
else if (keyCode === DOWN_ARROW) // Move the player down
p1.dir(0, 1);
else if (keyCode === LEFT_ARROW) // Move the player left
p1.dir(-1, 0);
else if (keyCode === RIGHT_ARROW) // Move the player right
p1.dir(1, 0);
}