Ir al contenido

04. Interaktives Spiel

Erstellung eines einfachen interaktiven Spiels mit HTML, CSS und JavaScript zur Arbeit mit DOM-Manipulation und Events.

0Lesungen

04. Interaktives Spiel mit HTML, CSS und JavaScript

Sección titulada «04. Juego interactivo con HTML, CSS y JavaScript»

In diesem Abschnitt werden wir das Szenario und die Charaktere eines kleinen interaktiven Spiels mit HTML, CSS und JavaScript erstellen. Unser Ziel ist es, die Grundlagen von JavaScript, die DOM-Manipulation, das Event-Management und die objektorientierte Programmierung mit der Erstellung einer einfachen, aber funktionalen Benutzeroberfläche zu kombinieren.

Wir werden sehen, dass es ein klar anfälliges Element im Code gibt, das es einem Angreifer ermöglichen würde, schädlichen Code in die Seite zu injizieren, indem er ein Formular-Input verwendet. Diese Schwachstelle und andere werden im Thema 3 - Web-Sicherheitsprüfungen geprüft, ausgenutzt und korrigiert.

/juego
|-- index.html
|-- index.css
|-- classes.js
|-- main.js

Grundlegendes Szenario: DOM-Management und erste OOP

Sección titulada «Escenario Básico: Gestión del DOM y POO Inicial»

Spiel-Szenario

Wir werden die Datei index.html herunterladen und bearbeiten, um die Grundstruktur unseres Spiels zu erstellen. Wir werden sehen, wie wir die DOM-Elemente erstellen und so konfigurieren, dass sie unseren Anforderungen entsprechen.

<!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>

Anschließend werden wir die Datei index.css erstellen, um die Styles unseres Spiels zu definieren. Hier wenden wir CSS-Regeln an, damit unsere DOM-Elemente attraktiv aussehen und der gewünschten Benutzeroberfläche entsprechen.

* {
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;
}

In diesem Schritt definieren wir die JavaScript-Klassen, die wir für unser Spiel benötigen. Diese Klassen ermöglichen es uns, Objekte und Datenstrukturen zu erstellen, die auf die Anforderungen unseres Spiels zugeschnitten sind.

// --------- 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
}
}

Schließlich werden wir die Datei main.js erstellen, die das Herzstück unseres Spiels sein wird. Hier werden wir die Spiellogik implementieren, die Events verwalten und die Interaktion mit dem Benutzer konfigurieren.

// --------- 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);

Fortgeschrittenes Szenario: Tastatur-Event-Management und Bewegung der Spielobjekte

Sección titulada «Escenario Avanzado: Gestión de Eventos de Teclado y Movimiento de los Objetos del Juego»

In diesem Szenario werden wir bei der Erstellung unseres interaktiven Spiels einen Schritt weitergehen. Wir werden die Tastatur-Event-Verwaltung implementieren, damit der Benutzer intuitiver mit dem Spiel interagieren kann.

// (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 pantalla
const pantallaAncho = window.innerWidth;
const pantallaAlto = window.innerHeight;
const fotogramas = 1000 / 60;
// (main.js) Variables para la gestión de la partida
const 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, alto
const 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 tecla
window.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 juego
setInterval(() => {
// 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);

Vollständiges Szenario: Spiellogik (Kollisionen, Punktzahlen und Spielende)

Sección titulada «Escenario Completo: Lógica del Juego (Colisiones, Puntuaciones y Final de Partida)»

Im finalen Szenario werden wir die Spiellogik vervollständigen. Wir werden die Kollisionserkennung, das Punktesystem und die Bedingung für das Spielende implementieren.

// (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 enemigo
vectorEnemigos.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 vidas
class 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;
}
}
}