hello-world icon indicating copy to clipboard operation
hello-world copied to clipboard

My account

Open Okunola7 opened this issue 6 months ago • 0 comments

HTML:

<!DOCTYPE html>
<html>
<head>
	<title>Bird Flight Game</title>
	<style>
		/* Add some basic styling */
		body {
			background-color: #f0f0f0;
		}
		.bird {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 50px;
			height: 50px;
			background-color: #ff0000;
			border-radius: 50%;
		}
		.obstacle {
			position: absolute;
			top: 0;
			left: 0;
			width: 50px;
			height: 200px;
			background-color: #000;
		}
		.score {
			position: absolute;
			top: 10px;
			left: 10px;
			font-size: 24px;
			font-weight: bold;
		}
	</style>
</head>
<body>
	<div class="bird"></div>
	<div class="obstacle"></div>
	<div class="score">Score: 0</div>
	<script src="game.js"></script>
</body>
</html>

JavaScript (game.js):

// Get elements
const bird = document.querySelector('.bird');
const obstacle = document.querySelector('.obstacle');
const scoreDisplay = document.querySelector('.score');

// Set initial values
let birdX = 250;
let birdY = 250;
let velocity = 0;
let score = 0;
let obstacleX = 500;
let obstacleY = Math.random() * 300;

// Handle tap event
document.addEventListener('touchstart', () => {
	velocity = -10;
});

// Update game state
function update() {
	birdY += velocity;
	velocity += 0.5; // Gravity

	// Move bird element
	bird.style.top = `${birdY}px`;
	bird.style.left = `${birdX}px`;

	// Move obstacle
	obstacleX -= 2;
	obstacle.style.left = `${obstacleX}px`;
	obstacle.style.top = `${obstacleY}px`;

	// Check collision
	if (checkCollision()) {
		endGame();
	}

	// Check score
	if (obstacleX < birdX && obstacleX + 50 > birdX) {
		score++;
		scoreDisplay.textContent = `Score: ${score}`;
		obstacleX = 500;
		obstacleY = Math.random() * 300;
	}

	// Request next frame
	requestAnimationFrame(update);
}

// Check collision between bird and obstacle
function checkCollision() {
	const birdRect = bird.getBoundingClientRect();
	const obstacleRect = obstacle.getBoundingClientRect();
	return (
		birdRect.top < obstacleRect.bottom &&
		birdRect.bottom > obstacleRect.top &&
		birdRect.left < obstacleRect.right &&
		birdRect.right > obstacleRect.left
	);
}

// End game
function endGame() {
	alert(`Game Over! Score: ${score}`);
	score = 0;
	scoreDisplay.textContent = `Score: ${score}`;
	birdY = 250;
	obstacleX = 500;
	obstacleY = Math.random() * 300;
}

// Start game loop
update();

Okunola7 avatar Jul 30 '24 18:07 Okunola7