Juego de Supervivencia Zombie en 3D Estilo Minecraft
Aquí tienes un juego de supervivencia zombie en 3D con mecánicas de construcción y recolección, todo en un solo archivo HTML:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ZombieCraft Survival</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/PointerLockControls.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #1a1f25, #0c0e13);
color: #e0e0e0;
overflow: hidden;
height: 100vh;
display: flex;
flex-direction: column;
}
#gameContainer {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
#gameCanvas {
display: block;
width: 100%;
height: 100%;
}
#uiOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 10;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 20px;
height: 20px;
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.7);
border-radius: 50%;
pointer-events: none;
}
#healthBar {
position: absolute;
top: 20px;
left: 20px;
width: 200px;
height: 30px;
background: rgba(0, 0, 0, 0.5);
border: 2px solid #444;
border-radius: 5px;
overflow: hidden;
}
#healthFill {
height: 100%;
width: 100%;
background: linear-gradient(90deg, #e74c3c, #c0392b);
transition: width 0.3s;
}
#staminaBar {
position: absolute;
top: 60px;
left: 20px;
width: 150px;
height: 15px;
background: rgba(0, 0, 0, 0.5);
border: 2px solid #444;
border-radius: 5px;
overflow: hidden;
}
#staminaFill {
height: 100%;
width: 100%;
background: linear-gradient(90deg, #3498db, #2980b9);
transition: width 0.3s;
}
#inventory {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
background: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 10px;
border: 2px solid #444;
}
.inventory-slot {
width: 60px;
height: 60px;
background: rgba(100, 100, 100, 0.4);
border: 2px solid #555;
border-radius: 5px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
pointer-events: auto;
}
.inventory-slot.active {
border-color: #f39c12;
background: rgba(200, 150, 50, 0.3);
transform: scale(1.1);
}
.inventory-slot img {
width: 40px;
height: 40px;
pointer-events: none;
}
.slot-label {
font-size: 12px;
margin-top: 2px;
color: #ddd;
pointer-events: none;
}
#resources {
position: absolute;
top: 20px;
right: 20px;
background: rgba(0, 0, 0, 0.5);
padding: 15px;
border-radius: 10px;
border: 2px solid #444;
}
.resource-item {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.resource-item:last-child {
margin-bottom: 0;
}
.resource-icon {
width: 30px;
height: 30px;
margin-right: 10px;
background: #555;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
#timeDisplay {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.5);
padding: 8px 15px;
border-radius: 20px;
border: 2px solid #444;
font-size: 18px;
text-align: center;
}
#messageBox {
position: absolute;
top: 100px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.7);
padding: 10px 20px;
border-radius: 10px;
border-left: 4px solid #f39c12;
font-size: 16px;
max-width: 400px;
text-align: center;
opacity: 0;
transition: opacity 0.5s;
}
#startScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(rgba(10, 20, 30, 0.9), rgba(5, 10, 15, 0.95));
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 100;
}
#gameTitle {
font-size: 4rem;
font-weight: bold;
color: #e74c3c;
text-shadow: 0 0 10px rgba(231, 76, 60, 0.7);
margin-bottom: 20px;
letter-spacing: 3px;
}
#startButton {
background: linear-gradient(to bottom, #27ae60, #219653);
color: white;
border: none;
padding: 15px 50px;
font-size: 1.5rem;
border-radius: 50px;
cursor: pointer;
margin-top: 40px;
transition: all 0.3s;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
#startButton:hover {
transform: scale(1.05);
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.6);
background: linear-gradient(to bottom, #2ecc71, #27ae60);
}
.controls {
background: rgba(0, 0, 0, 0.6);
padding: 20px;
border-radius: 10px;
margin-top: 30px;
max-width: 500px;
text-align: center;
border: 1px solid #444;
}
.controls h3 {
color: #f39c12;
margin-bottom: 15px;
}
.control-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #333;
}
.control-item:last-child {
border-bottom: none;
}
.key {
background: #444;
padding: 3px 10px;
border-radius: 5px;
min-width: 40px;
display: inline-block;
text-align: center;
}
#gameOver {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.85);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 200;
display: none;
}
#gameOver h2 {
font-size: 4rem;
color: #e74c3c;
margin-bottom: 20px;
}
#restartButton {
background: linear-gradient(to bottom, #e74c3c, #c0392b);
color: white;
border: none;
padding: 15px 50px;
font-size: 1.5rem;
border-radius: 50px;
cursor: pointer;
margin-top: 40px;
transition: all 0.3s;
}
#restartButton:hover {
transform: scale(1.05);
background: linear-gradient(to bottom, #ff5a4d, #e74c3c);
}
.stats {
font-size: 1.5rem;
margin: 10px 0;
color: #f39c12;
}
#ambientSound {
display: none;
}
</style>
</head>
<body>
<div id="gameContainer">
<canvas id="gameCanvas"></canvas>
<div id="uiOverlay">
<div id="crosshair"></div>
<div id="healthBar">
<div id="healthFill"></div>
</div>
<div id="staminaBar">
<div id="staminaFill"></div>
</div>
<div id="timeDisplay">Día 1 | 08:00</div>
<div id="messageBox">Bienvenido a ZombieCraft Survival</div>
<div id="inventory">
<div class="inventory-slot active" data-item="axe">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTE0IDEzbC0xNSAxNW0xMi0zbC00IDQgMTAtMTBtLTMuNS02LjVjLS45NC0uOTQtLjk0LTIuNTYgMC0zLjVzMi41Ni0uOTQgMy41IDBsNSA1Yy45NC45NC45NCAyLjU2IDAgMy41cy0yLjU2Ljk0LTMuNSAwbC01LTV6Ii8+PC9zdmc+" alt="Hacha">
<span class="slot-label">Hacha</span>
</div>
<div class="inventory-slot" data-item="pickaxe">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTIwIDEwaC00bC00IDR2NC4xYTMuOSAzLjkgMCAwIDEtNy44IDB2LTUuOGEzLjk4IDMuOTggMCAwIDEgMi4xLTMuNTRsOC41NC04LjU0YTIgMiAwIDAgMSAyLjgzIDBsMS42NiAxLjY2YTIgMiAwIDAgMSAwIDIuODNMMTMgMTUiLz48L3N2Zz4=" alt="Pico">
<span class="slot-label">Pico</span>
</div>
<div class="inventory-slot" data-item="sword">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTE3IDdsLTUgNS01LTVoMTB6TTcgMTd2NSIgLz48cGF0aCBkPSJNMTcgMTd2NSIgLz48cGF0aCBkPSJNMTIgMnYxMCIgLz48L3N2Zz4=" alt="Espada">
<span class="slot-label">Espada</span>
</div>
<div class="inventory-slot" data-item="wood">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTEyIDV2MTQiIC8+PHBhdGggZD0iTTUgMTJoMTQiIC8+PHBhdGggZD0iTTMgM2wxOCAxOCIgLz48L3N2Zz4=" alt="Madera">
<span class="slot-label">Madera</span>
</div>
<div class="inventory-slot" data-item="stone">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTMgMTJoNmwzIDhsNi0xMm0tMyA4aC0zbC0zLThoLjVtOC41IDRoLjUiIC8+PC9zdmc+" alt="Piedra">
<span class="slot-label">Piedra</span>
</div>
<div class="inventory-slot" data-item="wall">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iMiI+PHBhdGggZD0iTTQgMTh2LTEyaDgiIC8+PHBhdGggZD0iTTEyIDE4di0xMmg4IiAvPjxwYXRoIGQ9Ik0xMiA1djE0IiAvPjxwYXRoIGQ9Ik00IDVoMTYiIC8+PC9zdmc+" alt="Pared">
<span class="slot-label">Pared</span>
</div>
</div>
<div id="resources">
<div class="resource-item">
<div class="resource-icon">W</div>
<div>Madera: <span id="woodCount">0</span></div>
</div>
<div class="resource-item">
<div class="resource-icon">S</div>
<div>Piedra: <span id="stoneCount">0</span></div>
</div>
<div class="resource-item">
<div class="resource-icon">Z</div>
<div>Zombies: <span id="zombieCount">0</span></div>
</div>
</div>
</div>
<div id="startScreen">
<h1 id="gameTitle">ZOMBIECRAFT SURVIVAL</h1>
<p style="font-size: 1.2rem; max-width: 700px; text-align: center; margin-bottom: 30px;">
Sobrevive en un mundo post-apocalíptico lleno de zombies. Recolecta recursos, construye defensas y lucha por tu vida.
</p>
<div class="controls">
<h3>CONTROLES</h3>
<div class="control-item">
<span>Movimiento:</span>
<span><span class="key">W</span> <span class="key">A</span> <span class="key">S</span> <span class="key">D</span></span>
</div>
<div class="control-item">
<span>Saltar:</span>
<span><span class="key">ESPACIO</span></span>
</div>
<div class="control-item">
<span>Correr:</span>
<span><span class="key">SHIFT</span></span>
</div>
<div class="control-item">
<span>Interactuar/Atacar:</span>
<span><span class="key">CLICK IZQ</span></span>
</div>
<div class="control-item">
<span>Construir:</span>
<span><span class="key">CLICK DER</span></span>
</div>
<div class="control-item">
<span>Cambiar objeto:</span>
<span><span class="key">1-6</span> o <span class="key">RUEDA</span></span>
</div>
</div>
<button id="startButton">EMPEZAR A SOBREVIVIR</button>
</div>
<div id="gameOver">
<h2>¡HAS MUERTO!</h2>
<p class="stats">Días sobrevividos: <span id="daysSurvived">0</span></p>
<p class="stats">Zombies eliminados: <span id="zombiesKilled">0</span></p>
<p class="stats">Recursos recolectados: <span id="resourcesCollected">0</span></p>
<button id="restartButton">REINTENTAR</button>
</div>
</div>
<audio id="ambientSound" loop>
<source src="https://assets.mixkit.co/sfx/preview/mixkit-forest-ambience-573.mp3" type="audio/mpeg">
</audio>
<script>
// Variables globales
let scene, camera, renderer, controls;
let player, world = [];
let zombies = [];
let resources = [];
let playerVelocity = new THREE.Vector3();
let playerDirection = new THREE.Vector3();
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = true;
let clock = new THREE.Clock();
let playerHealth = 100;
let playerStamina = 100;
let gameTime = 8 * 60; // Minutos del día (8:00 AM)
let dayCount = 1;
let woodCount = 0;
let stoneCount = 0;
let zombiesKilled = 0;
let resourcesCollected = 0;
let gameActive = false;
let currentItem = 'axe';
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
let lastResourceGathered = 0;
let lastAttack = 0;
let lastZombieSpawn = 0;
let zombieSpawnTimer = 0;
// Inicialización del juego
function init() {
// Crear la escena
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x87CEEB, 50, 200);
scene.background = new THREE.Color(0x87CEEB);
// Crear la cámara
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 10;
// Crear el renderizador
renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('gameCanvas'), antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
// Añadir iluminación
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xffffff, 0.8);
sunLight.position.set(100, 100, 50);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 1024;
sunLight.shadow.mapSize.height = 1024;
scene.add(sunLight);
// Crear el jugador
createPlayer();
// Crear el mundo
createWorld();
// Añadir algunos recursos iniciales
for (let i = 0; i < 20; i++) {
createResource('tree', Math.random() * 100 - 50, 0, Math.random() * 100 - 50);
}
for (let i = 0; i < 15; i++) {
createResource('rock', Math.random() * 100 - 50, 0, Math.random() * 100 - 50);
}
// Iniciar controles
initControls();
// Actualizar UI
updateUI();
// Iniciar animación
animate();
}
// Crear jugador
function createPlayer() {
const geometry = new THREE.CapsuleGeometry(0.5, 1, 4, 8);
const material = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
player = new THREE.Mesh(geometry, material);
player.position.y = 10;
scene.add(player);
}
// Crear mundo
function createWorld() {
// Crear terreno
const groundGeometry = new THREE.PlaneGeometry(200, 200, 50, 50);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x3d8c40,
wireframe: false
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// Añadir algunos bloques al mundo
for (let x = -20; x <= 20; x += 5) {
for (let z = -20; z <= 20; z += 5) {
if (Math.random() > 0.7) continue;
createBlock('grass', x, 0.5, z);
}
}
}
// Crear un bloque
function createBlock(type, x, y, z) {
let color;
switch(type) {
case 'grass': color = 0x4CAF50; break;
case 'wood': color = 0x8B4513; break;
case 'stone': color = 0x9E9E9E; break;
case 'wall': color = 0x607D8B; break;
}
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial({ color: color });
const block = new THREE.Mesh(geometry, material);
block.position.set(x, y, z);
block.castShadow = true;
block.receiveShadow = true;
block.userData = { type: type };
scene.add(block);
world.push(block);
return block;
}
// Crear recurso
function createResource(type, x, y, z) {
let resource;
if (type === 'tree') {
const trunkGeometry = new THREE.CylinderGeometry(0.3, 0.4, 3, 8);
const trunkMaterial = new THREE.MeshPhongMaterial({ color: 0x8B4513 });
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.set(x, y + 1.5, z);
const leavesGeometry = new THREE.SphereGeometry(2, 8, 8);
const leavesMaterial = new THREE.MeshPhongMaterial({ color: 0x2E7D32 });
const leaves = new THREE.Mesh(leavesGeometry, leavesMaterial);
leaves.position.set(x, y + 4, z);
resource = new THREE.Group();
resource.add(trunk);
resource.add(leaves);
resource.userData = { type: 'tree', health: 3 };
} else if (type === 'rock') {
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const rockMaterial = new THREE.MeshPhongMaterial({ color: 0x757575 });
resource = new THREE.Mesh(rockGeometry, rockMaterial);
resource.position.set(x, y + 1, z);
resource.userData = { type: 'rock', health: 2 };
}
resource.castShadow = true;
resource.receiveShadow = true;
scene.add(resource);
resources.push(resource);
return resource;
}
// Crear zombie
function createZombie(x, z) {
const bodyGeometry = new THREE.CapsuleGeometry(0.4, 1, 4, 8);
const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0x4CAF50 });
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.position.y = 1;
const headGeometry = new THREE.SphereGeometry(0.4, 8, 8);
const headMaterial = new THREE.MeshPhongMaterial({ color: 0x388E3C });
const head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 2;
const zombie = new THREE.Group();
zombie.add(body);
zombie.add(head);
zombie.position.set(x, 0, z);
zombie.userData = {
health: 30,
speed: 0.02,
attackDamage: 10,
lastAttack: 0
};
scene.add(zombie);
zombies.push(zombie);
return zombie;
}
// Inicializar controles
function initControls() {
// Controles de movimiento
document.addEventListener('keydown', (event) => {
switch(event.code) {
case 'KeyW': moveForward = true; break;
case 'KeyS': moveBackward = true; break;
case 'KeyA': moveLeft = true; break;
case 'KeyD': moveRight = true; break;
case 'Space': if (canJump) playerVelocity.y = 0.15; canJump = false; break;
case 'ShiftLeft': playerStamina = Math.max(0, playerStamina - 1); break;
}
});
document.addEventListener('keyup', (event) => {
switch(event.code) {
case 'KeyW': moveForward = false; break;
case 'KeyS': moveBackward = false; break;
case 'KeyA': moveLeft = false; break;
case 'KeyD': moveRight = false; break;
}
});
// Controles de ratón
document.addEventListener('mousedown', (event) => {
if (!gameActive) return;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
if (event.button === 0) { // Clic izquierdo
const now = Date.now();
// Comprobar si estamos mirando un recurso
const resourceIntersects = raycaster.intersectObjects(resources);
if (resourceIntersects.length > 0 && now - lastResourceGathered > 500) {
gatherResource(resourceIntersects[0].object);
lastResourceGathered = now;
return;
}
// Comprobar si estamos mirando un zombie
const zombieIntersects = raycaster.intersectObjects(zombies);
if (zombieIntersects.length > 0 && now - lastAttack > 500) {
attackZombie(zombieIntersects[0].object);
lastAttack = now;
return;
}
// Comprobar si estamos mirando un bloque
const blockIntersects = raycaster.intersectObjects(world);
if (blockIntersects.length > 0 && now - lastAttack > 500) {
breakBlock(blockIntersects[0].object);
lastAttack = now;
}
}
if (event.button === 2) { // Clic derecho
placeBlock();
}
});
// Prevenir menú contextual en clic derecho
document.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
// Cambiar objeto seleccionado
document.addEventListener('wheel', (event) => {
if (!gameActive) return;
const slots = document.querySelectorAll('.inventory-slot');
let currentIndex = Array.from(slots).findIndex(slot => slot.classList.contains('active'));
if (event.deltaY > 0) {
currentIndex = (currentIndex + 1) % slots.length;
} else {
currentIndex = (currentIndex - 1 + slots.length) % slots.length;
}
selectItem(slots[currentIndex].dataset.item);
});
// Atajos de teclado para selección de objetos
document.addEventListener('keydown', (event) => {
if (!gameActive) return;
if (event.key >= '1' && event.key <= '6') {
const index = parseInt(event.key) - 1;
const slots = document.querySelectorAll('.inventory-slot');
if (index < slots.length) {
selectItem(slots[index].dataset.item);
}
}
});
// Botón de inicio
document.getElementById('startButton').addEventListener('click', startGame);
// Botón de reinicio
document.getElementById('restartButton').addEventListener('click', restartGame);
}
// Seleccionar objeto
function selectItem(item) {
currentItem = item;
const slots = document.querySelectorAll('.inventory-slot');
slots.forEach(slot => {
if (slot.dataset.item === item) {
slot.classList.add('active');
} else {
slot.classList.remove('active');
}
});
showMessage(`Seleccionado: ${getItemName(item)}`);
}
// Obtener nombre del objeto
function getItemName(item) {
const names = {
'axe': 'Hacha',
'pickaxe': 'Pico',
'sword': 'Espada',
'wood': 'Madera',
'stone': 'Piedra',
'wall': 'Pared'
};
return names[item] || item;
}
// Recolectar recurso
function gatherResource(resource) {
if (resource.userData.health > 0) {
resource.userData.health--;
if (resource.userData.health <= 0) {
// Eliminar recurso
scene.remove(resource);
resources = resources.filter(r => r !== resource);
// Añadir recursos al inventario
if (resource.userData.type === 'tree') {
woodCount += 3;
resourcesCollected += 3;
} else if (resource.userData.type === 'rock') {
stoneCount += 2;
resourcesCollected += 2;
}
updateUI();
showMessage(`Recurso recolectado: ${resource.userData.type === 'tree' ? 'Madera' : 'Piedra'}`);
// Crear nuevo recurso después de un tiempo
setTimeout(() => {
createResource(resource.userData.type,
Math.random() * 100 - 50, 0, Math.random() * 100 - 50);
}, 30000);
}
}
}
// Atacar zombie
function attackZombie(zombie) {
if (currentItem !== 'sword') {
showMessage("¡Necesitas una espada para atacar!");
return;
}
zombie.userData.health -= 15;
if (zombie.userData.health <= 0) {
// Eliminar zombie
scene.remove(zombie);
zombies = zombies.filter(z => z !== zombie);
zombiesKilled++;
updateUI();
showMessage("¡Zombie eliminado!");
} else {
showMessage("¡Golpeaste al zombie!");
}
}
// Romper bloque
function breakBlock(block) {
if (block.userData.type === 'grass' && currentItem !== 'pickaxe') {
showMessage("¡Necesitas un pico para romper esto!");
return;
}
scene.remove(block);
world = world.filter(b => b !== block);
if (block.userData.type === 'grass') {
stoneCount++;
resourcesCollected++;
}
updateUI();
showMessage(`Bloque de ${block.userData.type} destruido`);
}
// Colocar bloque
function placeBlock() {
if (currentItem === 'wood' && woodCount < 1) {
showMessage("¡No tienes suficiente madera!");
return;
}
if (currentItem === 'stone' && stoneCount < 1) {
showMessage("¡No tienes suficiente piedra!");
return;
}
if (currentItem === 'wall' && (woodCount < 1 || stoneCount < 1)) {
showMessage("¡Necesitas madera y piedra para construir una pared!");
return;
}
raycaster.setFromCamera(new THREE.Vector2(0, 0), camera);
const intersects = raycaster.intersectObjects(world);
if (intersects.length > 0) {
const point = intersects[0].point;
const face = intersects[0].face;
// Calcular posición para el nuevo bloque
const normal = new THREE.Vector3(face.normal.x, face.normal.y, face.normal.z);
const newPosition = point.clone().add(normal.multiplyScalar(0.5));
newPosition.x = Math.round(newPosition.x);
newPosition.y = Math.round(newPosition.y);
newPosition.z = Math.round(newPosition.z);
// Verificar si ya hay un bloque en esa posición
const blockExists = world.some(block =>
block.position.x === newPosition.x &&
block.position.y === newPosition.y &&
block.position.z === newPosition.z
);
if (!blockExists) {
// Crear el bloque
let blockType;
switch(currentItem) {
case 'wood':
blockType = 'wood';
woodCount--;
break;
case 'stone':
blockType = 'stone';
stoneCount--;
break;
case 'wall':
blockType = 'wall';
woodCount--;
stoneCount--;
break;
default:
return;
}
createBlock(blockType, newPosition.x, newPosition.y, newPosition.z);
updateUI();
showMessage(`Bloque de ${blockType} colocado`);
}
}
}
// Mostrar mensaje
function showMessage(text) {
const messageBox = document.getElementById('messageBox');
messageBox.textContent = text;
messageBox.style.opacity = 1;
setTimeout(() => {
messageBox.style.opacity = 0;
}, 3000);
}
// Actualizar UI
function updateUI() {
document.getElementById('healthFill').style.width = `${playerHealth}%`;
document.getElementById('staminaFill').style.width = `${playerStamina}%`;
document.getElementById('woodCount').textContent = woodCount;
document.getElementById('stoneCount').textContent = stoneCount;
document.getElementById('zombieCount').textContent = zombies.length;
// Actualizar tiempo
const hours = Math.floor(gameTime / 60);
const minutes = gameTime % 60;
document.getElementById('timeDisplay').textContent =
`Día ${dayCount} | ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}
// Iniciar juego
function startGame() {
document.getElementById('startScreen').style.display = 'none';
gameActive = true;
// Iniciar sonido ambiente
const ambientSound = document.getElementById('ambientSound');
ambientSound.volume = 0.3;
ambientSound.play();
// Activar controles de puntero
controls = new THREE.PointerLockControls(camera, document.body);
document.body.requestPointerLock = document.body.requestPointerLock || document.body.mozRequestPointerLock || document.body.webkitRequestPointerLock;
document.body.requestPointerLock();
// Seleccionar primer objeto
selectItem('axe');
// Mensaje de bienvenida
showMessage("¡Sobrevive el mayor tiempo posible! Recolecta recursos y construye defensas.");
}
// Reiniciar juego
function restartGame() {
// Reiniciar variables
playerHealth = 100;
playerStamina = 100;
gameTime = 8 * 60;
dayCount = 1;
woodCount = 0;
stoneCount = 0;
zombiesKilled = 0;
resourcesCollected = 0;
// Eliminar zombies y recursos
zombies.forEach(zombie => scene.remove(zombie));
zombies = [];
resources.forEach(resource => scene.remove(resource));
resources = [];
// Añadir recursos iniciales
for (let i = 0; i < 20; i++) {
createResource('tree', Math.random() * 100 - 50, 0, Math.random() * 100 - 50);
}
for (let i = 0; i < 15; i++) {
createResource('rock', Math.random() * 100 - 50, 0, Math.random() * 100 - 50);
}
// Reposicionar jugador
player.position.set(0, 10, 0);
// Ocultar pantalla de fin de juego
document.getElementById('gameOver').style.display = 'none';
// Iniciar juego
gameActive = true;
updateUI();
showMessage("¡Nueva partida comenzada! Buena suerte.");
}
// Manejar muerte del jugador
function playerDie() {
gameActive = false;
document.getElementById('gameOver').style.display = 'flex';
document.getElementById('daysSurvived').textContent = dayCount;
document.getElementById('zombiesKilled').textContent = zombiesKilled;
document.getElementById('resourcesCollected').textContent = resourcesCollected;
// Detener sonido
document.getElementById('ambientSound').pause();
}
// Bucle de animación
function animate() {
requestAnimationFrame(animate);
if (!gameActive) return;
const delta = Math.min(clock.getDelta(), 0.1);
// Actualizar movimiento del jugador
playerVelocity.y -= 0.01; // Gravedad
playerDirection.z = Number(moveForward) - Number(moveBackward);
playerDirection.x = Number(moveRight) - Number(moveLeft);
playerDirection.normalize();
// Rotar dirección según la orientación de la cámara
if (controls.isLocked) {
const speed = 0.1;
player.translateX(playerDirection.x * speed);
player.translateZ(playerDirection.z * speed);
}
// Aplicar velocidad
player.position.y += playerVelocity.y;
// Detectar colisión con el suelo
if (player.position.y < 1) {
player.position.y = 1;
playerVelocity.y = 0;
canJump = true;
}
// Actualizar posición de la cámara
if (controls.isLocked) {
camera.position.copy(player.position);
camera.position.y += 1.6; // Altura de los ojos
}
// Actualizar tiempo del juego
gameTime += delta * 2; // 2 minutos por segundo real
if (gameTime >= 1440) { // 24 horas
gameTime = 0;
dayCount++;
// Aumentar dificultad cada día
zombieSpawnTimer = Math.max(10, 30 - dayCount * 2); // Zombis aparecen más rápido
showMessage(`¡Día ${dayCount}! Los zombies son más agresivos...`);
}
// Actualizar stamina
if (playerStamina < 100) {
playerStamina = Math.min(100, playerStamina + delta * 5);
}
// Generar zombies
lastZombieSpawn += delta;
if (lastZombieSpawn > zombieSpawnTimer && zombies.length < 10 + dayCount * 2) {
const angle = Math.random() * Math.PI * 2;
const distance = 30 + Math.random() * 20;
const x = player.position.x + Math.cos(angle) * distance;
const z = player.position.z + Math.sin(angle) * distance;
createZombie(x, z);
lastZombieSpawn = 0;
}
// Actualizar zombies
zombies.forEach(zombie => {
// Movimiento hacia el jugador
const direction = new THREE.Vector3();
direction.subVectors(player.position, zombie.position).normalize();
zombie.position.x += direction.x * zombie.userData.speed;
zombie.position.z += direction.z * zombie.userData.speed;
// Rotar hacia el jugador
zombie.lookAt(player.position.x, zombie.position.y, player.position.z);
// Detectar colisión con jugador
const distance = zombie.position.distanceTo(player.position);
if (distance < 1.5) {
const now = Date.now();
if (now - zombie.userData.lastAttack > 1000) {
playerHealth -= zombie.userData.attackDamage;
updateUI();
showMessage("¡Un zombie te ha atacado!");
zombie.userData.lastAttack = now;
if (playerHealth <= 0) {
playerDie();
}
}
}
});
// Actualizar iluminación según la hora
const hour = gameTime / 60;
let lightIntensity = 0.5;
if (hour > 20 || hour < 6) {
lightIntensity = 0.1;
} else if (hour > 18 || hour < 8) {
lightIntensity = 0.3;
}
scene.children.forEach(child => {
if (child instanceof THREE.DirectionalLight) {
child.intensity = lightIntensity;
}
});
// Actualizar UI
updateUI();
// Renderizar
renderer.render(scene, camera);
}
// Manejar cambio de tamaño de ventana
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Iniciar el juego cuando se cargue la página
window.addEventListener('load', init);
</script>
</body>
</html>
Características del juego
Este juego de supervivencia zombie estilo Minecraft incluye:
-
Movimiento en primera persona completo:
- Movimiento con teclado (WASD)
- Salto y carrera
- Vista controlada por ratón
-
Sistema de recolección de recursos:
- Árboles (para obtener madera)
- Rocas (para obtener piedra)
- Herramientas: hacha, pico y espada
-
Mecánicas de construcción:
- Colocación de bloques de madera, piedra y paredes
- Sistema de inventario para gestionar recursos
-
Sistema de supervivencia:
- Barra de salud y resistencia
- Zombies que te persiguen y atacan
- Ciclo día/noche que afecta la visibilidad
-
Interfaz de usuario intuitiva:
- Cruz de puntería central
- Barras de salud y resistencia
- Inventario con 6 ranuras
- Contador de recursos
- Reloj que muestra el día y hora
-
Mecánicas de juego:
- Dificultad que aumenta con cada día que pasa
- Mensajes informativos
- Estadísticas de juego
- Pantalla de inicio y de fin de juego
Instrucciones de juego
-
Haz clic en "EMPEZAR A SOBREVIVIR" para comenzar
-
Controles:
- WASD: Movimiento
- Espacio: Saltar
- Shift: Correr (gasta resistencia)
- Clic izquierdo: Atacar/Recolectar
- Clic derecho: Construir
- Rueda del ratón: Cambiar objeto
- Teclas 1-6: Seleccionar objeto rápidamente
-
Objetivo: Sobrevive el mayor tiempo posible recolectando recursos, construyendo defensas y luchando contra zombies.
¡Disfruta del juego! La dificultad aumenta con cada día que pasa, así que prepara tus defensas.