-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfood.js
37 lines (33 loc) · 1.17 KB
/
food.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { onSnake, expandSnake } from "./snake.js"
import { randomGridPosition } from "./grid.js"
// VARIABLES
let food = getRandomFoodPosition();
const expansion_rate = 5;
let score = 0;
divScore.innerText="Score: 0";
// if on top of food expand snake and set food to reppear in random position
export function update() {
if (onSnake(food)) {
score++;
expandSnake(expansion_rate);
food = getRandomFoodPosition();
}
divScore.textContent = `${"Score: "}` + score;
}
//create food element and add to gameBoard
export function draw(gameBoard) {
const foodElement = document.createElement('div');
foodElement.style.gridRowStart = food.y;
foodElement.style.gridColumnStart = food.x;
foodElement.classList.add('food');
gameBoard.appendChild(foodElement);
};
// Randomise food position every time it is eaten including not a position on the snake
// uses while loop to ensure that when food is null or on snake already, get new position
function getRandomFoodPosition() {
let newFoodPosition
while (newFoodPosition == null || onSnake(newFoodPosition)) {
newFoodPosition = randomGridPosition();
};
return newFoodPosition;
};