As an AI language model, I can provide a basic algorithm for a simple game of Flappy Bird as follows:
- Initialize the game canvas and create the bird object.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let bird = { x: 50, y: canvas.height/2, size: 25, velocity: 0 };
- Set up game variables such as gravity, jump velocity, and score.
const gravity = 0.5;
const jumpVelocity = -10;
let score = 0;
- Create an obstacle array with random heights and positions.
let obstacles = [];
function createObstacle() {
let height = Math.floor(Math.random()*(canvas.height-200))+100;
let gap = 150;
let topObstacle = { x: canvas.width, y: 0, width: 50, height: height };
let bottomObstacle = { x: canvas.width, y: height + gap, width: 50, height: canvas.height - height - gap };
obstacles.push(topObstacle, bottomObstacle);
}
- Move the obstacles from right to left across the screen and check for collisions with the bird.
function moveObstacles() {
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].x -= 2;
if (obstacles[i].x + obstacles[i].width < 0) {
obstacles.splice(i, 1);
score++;
}
if (bird.x < obstacles[i].x + obstacles[i].width && bird.x + bird.size > obstacles[i].x &&
bird.y < obstacles[i].y + obstacles[i].height && bird.y + bird.size > obstacles[i].y) {
endGame();
}
}
}
- Update the bird's position based on the user's input (usually a space bar press) and apply gravity.
document.addEventListener('keydown', (event) => {
if (event.code === 'Space') {
bird.velocity = jumpVelocity;
}
});
function moveBird() {
bird.velocity += gravity;
bird.y += bird.velocity;
}
- Check if the bird has flown off the screen or hit the ground, if so, end the game.
function checkBirdPosition() {
if (bird.y + bird.size > canvas.height || bird.y < 0) {
endGame();
}
}
- Repeat steps 4-6 until the game ends.
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveObstacles();
moveBird();
checkBirdPosition();
drawObstacles();
drawBird();
drawScore();
if (!isGameEnded) {
requestAnimationFrame(gameLoop);
}
}
requestAnimationFrame(gameLoop);
- Display the user's score and allow them to play again.
function endGame() {
isGameEnded = true;
alert(`Game over!\nYour score: ${score}`);
resetGame();
}
function resetGame() {
obstacles = [];
bird = { x: 50, y: canvas.height/2, size: 25, velocity: 0 };
score = 0;
isGameEnded = false;
createObstacle();
}
function drawScore() {
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, 10, 30);
}
Note: This is a basic implementation, you can add additional features such as game sounds, better graphics, and difficulty levels to make the game more interesting.