Untitled
unknown
plain_text
9 months ago
2.7 kB
6
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dodge the Obstacles</title>
<style>
body { text-align: center; font-family: Arial, sans-serif; }
canvas { background: white; display: block; margin: 20px auto; border: 2px solid black; }
</style>
</head>
<body>
<h1>Dodge the Obstacles</h1>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const player = { x: 375, y: 550, width: 50, height: 50, speed: 5 };
let obstacles = [];
let score = 0;
let gameOver = false;
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft" && player.x > 0) player.x -= player.speed;
if (e.key === "ArrowRight" && player.x < canvas.width - player.width) player.x += player.speed;
});
function createObstacle() {
const x = Math.random() * (canvas.width - 50);
obstacles.push({ x: x, y: 0, width: 50, height: 50, speed: 5 });
}
function updateGame() {
if (Math.random() < 0.02) createObstacle();
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].y += obstacles[i].speed;
if (
player.x < obstacles[i].x + obstacles[i].width &&
player.x + player.width > obstacles[i].x &&
player.y < obstacles[i].y + obstacles[i].height &&
player.y + player.height > obstacles[i].y
) {
gameOver = true;
}
}
obstacles = obstacles.filter(obstacle => obstacle.y < canvas.height);
if (!gameOver) score++;
}
function drawGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.fillStyle = "red";
obstacles.forEach(obstacle => ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height));
ctx.fillStyle = "black";
ctx.fillText("Score: " + score, 10, 20);
}
function gameLoop() {
updateGame();
drawGame();
if (!gameOver) requestAnimationFrame(gameLoop);
else alert("Game Over! Score: " + score);
}
gameLoop();
</script>
</body>
</html>Editor is loading...
Leave a Comment