vida
Cómo Crear un Juego de Vida con JavaScript (Paso a Paso)
¿Quieres programar un juego simple donde un personaje pierde vida al chocar con obstáculos? ¡Aquí te explico cómo funciona este código desde cero!
🔷 1. Estructura HTML Básica
Primero, creamos un <canvas> (lienzo) donde se dibujará el juego:
<!DOCTYPE html>
<html>
<head>
<title>Protagonista con Barra de Vida</title>
</head>
<body onload="inicializa()">
<canvas id="canvas" width="500" height="300" style="border:2px solid #000"></canvas>
</body>
</html><canvas>: Es nuestro "tablero de dibujo" (500x300 píxeles).onload="inicializa()": Cuando la página carga, ejecuta la funcióninicializa().
🔷 2. Configuración Inicial (JavaScript)
var canvas, ctx;
var FPS = 50; // Fotogramas por segundo
var imgMega = new Image();
imgMega.src = 'img/mega.jpeg'; // Imagen del protagonista
function inicializa() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"); // Contexto para dibujar
setInterval(principal, 1000 / FPS); // Bucle del juego
}ctx: Permite dibujar formas, imágenes y texto en el canvas.setInterval: Ejecuta la funciónprincipal()50 veces por segundo (para animación fluida).
🔷 3. El Protagonista (Barra de Vida y Movimiento)
var protagonista = function(x, y) {
this.x = x; // Posición X
this.y = y; // Posición Y
this.velocidad = 3;
this.vida = 100; // Vida inicial (100%)
// Dibuja al personaje
this.dibuja = function() {
ctx.drawImage(imgMega, this.x, this.y, 50, 50);
};
// Movimiento (teclas direccionales)
this.arriba = function() { this.y -= this.velocidad; };
this.abajo = function() { this.y += this.velocidad; };
this.izquierda = function() { this.x -= this.velocidad; };
this.derecha = function() { this.x += this.velocidad; };
// Barra de vida (roja)
this.dibujaVida = function() {
ctx.fillStyle = "red";
ctx.fillRect(10, 10, this.vida * 2, 20); // Ancho = vida * 2px
ctx.strokeStyle = "black";
ctx.strokeRect(10, 10, 200, 20); // Borde
};
};
var prota = new protagonista(200, 200); // Crea al protagonistadrawImage: Dibuja una imagen (en este caso,mega.jpeg).dibujaVida: Muestra una barra roja que disminuye al perder vida.
🔷 4. Enemigos (Obstáculos Amarillos)
var personaje = function(x, y) {
this.x = x;
this.y = y;
this.derecha = true; // Dirección inicial
// Dibuja un rectángulo amarillo
this.dibuja = function() {
ctx.fillStyle = "#fff000";
ctx.fillRect(this.x, this.y, 50, 50);
};
// Movimiento automático (izquierda/derecha)
this.mueve = function(velocidad) {
if (this.derecha) {
this.x += velocidad;
if (this.x > 450) this.derecha = false;
} else {
this.x -= velocidad;
if (this.x < 0) this.derecha = true;
}
};
};
// Crea 3 enemigos
var per1 = new personaje(10, 50);
var per2 = new personaje(10, 120);
var per3 = new personaje(10, 230);fillRect: Dibuja un rectángulo (enemigo).mueve: Los enemigos rebotan al llegar a los bordes.
🔷 5. Detección de Colisiones
function colision(a, b) {
return (
a.x < b.x + 50 && // Lógica de superposición
a.x + 50 > b.x &&
a.y < b.y + 50 &&
a.y + 50 > b.y
);
}Si el protagonista toca un enemigo, pierde vida:
if (colision(prota, per1) || colision(prota, per2) || colision(prota, per3)) {
prota.vida -= 1; // ¡Pierde 1% de vida!
}🔷 6. Controles (Teclado)
document.addEventListener('keydown', function(tecla) {
if (tecla.keyCode == 38) prota.arriba(); // Flecha arriba
if (tecla.keyCode == 40) prota.abajo(); // Flecha abajo
if (tecla.keyCode == 37) prota.izquierda(); // Flecha izquierda
if (tecla.keyCode == 39) prota.derecha(); // Flecha derecha
});🔷 7. Bucle Principal del Juego
function principal() {
// Limpia el canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Dibuja y mueve enemigos
per1.dibuja(); per1.mueve(1);
per2.dibuja(); per2.mueve(3);
per3.dibuja(); per3.mueve(2);
// Dibuja protagonista y barra de vida
prota.dibuja();
prota.dibujaVida();
// Game Over si vida <= 0
if (prota.vida <= 0) {
alert("¡Fin del juego! Vida agotada.");
prota.vida = 100; // Reinicia (opcional)
}
}🎮 ¿Cómo Jugar?
Usa las flechas del teclado para mover al personaje.
Evita los bloques amarillos (te quitan vida).
¡No dejes que la barra roja llegue a 0!
👉 Reflexión:
En la vida real, cada obstáculo nos resta energía, pero con estrategia y movimiento, podemos seguir adelante. ¿Qué "enemigos" te quitan vida a ti?
(Código completo en el primer mensaje ⬆️)
Comentarios
Publicar un comentario