04. Interactive Game
Creating a basic interactive game with HTML, CSS, and JavaScript to practice DOM manipulation and events.
04. Interactive Game with HTML, CSS, and JavaScript
Sección titulada «04. Juego interactivo con HTML, CSS y JavaScript»In this section, we will create the scenario and characters of a small interactive game using HTML, CSS, and JavaScript. Our goal is to combine basic JavaScript concepts, DOM manipulation, event handling, and object-oriented programming with the creation of a simple but functional user interface.
We will see that there is a clearly vulnerable element in the code that would allow an attacker to inject malicious code into the page using a form input. This vulnerability and others will be audited, exploited, and fixed in topic 3 - web security audits.
Project Structure
Sección titulada «Estructura del Proyecto»/juego|-- index.html|-- index.css|-- classes.js|-- main.jsBasic Scenario: DOM Management and Initial OOP
Sección titulada «Escenario Básico: Gestión del DOM y POO Inicial»
index.html
Sección titulada «index.html»We will download the index.html file and edit it to create the basic structure of our game. We will see how we create DOM elements and configure them to suit our needs.
<!DOCTYPE html><html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Juego interactivo HTML, CSS y JavaScript</title> <meta name="description" content="Juego JS para trabajar la manipulación del DOM, la gestión de eventos y la POO." /> <meta name="author" content="Xavi Garcia @xavig-icv" /> <meta name="copyright" content="Xavi Garcia @xavig-icv" /> <link rel="stylesheet" href="./index.css" /> </head> <body> <div id="pantalla"></div> <div id="infoPartida"></div> <script src="./classes.js"></script> <script src="./main.js"></script> </body></html>index.css
Sección titulada «index.css»Next, we will create the index.css file to define the styles of our game. Here, we will apply CSS rules so that our DOM elements look attractive and fit the interface we want.
* { margin: 0; padding: 0; box-sizing: border-box;}
body { overflow: hidden;}
#pantalla { width: 100vw; height: 100vh; background-color: #222; overflow: hidden; z-index: 0;}
.nave { position: absolute; z-index: 1;}
.jugador { background-color: lightblue;}
.enemigo { background-color: lightcoral;}
.asteroide { position: absolute; background-color: rgba(255, 255, 255, 0.5); border-radius: 50%;}
#infoPartida { position: absolute; top: 0; right: 0; padding: 1rem; font-size: 1.25rem; color: white; background-color: rgba(0, 0, 0, 0.2); border-radius: 5px; width: 200px; z-index: 2;}
#infoPartida > p { margin: 0.25rem;}classes.js
Sección titulada «classes.js»In this step, we will define the JavaScript classes we need for our game. These classes will allow us to create objects and data structures that suit the needs of our game.
// --------- Clase Base ---------class Entidad { constructor(posicion = {x: 0, y: 0}, ancho = 50, alto = 50) { this.x = posicion.x; this.y = posicion.y; this.ancho = ancho; this.alto = alto; // Crear el elemento HTML this.elementHTML = document.createElement("div"); this.elementHTML.style.left = this.x + "px"; this.elementHTML.style.top = this.y + "px"; this.elementHTML.style.width = this.ancho + "px"; this.elementHTML.style.height = this.alto + "px"; }
// Modifica la posición del elemento en la pantalla dibujar() { this.elementHTML.style.left = this.x + "px"; this.elementHTML.style.top = this.y + "px"; }
mover() { // Implementar la lógica de movimiento }}main.js
Sección titulada «main.js»Finally, we will create the main.js file, which will be the heart of our game. Here, we will implement the game logic, manage events, and configure user interaction.
// --------- Pantalla del Juego ---------const pantalla = document.querySelector("#pantalla");const infoPartida = document.querySelector("#infoPartida");
// --------- Objeto Jugador ---------const jugador = new Entidad({x: 100, y: 300}, 150, 100);jugador.elementHTML.classList.add("nave", "jugador");pantalla.append(jugador.elementHTML);
// --------- Objeto Enemigo ---------const enemigo = new Entidad({x: 500, y: 200}, 75, 75);enemigo.elementHTML.classList.add("nave", "enemigo");pantalla.append(enemigo.elementHTML);
// ------- Objeto asteroide -------const asteroides = [];for (let i = 0; i < 100; i++) { let posX = Math.floor(Math.random() * 1200); let posY = Math.floor(Math.random() * 800); const asteroide = new Entidad({x: posX, y: posY}, 5, 5); asteroide.elementHTML.classList.add("asteroide"); pantalla.append(asteroide.elementHTML); asteroides.push(asteroide);}
// ------- Información de la partida -------const elementNombre = document.createElement("p");const elementPuntos = document.createElement("p");const elementEliminados = document.createElement("p");const elementVidas = document.createElement("p");elementNombre.innerHTML = `Jugador: Pepito`;infoPartida.append(elementNombre);elementPuntos.innerHTML = `Puntos: 100`;infoPartida.append(elementPuntos);elementEliminados.innerHTML = `Kills: 12`;infoPartida.append(elementEliminados);elementVidas.innerHTML = `Vidas: 2`;infoPartida.append(elementVides);Advanced Scenario: Keyboard Event Management and Game Object Movement
Sección titulada «Escenario Avanzado: Gestión de Eventos de Teclado y Movimiento de los Objetos del Juego»In this scenario, we will advance the creation of our interactive game. We will implement keyboard event management so that the user can interact with the game more intuitively.
// (classes.js) Herencia de Clases y Polimorfismo
class Jugador extends Entidad { constructor(nombre, vidas, velocidad, posicion, ancho, alto) { super(posicion, ancho, alto); this.nombre = nombre; this.vidas = vidas; this.velocidad = velocidad; this.puntos = 0; this.eliminados = 0; this.elementHTML.classList.add("nave", "jugador"); }
mover() { if (this.y < 0) { this.y = 0; } else if (this.y + this.alto > pantallaAlto) { this.y = pantallaAlto - this.alto; } }}
class Enemigo extends Entidad { constructor(velocidad, posicion, ancho, alto) { super(posicion, ancho, alto); this.velocidad = velocidad; this.elementHTML.classList.add("nave", "enemigo"); }
mover() { this.x -= this.velocidad; if (this.x < -this.ancho) { this.x = pantallaAncho + this.ancho; } }}
class Asteroide extends Entidad { constructor(velocidad, posicion, ancho = 5, alto = 5) { super(posicion, ancho, alto); this.velocidad = velocidad; this.elementHTML.classList.add("asteroide"); }
mover() { this.x -= this.velocidad; if (this.x < -this.ancho) { this.x = pantallaAncho + this.ancho; } }}// (main.js) Nuevas variables de pantallaconst pantallaAncho = window.innerWidth;const pantallaAlto = window.innerHeight;const fotogramas = 1000 / 60;// (main.js) Variables para la gestión de la partidaconst nivel = 1;const maxPuntos = 100;const vectorAsteroides = [];const vectorEnemigos = [];const maxAsteroides = 100;const maxEnemigos = 12;// (main.js) Actualización: Instanciación de Clases (Jugador, Enemigo y Asteroides)
// ---- Objeto Jugador ----// Constructor: nombre, vidas, velocidad, posicion, ancho, altoconst jugador = new Jugador("Pepito", 3, 10, {x: 100, y: 300}, 150, 100);pantalla.append(jugador.elementHTML);
// ---- Vector de objetos Enemigo ----for (let i = 0; i < maxEnemigos; i++) { // Creamos un enemigo de 50x50 let posX = pantallaAncho + 50; let posY = Math.floor(Math.random() * (pantallaAlto - 50)); let velocidad = Math.floor(Math.random() * 5) + 1; vectorEnemigos.push(new Enemigo(velocidad, {x: posX, y: posY}, 50, 50)); pantalla.append(vectorEnemigos[i].elementHTML);}
// ---- Vector de objetos Asteroides ----for (let i = 0; i < maxAsteroides; i++) { // Creamos un asteroide de 5x5 let posX = Math.floor(Math.random() * pantallaAncho - 3); let posY = Math.floor(Math.random() * pantallaAlto - 3); let velocidad = Math.floor(Math.random() * 10) + 1; vectorAsteroides.push(new Asteroide(velocidad, {x: posX, y: posY}, 3, 3)); pantalla.append(vectorAsteroides[i].elementHTML);}// (main.js) Actualización de los datos de información de la partida// ------- Información de la partida -------const elementNombre = document.createElement("p");const elementPuntos = document.createElement("p");const elementEliminados = document.createElement("p");const elementVidas = document.createElement("p");elementNombre.innerHTML = `Jugador: ${jugador.nombre}`;infoPartida.append(elementNombre);elementPuntos.innerHTML = `Puntos: ${jugador.puntos}`;infoPartida.append(elementPuntos);elementEliminados.innerHTML = `Kills: ${jugador.eliminados}`;infoPartida.append(elementEliminados);elementVidas.innerHTML = `Vidas: ${jugador.vidas}`;infoPartida.append(elementVidas);// (main.js) Eventos de teclado// Control de la nave del jugador cuando presiona una teclawindow.addEventListener("keydown", (event) => { switch(event.code) { case "ArrowUp": jugador.y -= jugador.velocidad; break; case "ArrowDown": jugador.y += jugador.velocidad; break; default: break; }});// (main.js) Bucle de animación del juegosetInterval(() => { // 1. Gestión del jugador jugador.dibujar(); jugador.mover();
// 2. Gestión de los enemigos vectorEnemigos.forEach(enemigo => { enemigo.dibujar(); enemigo.mover(); });
// 3. Gestión de los asteroides vectorAsteroides.forEach(asteroide => { asteroide.dibujar(); asteroide.mover(); });}, fotogramas);Complete Scenario: Game Logic (Collisions, Scoring, and End of Game)
Sección titulada «Escenario Completo: Lógica del Juego (Colisiones, Puntuaciones y Final de Partida)»In the final scenario, we will complete the game logic. We will implement collision detection, the scoring system, and the condition for the end of the game.
// (main.js) Comprobar colisiones entre el jugador y los enemigos
function comprobarColisiones() { vectorEnemigos.forEach(enemigo => { if (jugador.x <= enemigo.x + enemigo.ancho && jugador.x + jugador.ancho >= enemigo.x && jugador.y <= enemigo.y + enemigo.alto && jugador.y + jugador.alto >= enemigo.y) { // Colisión detectada enemigo.x = pantallaAncho + enemigo.ancho; jugador.puntos = jugador.puntos + (nivel * 10); jugador.eliminados++; infoPartida.querySelector("p:nth-child(2)").innerHTML = `Puntos: ${jugador.puntos}`; infoPartida.querySelector("p:nth-child(3)").innerHTML = `Kills: ${jugador.eliminados}`; if (jugador.puntos >= maxPuntos) { jugador.velocidad = 0; vectorEnemigos.forEach(enemigo => { enemigo.velocidad = 0; }); // Preparar el siguiente nivel alert("¡Nivel superado! :)"); } } });}// (main.js) Controlar las colisiones al bucle de animación// ----- Bucle de animación del juego -----setInterval(() => { // 0. Gestión de colisiones comprobarColisiones();
// 1. Gestión del jugador infoPartida.querySelector("p:nth-child(4)").innerHTML = `Vidas: ${jugador.vidas}`; if (jugador.vidas < 0) { jugador.velocidad = 0; setTimeout(() => { location.reload(); }, 5000); } jugador.dibujar(); jugador.mover(); ... ...// (main.js) Controlar las vidas del jugador cuando un enemigo supera la pantalla// Se debe pasar el objeto "jugador" al constructor del enemigovectorEnemigos.push(new Enemigo(jugador, velocidad, {x: posX, y: posY}, 50, 50));// (classes.js) Añadir al constructor del enemigo e inicializar la variable "jugador" y controlar las vidasclass Enemigo extends Entidad { constructor(jugador, velocidad, posicion, ancho, alto) { super(posicion, ancho, alto); this.jugador = jugador; this.velocidad = velocidad; this.elementHTML.classList.add("nave", "enemigo"); }
mover() { this.x -= this.velocidad; if (this.x < -this.ancho) { this.jugador.vidas--; this.x = pantallaAncho + this.ancho; } }}
