-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
94 lines (83 loc) · 2.33 KB
/
game.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import {
gameBoard,
snakeBody,
snakeSpeed,
appendNewSnakeSegment,
drawSnake,
updateSnake,
manipulateSpeeed
} from './snake.js';
import {
checkIfSnakeAte,
drawFood,
updateFood,
setFoodStarterPosition
} from "./food.js";
let lastRenderTime = 0
let globalID;
const snakeStarterPosition = { 'x' : 11, 'y' : 11}
const foodStarterPosition = { 'x' : 13, 'y' : 13}
const xAxisEdgeCases = [-1,21]
const yAxisEdgeCases = [-1,22]
window.addEventListener("load", function(){
snakeBody.push(snakeStarterPosition)
setFoodStarterPosition(foodStarterPosition)
})
let controlPanel = document.getElementById('controlPanel')
controlPanel.addEventListener('click', (event) =>{
let clickedButton = event.target
if (clickedButton.id === "start-continue"){
if (clickedButton.innerHTML === 'Restart'){
document.location.reload()
}else{
window.requestAnimationFrame(initGame)
clickedButton.innerHTML = 'Continue'
}
}else if (clickedButton.id === "pause"){
pauseGame()
}else if (clickedButton.id === "speed-up"){
manipulateSpeeed('add')
}else{
manipulateSpeeed('subtract')
}
})
function initGame(currentTime) {
// if (globalID === 600){gameOver()}
globalID = window.requestAnimationFrame(initGame)
const secondsSinceLastRender = (currentTime - lastRenderTime)/1000 // divide milliseconds to seconds
if (secondsSinceLastRender < 1 / snakeSpeed){return}
lastRenderTime = currentTime
console.log(snakeSpeed)
if (checkGameOver()){return}
update()
draw()
}
export function pauseGame(){
cancelAnimationFrame(globalID)
}
function update(){
updateSnake()
if (checkIfSnakeAte()){
updateFood()
appendNewSnakeSegment()
}
}
function draw(){
gameBoard.innerText=''
drawSnake()
drawFood()
}
function checkGameOver(){
if (xAxisEdgeCases.includes(snakeBody[0].x) || yAxisEdgeCases.includes(snakeBody[0].y)){
gameOver()
return true
}
}
function gameOver(){
pauseGame()
let gameOverElement = document.createElement("div")
gameOverElement.classList.add('error-message-container')
gameOverElement.innerHTML = '<h1>GAME OVER !!</h1>'
gameBoard.appendChild(gameOverElement)
document.getElementById("start-continue").innerText = 'Restart'
}