-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
98 lines (87 loc) · 2.83 KB
/
app.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
95
96
97
98
const playBoard = document.querySelector(".play-board")
const score = document.querySelector(".score")
const higthScoreElement = document.querySelector(".hight-score")
let GameeOver = false
let foodX, foodY;
let snakeX = 5, snakeY = 10;
let snakeBody = []
let velocityX = 0, velocityY = 0;
let setIntervalId;
let scoreUpdate = 0
//punteggio
let higthScore = localStorage.getItem("higth-score") || 0
higthScoreElement.innerText = `higth score: ${higthScore}`
const changePosition = () => {
//funzione che cambia la posizione da 0 a 30
foodX = Math.floor(Math.random() * 30) + 1;
foodY = Math.floor(Math.random() * 30) + 1;
}
//comandi da tastiera
const changeDirection = (e) => {
if (e.key === "ArrowUp") {
velocityX = 0
velocityY = -1
}
else if (e.key === "ArrowDown") {
velocityX = 0
velocityY = 1
}
else if (e.key === "ArrowLeft") {
velocityX = -1
velocityY = 0
}
else if (e.key === "ArrowRight") {
velocityX = 1
velocityY = 0
}
console.log(e);
}
const handeGameOver = () => {
alert("game Over")
// initGame()
clearInterval(setIntervalId)
location.reload()
// localStorage.getItem(scoreUpdate)
}
const initGame = () => {
let htmlMarkup = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`
if (GameeOver) return handeGameOver()
//aggiunge un elemento ogni volta che il serpente mangia e cambia posizione al cibo
if (snakeX === foodX && snakeY === foodY) {
changePosition()
snakeBody.push([foodX, foodY])
console.log(snakeBody);
scoreUpdate++
score.innerText = `score: ${scoreUpdate}`
higthScore = scoreUpdate > higthScore ? scoreUpdate : higthScore
console.log(higthScore);
localStorage.setItem(`higth-score`, higthScore)
higthScoreElement.innerText = `higth score: ${higthScore}`
}
for (let i = snakeBody.length - 1; i > 0; i--) {
snakeBody[i] = snakeBody[i - 1]
}
//collisione con le pareti
if (snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
// alert("game over")
GameeOver = true
}
//setta la prima posizione del serpente
snakeBody[0] = [snakeX, snakeY]
//update della direzione
snakeX += velocityX
snakeY += velocityY
//aggiorna l'elemento serpente
for (let i = 0; i < snakeBody.length; i++) {
htmlMarkup += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`
if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
GameeOver = true
}
}
playBoard.innerHTML = htmlMarkup
}
changePosition()
setIntervalId = setInterval(initGame, 125);
// changeDirection()
document.addEventListener("keydown", changeDirection)
localStorage.getItem(snakeBody)