<!
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fireball Dodge</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// JavaScript code for the game goes here
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Define player properties
let player = {
x: 50,
y: canvas.height - 50,
width: 30,
height: 30,
jumping: false,
jumpHeight: 100,
jumpDuration: 500, // milliseconds
jumpStart: 0,
velocityY: 0,
gravity: 0.5
};
// Fireballs array
let fireballs = [];
// Game variables
let score = 0;
let gameSpeed = 2;
let gameOver = false;
// Event listener for tap/click to jump
canvas.addEventListener('click', () => {
if (!player.jumping) {
player.jumping = true;
player.jumpStart = Date.now();
}
});
// Game loop
function gameLoop() {
if (!gameOver) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update player position
if (player.jumping) {
let jumpTime = Date.now() - player.jumpStart;
if (jumpTime < player.jumpDuration) {
player.velocityY = -10; // Adjust jump height
} else {
player.jumping = false;
player.velocityY = 0;
}
} else {
player.velocityY += player.gravity;
}
player.y += player.velocityY;
// Draw player
ctx.fillStyle = 'blue';
ctx.fillRect(player.x, player.y, player.width, player.height);
// Generate fireballs
if (Math.random() < 0.02) {
fireballs.push({
x: Math.random() * canvas.width,
y: 0,
radius: 10,
speed: Math.random() * 3 + 1 // random speed between 1 and
4
});
}
// Update and draw fireballs
fireballs.forEach((fireball, index) => {
fireball.y += fireball.speed;
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(fireball.x, fireball.y, fireball.radius, 0, Math.PI *
2);
ctx.fill();
// Check collision with player
if (collision(player, fireball)) {
gameOver = true;
}
// Remove fireball if off screen
if (fireball.y > canvas.height) {
fireballs.splice(index, 1);
score++;
}
});
// Display score
ctx.fillStyle = 'black';
ctx.font = '24px Arial';
ctx.fillText('Score: ' + score, 10, 30);
// Request next frame
requestAnimationFrame(gameLoop);
} else {
// Game over
ctx.fillStyle = 'black';
ctx.font = '36px Arial';
ctx.fillText('Game Over!', canvas.width / 2 - 100, canvas.height /
2 - 50);
ctx.fillText('Score: ' + score, canvas.width / 2 - 80,
canvas.height / 2);
}
}
// Function to check collision between two objects
function collision(player, fireball) {
let dx = player.x + player.width / 2 - fireball.x;
let dy = player.y + player.height / 2 - fireball.y;
let distance = Math.sqrt(dx * dx + dy * dy);
return distance < player.width / 2 + fireball.radius;
}
// Start the game loop
gameLoop();
</script>
</body>
</html>