Skip to content

Instantly share code, notes, and snippets.

@luizbills
Created April 8, 2025 11:19
Show Gist options
  • Save luizbills/ff7a56143d921f76df764bf5bd530c63 to your computer and use it in GitHub Desktop.
Save luizbills/ff7a56143d921f76df764bf5bd530c63 to your computer and use it in GitHub Desktop.
"Flappy Bird" in Litecanvas
litecanvas({
width: 240,
height: 360,
// autoscale: false
});
let bird, pipes, score, gameOver, gravity, frames;
function reset() {
bird = { x: 50, y: CENTERY, vy: 0, size: 12 };
pipes = [];
score = 0;
gameOver = false;
gravity = 0.3;
frames = 0;
}
function init() {
loadFont('monogram', '/fonts/monogram.ttf')
bestScore = 0
reset()
}
// Bird jump on click/touch
function tapped() {
if (LOADING) return;
if (gameOver && ELAPSED - gameOver > 1) {
reset();
} else {
bird.vy = -6;
}
}
function update(dt) {
if (LOADING) return;
if (gameOver) return;
// Bird movement
bird.vy += gravity;
bird.y += bird.vy;
// Generate random pipes
if (frames % 100 === 0) {
const gap = 150;
const topHeight = rand(50, HEIGHT - gap - 50);
pipes.push({ x: WIDTH, top: topHeight, bottom: topHeight + gap });
}
// Move and remove pipes
pipes.forEach(pipe => {
pipe.x -= 1.5;
if (pipe.x < -50) pipes.shift();
// Collision with each pipe
if (
bird.x + bird.size > pipe.x && bird.x - bird.size < pipe.x + 50 &&
(bird.y - bird.size < pipe.top || bird.y + bird.size > pipe.bottom)
) {
gameOver = ELAPSED;
}
});
// Collision with floor/ceiling
if (bird.y < 0 || bird.y > HEIGHT) {
gameOver = ELAPSED;
}
// Score
pipes.forEach(pipe => {
if (pipe.x + 50 === bird.x) {
score++;
sfx()
// check new best score
if (score > bestScore) bestScore = score
}
});
}
function draw() {
cls(6); // Background
if (LOADING) return;
// pipes
pipes.forEach(pipe => {
rectfill(pipe.x, 0, 50, pipe.top, 9); // Top pipe
rectfill(pipe.x, pipe.bottom, 50, HEIGHT, 9); // Bottom pipe
});
// Bird (yellow circle)
circfill(bird.x, bird.y, bird.size, 5);
// Current score
textfont('monogram')
textsize(32)
textalign("center", "middle");
text(CENTERX, 20, score);
// Current best score
textsize(16)
text(CENTERX, 40, 'BEST: ' + bestScore);
// Game Over message
if (gameOver) {
textsize(32)
text(CENTERX, CENTERY, ELAPSED - gameOver > 1 ? "TAP TO RESTART" : "GAME OVER");
}
// Increment frames
frames++;
}
@luizbills
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment