¡Excelente idea! Crear un Space Invaders moderno directamente en HTML, CSS y JavaScript, todo en una sola página, es un desafío divertido que muestra el poder de estas tecnologías.
Aquí tienes el código completo. He utilizado el elemento <canvas> para los gráficos del juego, ya que ofrece un control mucho mayor y mejor rendimiento para animaciones complejas que usar muchos divs. El CSS se encargará de la estética moderna, los efectos visuales y el posicionamiento de los elementos de la interfaz.
Copia y pega todo este código en un único archivo index.html (o el nombre que prefieras) y ábrelo en tu navegador.
html
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space Invaders Moderno</title>
<style>
/* Estilos generales y modernos */
body {
margin: 0;
overflow: hidden; /* Evita barras de desplazamiento */
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(to bottom, #000000, #1a0033); /* Fondo oscuro espacial */
font-family: 'Press Start 2P', cursive; /* Fuente retro-moderna, se importará después */
color: #00ffcc; /* Color futurista */
text-shadow: 0 0 8px #00ffcc, 0 0 15px #00ffcc; /* Efecto neón */
position: relative; /* Para posicionar elementos absolutos dentro */
}
/* Importa la fuente retro */
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
/* Contenedor del juego */
#game-container {
position: relative;
width: 800px; /* Ancho fijo del canvas */
height: 600px; /* Alto fijo del canvas */
background-color: rgba(0, 0, 0, 0.8); /* Fondo del juego semi-transparente */
border: 5px solid #00ffcc; /* Borde neón */
box-shadow: 0 0 20px #00ffcc, inset 0 0 10px #00ffcc; /* Sombra y resplandor */
border-radius: 10px;
overflow: hidden; /* Esconde cualquier desbordamiento */
}
/* Canvas del juego */
canvas {
display: block;
width: 100%;
height: 100%;
}
/* Elementos de la interfaz de usuario (HUD) */
#hud {
position: absolute;
top: 15px;
left: 15px;
right: 15px;
display: flex;
justify-content: space-between;
font-size: 1.2em;
pointer-events: none; /* Permite clics a través de él si no es interactivo */
z-index: 10;
}
#score, #lives {
background-color: rgba(0, 255, 204, 0.1);
padding: 5px 15px;
border-radius: 5px;
border: 1px solid rgba(0, 255, 204, 0.5);
box-shadow: 0 0 8px rgba(0, 255, 204, 0.6);
}
/* Pantallas de inicio y fin de juego */
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.9);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 20;
text-align: center;
opacity: 0;
visibility: hidden;
transition: opacity 0.5s ease, visibility 0.5s ease;
}
.overlay.active {
opacity: 1;
visibility: visible;
}
.overlay h1 {
font-size: 3em;
margin-bottom: 20px;
color: #00e6b8;
text-shadow: 0 0 15px #00e6b8, 0 0 25px #00e6b8;
}
.overlay p {
font-size: 1.5em;
margin-bottom: 30px;
color: #b3ffeb;
}
.overlay button {
background-color: #00ffcc;
color: #000;
border: 2px solid #00ffcc;
padding: 15px 30px;
font-family: 'Press Start 2P', cursive;
font-size: 1.5em;
cursor: pointer;
border-radius: 8px;
box-shadow: 0 0 15px #00ffcc;
transition: all 0.3s ease;
}
.overlay button:hover {
background-color: #00e6b8;
box-shadow: 0 0 25px #00e6b8, 0 0 40px #00e6b8;
transform: translateY(-3px);
}
/* Controles - Guía */
#controls-guide {
position: absolute;
bottom: 15px;
left: 15px;
right: 15px;
font-size: 0.9em;
text-align: center;
color: rgba(0, 255, 204, 0.6);
z-index: 10;
}
</style>
</head>
<body>
<div id="game-container">
<div id="hud">
<div id="score">SCORE: 0</div>
<div id="lives">LIVES: 3</div>
</div>
<canvas id="gameCanvas"></canvas>
<div id="startScreen" class="overlay active">
<h1>SPACE INVADERS<br>MODERNO</h1>
<p>Destruye a los invasores antes de que lleguen a la Tierra!</p>
<button id="startButton">INICIAR JUEGO</button>
</div>
<div id="gameOverScreen" class="overlay">
<h1>GAME OVER</h1>
<p id="finalScore">Tu puntuación: 0</p>
<button id="restartButton">JUGAR DE NUEVO</button>
</div>
<div id="gameWinScreen" class="overlay">
<h1>¡VICTORIA!</h1>
<p id="winScore">Has defendido la galaxia: 0</p>
<button id="playAgainButton">JUGAR DE NUEVO</button>
</div>
<div id="controls-guide">
← / → : Mover | ESPACIO : Disparar
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Establecer el tamaño del canvas (se ajustará con CSS)
canvas.width = 800;
canvas.height = 600;
// Elementos del HUD y pantallas
const scoreDisplay = document.getElementById('score');
const livesDisplay = document.getElementById('lives');
const startScreen = document.getElementById('startScreen');
const gameOverScreen = document.getElementById('gameOverScreen');
const gameWinScreen = document.getElementById('gameWinScreen');
const startButton = document.getElementById('startButton');
const restartButton = document.getElementById('restartButton');
const playAgainButton = document.getElementById('playAgainButton');
const finalScoreDisplay = document.getElementById('finalScore');
const winScoreDisplay = document.getElementById('winScore');
// Constantes del juego
const PLAYER_SPEED = 7;
const BULLET_SPEED = 10;
const ENEMY_BULLET_SPEED = 5;
const ENEMY_SPEED_X = 1.5;
const ENEMY_SPEED_Y = 20;
const ENEMY_COLS = 10;
const ENEMY_ROWS = 5;
const ENEMY_SPACING_X = 60;
const ENEMY_SPACING_Y = 40;
const ENEMY_HP = 1; // Salud de los enemigos
const MAX_ENEMY_BULLETS = 5; // Max balas enemigas en pantalla
const ENEMY_SHOT_INTERVAL = 1000; // Intervalo mínimo de disparo enemigo (ms)
// Variables del juego
let player;
let bullets = [];
let enemies = [];
let enemyBullets = [];
let score = 0;
let lives = 3;
let gameRunning = false;
let enemyDirection = 1; // 1 para derecha, -1 para izquierda
let lastEnemyMoveTime = 0;
let enemyMoveInterval = 500; // ms, cuánto más bajo más rápido
let lastPlayerShotTime = 0;
const PLAYER_SHOT_COOLDOWN = 300; // ms
// Control de teclado
const keys = {
ArrowLeft: false,
ArrowRight: false,
Space: false
};
// --- Clases de los objetos del juego ---
class Player {
constructor() {
this.width = 50;
this.height = 30;
this.x = canvas.width / 2 - this.width / 2;
this.y = canvas.height - this.height - 30;
this.color = '#00ffcc';
}
draw() {
ctx.save();
ctx.translate(this.x + this.width / 2, this.y + this.height / 2); // Centrar para rotar si fuera necesario
// Efecto de brillo
ctx.shadowBlur = 15;
ctx.shadowColor = this.color;
ctx.fillStyle = this.color;
ctx.beginPath();
// Base del triángulo
ctx.moveTo(-this.width / 2, this.height / 2);
ctx.lineTo(this.width / 2, this.height / 2);
// Parte superior
ctx.lineTo(0, -this.height / 2);
ctx.closePath();
ctx.fill();
// Ventanilla (opcional, para detalle)
ctx.fillStyle = '#ADD8E6'; // Azul claro
ctx.beginPath();
ctx.arc(0, -this.height / 4, this.width / 8, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
move() {
if (keys.ArrowLeft && this.x > 0) {
this.x -= PLAYER_SPEED;
}
if (keys.ArrowRight && this.x < canvas.width - this.width) {
this.x += PLAYER_SPEED;
}
}
shoot() {
const now = Date.now();
if (now - lastPlayerShotTime > PLAYER_SHOT_COOLDOWN) {
bullets.push(new Bullet(this.x + this.width / 2 - 2, this.y, -BULLET_SPEED, '#00ffcc')); // Balas hacia arriba
lastPlayerShotTime = now;
}
}
}
class Bullet {
constructor(x, y, dy, color) {
this.x = x;
this.y = y;
this.width = 4;
this.height = 12;
this.dy = dy; // Velocidad en Y (positivo hacia abajo, negativo hacia arriba)
this.color = color;
this.active = true; // Para saber si está activa y debería ser dibujada
}
draw() {
if (!this.active) return;
ctx.save();
ctx.shadowBlur = 10;
ctx.shadowColor = this.color;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.restore();
}
update() {
this.y += this.dy;
// Marcar para eliminación si está fuera de pantalla
if (this.y < -this.height || this.y > canvas.height) {
this.active = false;
}
}
}
class Enemy {
constructor(x, y) {
this.width = 40;
this.height = 30;
this.x = x;
this.y = y;
this.color = '#ff6666'; // Rojo para los enemigos
this.hp = ENEMY_HP;
this.active = true; // Si está activo o ha sido destruido
}
draw() {
if (!this.active) return;
ctx.save();
ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
// Efecto de brillo
ctx.shadowBlur = 10;
ctx.shadowColor = this.color;
ctx.fillStyle = this.color;
ctx.beginPath();
// Cuerpo principal
ctx.rect(-this.width / 2, -this.height / 2, this.width, this.height);
// Patas (simples rectángulos)
ctx.rect(-this.width / 2 + 5, this.height / 2, 5, 10); // Izq
ctx.rect(this.width / 2 - 10, this.height / 2, 5, 10); // Der
// Ojos
ctx.fillStyle = '#FFF'; // Blanco
ctx.arc(-this.width / 4, -this.height / 4, 3, 0, Math.PI * 2);
ctx.arc(this.width / 4, -this.height / 4, 3, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
takeHit() {
this.hp--;
if (this.hp <= 0) {
this.active = false;
return true; // Devuelve true si fue destruido
}
return false;
}
}
// --- Funciones del juego ---
function initGame() {
player = new Player();
bullets = [];
enemies = [];
enemyBullets = [];
score = 0;
lives = 3;
enemyDirection = 1;
lastEnemyMoveTime = 0;
enemyMoveInterval = 500; // Resetear la velocidad de los enemigos
lastPlayerShotTime = 0;
scoreDisplay.textContent = `SCORE: ${score}`;
livesDisplay.textContent = `LIVES: ${lives}`;
// Crear enemigos en cuadrícula
for (let row = 0; row < ENEMY_ROWS; row++) {
for (let col = 0; col < ENEMY_COLS; col++) {
const x = col * ENEMY_SPACING_X + 50; // Offset inicial
const y = row * ENEMY_SPACING_Y + 50; // Offset inicial
enemies.push(new Enemy(x, y));
}
}
hideScreens();
}
function hideScreens() {
startScreen.classList.remove('active');
gameOverScreen.classList.remove('active');
gameWinScreen.classList.remove('active');
}
function updateGame() {
if (!gameRunning) return;
// 1. Mover jugador
player.move();
// 2. Disparar jugador si se presiona espacio
if (keys.Space) {
player.shoot();
}
// 3. Actualizar balas del jugador
bullets.forEach(bullet => bullet.update());
bullets = bullets.filter(bullet => bullet.active); // Limpiar balas inactivas
// 4. Mover enemigos
const now = Date.now();
if (now - lastEnemyMoveTime > enemyMoveInterval) {
let hitEdge = false;
for (const enemy of enemies) {
if (enemy.active) {
enemy.x += ENEMY_SPEED_X * enemyDirection;
if (enemy.x + enemy.width > canvas.width || enemy.x < 0) {
hitEdge = true;
}
}
}
if (hitEdge) {
enemyDirection *= -1; // Invertir dirección
for (const enemy of enemies) {
if (enemy.active) {
enemy.y += ENEMY_SPEED_Y; // Bajar
// Comprobar si los enemigos han alcanzado al jugador
if (enemy.y + enemy.height > player.y) {
gameOver(false); // Invasión
return;
}
}
}
}
lastEnemyMoveTime = now;
}
// 5. Los enemigos disparan
if (enemyBullets.length < MAX_ENEMY_BULLETS && enemies.length > 0) {
const aliveEnemies = enemies.filter(e => e.active);
if (aliveEnemies.length > 0) {
if (Math.random() < 0.015) { // Probabilidad de disparo por frame
const shooter = aliveEnemies[Math.floor(Math.random() * aliveEnemies.length)];
enemyBullets.push(new Bullet(shooter.x + shooter.width / 2 - 2, shooter.y + shooter.height, ENEMY_BULLET_SPEED, '#ff0000')); // Balas rojas hacia abajo
}
}
}
// 6. Actualizar balas enemigas
enemyBullets.forEach(bullet => bullet.update());
enemyBullets = enemyBullets.filter(bullet => bullet.active);
// 7. Detección de colisiones: Bala del jugador vs. Enemigo
bullets.forEach(bullet => {
if (!bullet.active) return;
enemies.forEach(enemy => {
if (enemy.active && isColliding(bullet, enemy)) {
bullet.active = false; // Desactivar bala
if (enemy.takeHit()) { // Si el enemigo fue destruido
score += 100;
scoreDisplay.textContent = `SCORE: ${score}`;
}
}
});
});
enemies = enemies.filter(enemy => enemy.active); // Limpiar enemigos destruidos
// 8. Detección de colisiones: Bala enemiga vs. Jugador
enemyBullets.forEach(bullet => {
if (!bullet.active) return;
if (isColliding(bullet, player)) {
bullet.active = false;
lives--;
livesDisplay.textContent = `LIVES: ${lives}`;
if (lives <= 0) {
gameOver(true); // El jugador se quedó sin vidas
}
}
});
// 9. Comprobar victoria
if (enemies.length === 0 && gameRunning) {
gameWin();
}
}
function renderGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Limpiar canvas
// Dibujar jugador
player.draw();
// Dibujar balas del jugador
bullets.forEach(bullet => bullet.draw());
// Dibujar enemigos
enemies.forEach(enemy => enemy.draw());
// Dibujar balas enemigas
enemyBullets.forEach(bullet => bullet.draw());
}
// Función de detección de colisiones AABB (Axis-Aligned Bounding Box)
function isColliding(rect1, rect2) {
return rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y;
}
function gameLoop() {
if (!gameRunning) return; // Detener el bucle si el juego no está corriendo
updateGame();
renderGame();
requestAnimationFrame(gameLoop); // Solicitar el siguiente frame
}
function gameOver(hitByBullet) {
gameRunning = false;
gameOverScreen.classList.add('active');
finalScoreDisplay.textContent = `Tu puntuación: ${score}`;
if (!hitByBullet) {
finalScoreDisplay.textContent += "\n¡Los invasores llegaron a la Tierra!";
}
}
function gameWin() {
gameRunning = false;
gameWinScreen.classList.add('active');
winScoreDisplay.textContent = `Has defendido la galaxia con ${score} puntos!`;
}
// --- Manejadores de eventos ---
document.addEventListener('keydown', (e) => {
if (e.code in keys) {
keys[e.code] = true;
if (e.code === 'Space' && gameRunning) {
e.preventDefault(); // Previene que la barra espaciadora haga scroll
}
}
});
document.addEventListener('keyup', (e) => {
if (e.code in keys) {
keys[e.code] = false;
}
});
startButton.addEventListener('click', () => {
gameRunning = true;
initGame();
gameLoop();
});
restartButton.addEventListener('click', () => {
gameRunning = true;
initGame();
gameLoop();
});
playAgainButton.addEventListener('click', () => {
gameRunning = true;
initGame();
gameLoop();
});
// Mostrar pantalla de inicio al cargar
window.onload = () => {
startScreen.classList.add('active');
};
</script>
</body>
</html>
Explicación de los elementos clave:
HTML (<body>):
#game-container: Es el div principal que contiene todo el juego. Le damos un tamaño fijo y un borde moderno con sombras.
#hud: Contenedor para la puntuación (#score) y las vidas (#lives). Posicionado absolutamente en la parte superior.
#gameCanvas: El corazón del juego. Aquí es donde JavaScript dibujará todos los elementos gráficos.
.overlay: Son divs que se superponen al canvas para mostrar pantallas de "Inicio", "Game Over" o "Victoria". Se controlan su visibilidad con la clase active y transiciones CSS para un efecto suave.
#controls-guide: Una pequeña guía de controles en la parte inferior.
CSS (<style>):
Estilo General: Usa una fuente retro (Press Start 2P), un fondo oscuro con gradiente y colores neón (#00ffcc, #ff6666) para el texto y los bordes.
#game-container: Define el "marco" del juego, con un fondo semi-transparente y un borde con box-shadow para el efecto de resplandor.
canvas: Asegura que el canvas ocupe todo el espacio del contenedor.
#hud: Estiliza la información de puntuación y vidas, dándoles un aspecto "flotante" con transparencia y sombras.
.overlay: Controla la apariencia de las pantallas de inicio/fin. Usan position: absolute para cubrir el juego, flexbox para centrar su contenido, background-color con rgba para la transparencia, y transiciones para una aparición/desaparición suave.
button: Estilos para los botones de inicio/reinicio, con efecto neón y hover para interacción.
JavaScript (<script>):
Obtención de Elementos: Accede al canvas, su contexto 2D (ctx) y los elementos del DOM necesarios.
Constantes y Variables: Define valores para la velocidad, tamaño de los elementos, etc., y variables para el estado del juego (jugador, balas, enemigos, puntuación, vidas, etc.).
Con este código, obtendrás un Space Invaders funcional con una estética moderna y limpia, todo en un solo archivo HTML. ¡Espero que lo disfrutes!
Player: Dibuja el jugador como una nave triangular con un pequeño brillo. Tiene métodos para moverse y disparar.
Bullet: Dibuja las balas como rectángulos brillantes. Se mueven en una dirección dy.
Enemy: Dibuja a los enemigos con una forma más elaborada que un simple cuadrado, con "ojos" y "patas". Tienen hp (puntos de vida) para permitir enemigos más resistentes en el futuro (aunque aquí todos tienen 1 HP).
initGame(): Reinicia todas las variables del juego y crea la cuadrícula de enemigos al inicio de cada partida.
updateGame(): Es la función principal de la lógica del juego.
Mueve al jugador.
Gestiona el disparo del jugador.
Actualiza la posición de todas las balas (jugador y enemigo).
Mueve a los enemigos lateralmente y los hace bajar cuando llegan a los bordes.
Implementa el disparo aleatorio de los enemigos.
Realiza la detección de colisiones entre balas/enemigos y balas/jugador.
Comprueba las condiciones de "Game Over" (vidas agotadas o enemigos invadiendo) y "Victoria" (todos los enemigos destruidos).
renderGame(): Borra el canvas y redibuja todos los elementos en sus nuevas posiciones.
isColliding(rect1, rect2): Una función auxiliar para detectar si dos rectángulos se superponen (colisión).
gameLoop(): Utiliza requestAnimationFrame para crear un bucle de juego suave y eficiente que llama a updateGame y renderGame continuamente. Se detiene si gameRunning es false.
gameOver() / gameWin(): Funciones para manejar el final del juego, mostrando la pantalla correspondiente y deteniendo el bucle.
Event Listeners: Capturan las pulsaciones de teclado para mover al jugador y disparar, y los clics en los botones de las pantallas de inicio/fin para empezar nuevas partidas.