<!
DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Juego Básico</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
background: black;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const player = {
x: canvas.width / 2 - 25,
y: canvas.height - 60,
width: 50,
height: 50,
color: 'white',
speed: 10
};
const obstacle = {
x: Math.random() * (canvas.width - 50),
y: 0,
width: 50,
height: 50,
color: 'red',
speed: 5
};
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawObstacle() {
ctx.fillStyle = obstacle.color;
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}
function movePlayer(event) {
if (event.key === 'ArrowLeft' && player.x > 0) {
player.x -= player.speed;
}
if (event.key === 'ArrowRight' && player.x < canvas.width -
player.width) {
player.x += player.speed;
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawObstacle();
obstacle.y += obstacle.speed;
if (obstacle.y > canvas.height) {
obstacle.y = 0;
obstacle.x = Math.random() * (canvas.width - 50);
}
if (player.x < obstacle.x + obstacle.width &&
player.x + player.width > obstacle.x &&
player.y < obstacle.y + obstacle.height &&
player.y + player.height > obstacle.y) {
alert('¡Game Over!');
document.location.reload();
}
requestAnimationFrame(update);
}
document.addEventListener('keydown', movePlayer);
update();
</script>
</body>
</html>