forked from WebDevSimplified/Javascript-Snake-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfood.js
28 lines (24 loc) · 726 Bytes
/
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
import { onSnake, expandSnake } from './snake.js'
import { randomGridPosition } from './grid.js'
let food = getRandomFoodPosition()
const EXPANSION_RATE = 5
export function update() {
if (onSnake(food)) {
expandSnake(EXPANSION_RATE)
food = getRandomFoodPosition()
}
}
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)
}
function getRandomFoodPosition() {
let newFoodPosition
while (newFoodPosition == null || onSnake(newFoodPosition)) {
newFoodPosition = randomGridPosition()
}
return newFoodPosition
}