Untitled
unknown
plain_text
5 months ago
3.5 kB
5
Indexable
// Setup the game canvas const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Set canvas size canvas.width = 320; canvas.height = 480; // Game variables let bird; let pipes = []; let gravity = 0.6; let lift = -15; let isGameOver = false; let score = 0; // Bird object class Bird { constructor() { this.x = 50; this.y = canvas.height / 2; this.width = 20; this.height = 20; this.velocity = 0; } // Update bird's position update() { this.velocity += gravity; this.y += this.velocity; // Prevent the bird from flying off the canvas if (this.y + this.height > canvas.height) { this.y = canvas.height - this.height; if (!isGameOver) gameOver(); } else if (this.y < 0) { this.y = 0; } } // Jump the bird jump() { this.velocity = lift; } // Draw the bird on the canvas draw() { ctx.fillStyle = "#FF0"; ctx.fillRect(this.x, this.y, this.width, this.height); } } // Pipe object class Pipe { constructor() { this.width = 40; this.gap = 150; this.x = canvas.width; this.topHeight = Math.floor(Math.random() * (canvas.height - this.gap)); this.bottomHeight = canvas.height - (this.topHeight + this.gap); } // Update pipe's position and check for collisions update() { this.x -= 2; // Remove pipes that have passed off-screen if (this.x + this.width < 0) { pipes.shift(); score++; } // Check for collision with the bird if (this.x < bird.x + bird.width && this.x + this.width > bird.x) { if (bird.y < this.topHeight || bird.y + bird.height > this.topHeight + this.gap) { if (!isGameOver) gameOver(); } } } // Draw the pipes on the canvas draw() { ctx.fillStyle = "#00F"; ctx.fillRect(this.x, 0, this.width, this.topHeight); ctx.fillRect(this.x, this.topHeight + this.gap, this.width, this.bottomHeight); } } // Start the game function startGame() { bird = new Bird(); pipes = []; score = 0; isGameOver = false; mainLoop(); } // Game Over function function gameOver() { isGameOver = true; alert("Game Over! Final score: " + score); startGame(); // Restart the game } // Main game loop function mainLoop() { if (isGameOver) return; ctx.clearRect(0, 0, canvas.width, canvas.height); // Update and draw bird bird.update(); bird.draw(); // Generate new pipes periodically if (pipes.length === 0 || pipes[pipes.length - 1].x < canvas.width - 150) { pipes.push(new Pipe()); } // Update and draw pipes for (let i = 0; i < pipes.length; i++) { pipes[i].update(); pipes[i].draw(); } // Draw score ctx.fillStyle = "#000"; ctx.font = "20px Arial"; ctx.fillText("Score: " + score, 10, 30); // Request the next frame requestAnimationFrame(mainLoop); } // Handle keypresses (space bar to jump) document.addEventListener('keydown', (event) => { if (event.key === ' ' || event.key === 'ArrowUp') { if (!isGameOver) bird.jump(); } }); // Start the game when the page is loaded startGame();
Editor is loading...
Leave a Comment