Haz clic aquí para empezar
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let player = { x: 50, y: 150, w: 30, h: 30, dy: 0, jumping: false };
let obstacles = [{ x: 800, y: 160, w: 40, h: 40 }];
let gameSpeed = 5;
let gameStarted = false;
document.getElementById('startScreen').addEventListener('click', () => {
gameStarted = true;
document.getElementById('startScreen').style.display = 'none';
canvas.style.display = 'block';
draw();
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!gameStarted) return;
// Suelo
ctx.fillStyle = '#444';
ctx.fillRect(0, 190, canvas.width, 10);
// Jugador
ctx.fillStyle = '#f00';
ctx.fillRect(player.x, player.y, player.w, player.h);
// Obstáculos
ctx.fillStyle = '#0f0';
obstacles.forEach(o => {
ctx.fillRect(o.x, o.y, o.w, o.h);
o.x -= gameSpeed;
if (o.x + o.w < 0) o.x = canvas.width + Math.random() * 300;
if (player.x < o.x + o.w && player.x + player.w > o.x &&
player.y < o.y + o.h && player.y + player.h > o.y) {
alert('¡Game Over!');
obstacles = [{ x: 800, y: 160, w: 40, h: 40 }];
}
});
// Gravedad
if (player.y < 160 || player.jumping) {
player.dy += 0.8;
player.y += player.dy;
if (player.y >= 160) {
player.y = 160;
player.jumping = false;
player.dy = 0;
}
}
requestAnimationFrame(draw);
}
window.addEventListener('keydown', () => { if (!player.jumping) { player.dy = -15; player.jumping = true; } });
canvas.addEventListener('mousedown', () => { if (!player.jumping) { player.dy = -15; player.jumping = true; } });