-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
385 lines (341 loc) · 9.72 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
const btnEmpezar = document.querySelector('.btn-empezar')
const pantallaInicio = document.querySelector('.paginaInicio')
const pantallaFinal = document.querySelector('.paginaFinal')
const pantallaJuego = document.querySelector('.paginaGame')
const btnTerminaar = document.querySelector('.btn-reempezar')
const mySong = document.getElementById('mySong')
let nivelActual = 1
const puntosPorNivel = 20
let velocidadObastaculos = 4
btnEmpezar.addEventListener('click', () => {
pantallaInicio.style.display = 'none'
pantallaJuego.style.display = 'flex'
mySong.play()
mySong.volume = 0.05
gameStart()
recuperarPuntuciones()
})
btnTerminaar.addEventListener('click', () => {
pantallaInicio.style.display = 'flex'
pantallaFinal.style.display = 'none'
mySong.pause()
mySong.currentTime = 0
puntuarElemento.innerText = `Puntos: 0`
recuperarPuntuciones()
})
const carreteraFondo = {
x: 0,
y: 0,
w: 100,
h: 100,
velocidad: 3,
}
let roller = null
let obstaculos = []
let frecuenciaObstaculo = 1500
let obstaculosIntervalId = null
let gameIntervalId = null
let recompensaArray = []
function gameStart() {
roller = new Roller()
roller.colisiones = 0
addVidas()
gameIntervalId = setInterval(() => {
loop()
}, Math.round(1000 / 60))
obstaculosIntervalId = setInterval(() => {
addObstaculos()
addRecompensa()
}, frecuenciaObstaculo)
cogerNombre()
}
//movimiento de la carretera
const carretera = document.querySelector('.carretera')
function moverCarretera() {
carreteraFondo.x -= carreteraFondo.velocidad
carretera.style.backgroundPositionX = `${carreteraFondo.x}px `
if (carreteraFondo.x <= window.innerHeight) {
carreteraFondo.y = 0
}
}
function loop() {
obstaculos.forEach((cadaObstaculo) => {
cadaObstaculo.automaticMovement()
})
recompensaArray.forEach((cadaRecompesa) => {
cadaRecompesa.automaticMovement()
})
moverCarretera()
colisonGameOver()
detectarCruces()
detectarCrucePuntuar()
detectarObstaculos()
detectionBorderLimit()
detectarRecompensa()
}
//añadir obstaculos
let obstaculoAlternator = 0
let obstaculaAltura = 250
function addObstaculos() {
const randomPositionY = Math.floor(
Math.random() * (carretera.offsetHeight * 0.25 - obstaculaAltura) +
carretera.offsetHeight * 0.4
)
const espaciadoAdicional = Math.floor(Math.random() * 100)
let nuevoObastaculo = new Ostaculos(
randomPositionY + espaciadoAdicional,
velocidadObastaculos
)
obstaculos.push(nuevoObastaculo)
obstaculoAlternator++
}
function addRecompensa() {
const randomPositionY = Math.floor(
Math.random() * (carretera.offsetHeight * 0.5 - obstaculaAltura) +
carretera.offsetHeight * 0.5
)
const espaciadoAdicional = Math.floor(Math.random() * 50)
let nuevaRecompensa = new Recompensa(
randomPositionY + espaciadoAdicional,
velocidadObastaculos
)
recompensaArray.push(nuevaRecompensa)
}
//comandos
window.addEventListener('keydown', (event) => {
if (event.key === 's') {
roller.move('down')
} else if (event.key === 'w') {
roller.move('up')
} else if (event.key === 'd') {
roller.move('recto')
} else if (event.key === 'a') {
roller.move('atras')
}
})
//detectar limites
function detectionBorderLimit() {
if (roller.y >= pantallaJuego.offsetHeight - roller.h) {
roller.limitdown = true
} else {
roller.limitdown = false
}
if (roller.y <= pantallaJuego.offsetHeight * 0.3) {
roller.limitUp = true
} else {
roller.limitUp = false
}
}
function detectarObstaculos() {
if (obstaculos.length === 0) {
return //si el array esta vacio no se ejecuta
}
for (let i = obstaculos.length - 1; i >= 0; i--) {
if (obstaculos[i].x + obstaculos[i].w <= 0) {
obstaculos[i].node.remove()
obstaculos.splice(i, 1)
}
}
}
//puntuar por cruce
function detectarCrucePuntuar() {
obstaculos.forEach((cadaObstaculo) => {
if (
roller.x + roller.w > cadaObstaculo.x &&
roller.x < cadaObstaculo.x + cadaObstaculo.w &&
roller.y + roller.h > cadaObstaculo.y &&
roller.y < cadaObstaculo.y + cadaObstaculo.h &&
!cadaObstaculo.yaPuntuo
) {
roller.puntuar(1)
actualizarPuntosEnPantalla()
cadaObstaculo.yaPuntuo = true
if (puntos >= nivelActual * puntosPorNivel) {
aumentarNivel()
}
}
})
}
//Cruces
function detectarCruces() {
const mitadAlturaRoller = roller.y + roller.h / 2
obstaculos.forEach((cadaObstaculo) => {
const mitadAlturaObstaculo = cadaObstaculo.y + cadaObstaculo.h / 2
if (
mitadAlturaRoller < mitadAlturaObstaculo &&
roller.x + roller.w > cadaObstaculo.x &&
roller.x < cadaObstaculo.x + cadaObstaculo.w
) {
roller.node.style.zIndex = 0
} else if (
mitadAlturaRoller > mitadAlturaObstaculo &&
roller.x + roller.w > cadaObstaculo.x &&
roller.x < cadaObstaculo.x + cadaObstaculo.w
) {
roller.node.style.zIndex = 1
}
})
}
//coger Recompensas
function detectarRecompensa() {
recompensaArray.forEach((cadaRecompesa) => {
if (
roller.x + roller.w * 0.3 < cadaRecompesa.x + cadaRecompesa.w * 0.7 &&
roller.x + roller.w * 0.7 > cadaRecompesa.x + cadaRecompesa.w * 0.3 &&
roller.y + roller.h * 0.9 < cadaRecompesa.y + cadaRecompesa.h &&
roller.y + roller.h > cadaRecompesa.y + cadaRecompesa.h * 0.9 &&
!cadaRecompesa.yaPuntuo
) {
cadaRecompesa.node.remove()
roller.puntuar(2)
actualizarPuntosEnPantalla()
cadaRecompesa.yaPuntuo = true
}
})
}
//colisiones
const gameOverSound = new Audio('./audios/gameover.mp3')
const collisionSound = new Audio('./audios/grito.wav')
function colisonGameOver() {
obstaculos.forEach((cadaObstaculo, index) => {
// El 0.3 es la parte frontal y el 0.7 es la parte trasera el .0.9 es la parte inferios se refiere a los porcentajes
if (
roller.x + roller.w * 0.3 < cadaObstaculo.x + cadaObstaculo.w * 0.7 &&
roller.x + roller.w * 0.7 > cadaObstaculo.x + cadaObstaculo.w * 0.3 &&
roller.y + roller.h * 0.9 < cadaObstaculo.y + cadaObstaculo.h &&
roller.y + roller.h > cadaObstaculo.y + cadaObstaculo.h * 0.9
) {
roller.colisiones += 1
cambiarImagenJugador()
obstaculos.splice(index, 1)
cadaObstaculo.node.remove()
collisionSound.play()
if (roller.colisiones <= 3) {
arraVidas[roller.colisiones - 1].remove()
}
if (roller.colisiones >= 3) {
gameOverSound.play()
gameOverSound.volume = 0.07
gameOver()
console.log('cataplun')
}
}
})
}
// LocalStorage
function guardarLocalStorage() {
let nombre = cogerNombre()
let puntosJugador = puntos
let nuevaPuntuacion = { nombre, puntosJugador }
let puntuaciones = JSON.parse(localStorage.getItem('puntuaciones')) || []
puntuaciones.push(nuevaPuntuacion)
localStorage.setItem('puntuaciones', JSON.stringify(puntuaciones))
}
function recuperarPuntuciones() {
contenedorPuntos.innerHTML = ''
const puntuaciones = JSON.parse(localStorage.getItem('puntuaciones')) || []
puntuaciones.sort((a, b) => b.puntosJugador - a.puntosJugador)
const top5 = puntuaciones.slice(0, 5)
top5.forEach((puntuacion) => {
const li = document.createElement('li')
li.textContent = `${puntuacion.nombre} .......... ${puntuacion.puntosJugador} puntos`
contenedorPuntos.appendChild(li)
})
puntos = 0
}
// aumentar niveles
function aumentarNivel() {
nivelActual++
carreteraFondo.velocidad += 1
frecuenciaObstaculo -= 200
velocidadObastaculos += 1
clearInterval(obstaculosIntervalId)
obstaculosIntervalId = setInterval(() => {
addRecompensa()
addObstaculos()
}, frecuenciaObstaculo)
obstaculos.forEach((obstaculo) => {
obstaculo.speed += 1
})
recompensaArray.forEach((cadaReconpensa) => {
cadaReconpensa.speed += 1
})
}
const contenedorPuntos = document.querySelector('.contenedorFinal')
function gameOver() {
reset()
clearInterval(gameIntervalId)
clearInterval(obstaculosIntervalId)
pantallaJuego.style.display = 'none'
pantallaFinal.style.display = 'flex'
guardarLocalStorage()
recuperarPuntuciones()
}
function cogerNombre() {
const nombreDelJugador = document.querySelector('#inputName').value
if (!nombreDelJugador) {
return 'Pringao'
}
return nombreDelJugador
}
const playMusicBtn = document.getElementById('playSong')
playMusicBtn.addEventListener('click', function () {
if (!mySong.paused) {
mySong.pause()
mySong.volume = 0.05
playMusicBtn.textContent = 'OFF'
} else {
mySong.play()
playMusicBtn.textContent = 'ON'
mySong.volume = 0.05
}
})
const puntuarElemento = document.querySelector('.puntos')
const actualizarPuntosEnPantalla = () => {
if (puntuarElemento) {
puntuarElemento.innerText = `Puntos:${roller.puntuar(
0
)} - Nivel: ${nivelActual}`
}
}
function cambiarImagenJugador() {
roller.node.src = './image/crahs.png'
roller.node.classList.add('imagenaumenta')
setTimeout(() => {
roller.node.src = './image/patinadora.png'
roller.node.classList.remove('imagenaumenta')
}, 500)
}
// crear vidas
const vidas = document.querySelector('.vidas')
let arraVidas = []
let vidasMax = 3
function addVidas() {
vidas.innerHTML = ''
arraVidas = []
for (let i = 0; i < vidasMax; i++) {
const imgVida = document.createElement('img')
imgVida.src = './image/vidas.png'
imgVida.alt = 'Vida'
vidas.appendChild(imgVida)
arraVidas.push(imgVida)
}
}
addVidas()
// resetear todo
function reset() {
carretera.innerHTML = ''
roller = null
obstaculos = []
recompensaArray = []
nivelActual = 1
velocidadObastaculos = 4
obstaculos.forEach((obstaculo) => {
obstaculo.speed = 4
})
recompensaArray.forEach((cadaReconpensa) => {
cadaReconpensa.speed += 1
})
carreteraFondo.velocidad = 3
frecuenciaObstaculo = 1500
}