Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define game variables
- let canvas, ctx;
- let bird, gravity, pipes;
- let gameOver, score, highScore;
- // Initialize game
- function init() {
- canvas = document.createElement('canvas');
- canvas.width = 800;
- canvas.height = 600;
- document.body.appendChild(canvas);
- ctx = canvas.getContext('2d');
- bird = { x: canvas.width / 4, y: canvas.height / 2, size: 20, speed: 0 };
- gravity = 0.5;
- pipes = [];
- gameOver = false;
- score = 0;
- // Retrieve high score from local storage
- highScore = localStorage.getItem('highScore') || 0;
- // Event listener for jump
- document.addEventListener('keydown', function(event) {
- if (event.code === 'Space' && !gameOver) {
- bird.speed = -8; // Adjust jump strength if needed
- }
- });
- // Start game loop
- setInterval(update, 1000 / 60);
- }
- // Update game state
- function update() {
- // Clear canvas
- ctx.fillStyle = 'lightblue'; // Background color
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- // Move bird
- bird.speed += gravity;
- bird.y += bird.speed;
- // Draw bird
- ctx.fillStyle = 'yellow';
- ctx.beginPath();
- ctx.arc(bird.x, bird.y, bird.size, 0, Math.PI * 2);
- ctx.fill();
- // Generate pipes
- if (pipes.length === 0 || pipes[pipes.length - 1].x < canvas.width - 300) {
- pipes.push({ x: canvas.width, gapY: Math.random() * (canvas.height - 300) + 150 });
- }
- // Move pipes
- pipes.forEach(function(pipe) {
- pipe.x -= 2;
- // Check collision with pipes
- if (bird.x + (bird.size/2) >= pipe.x && bird.x - (bird.size/2) <= pipe.x + 50) {
- if (bird.y - (bird.size/2) <= pipe.gapY || bird.y + (bird.size/2) >= pipe.gapY + 200) {
- gameOver = true; // Collision with pipes
- console.log("BIRD Y "+bird.y+"\nBIRD SIZE "+bird.size+"\nPIPE GAP "+pipe.gapY)
- }
- }
- // Pass pipes
- if (pipe.x + 50 < bird.x && !pipe.passed && gameOver = false) {
- pipe.passed = true;
- score++;
- }
- });
- // Remove off-screen pipes
- pipes = pipes.filter(pipe => pipe.x > -50);
- // Draw pipes
- ctx.fillStyle = 'green';
- pipes.forEach(function(pipe) {
- ctx.fillRect(pipe.x, 0, 50, pipe.gapY);
- ctx.fillRect(pipe.x, pipe.gapY + 200, 50, canvas.height - pipe.gapY - 200);
- });
- // Draw score
- ctx.fillStyle = 'white';
- ctx.font = '24px Arial';
- ctx.fillText('Score: ' + score, 10, 30);
- // Update high score
- if (score > highScore) {
- highScore = score;
- localStorage.setItem('highScore', highScore);
- }
- // Draw high score
- ctx.fillText('High Score: ' + highScore, 10, 60);
- // Check game over
- if (bird.y > canvas.height || gameOver) {
- gameOver = true;
- ctx.fillStyle = 'black';
- ctx.font = '40px Arial';
- ctx.fillText('Game Over', canvas.width / 2 - 100, canvas.height / 2);
- }
- }
- // Start the game when the page loads
- window.onload = init;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement