Flappy Bird with p5.js, a JavaScript library: A Fun and Interactive Coding Tutorial

Welcome to an exciting coding journey where we’ll delve into the world of game development using p5.js! In this tutorial, we’ll guide you step-by-step through the creation of the classic Flappy Bird game. Whether you’re a beginner eager to enhance your coding skills or an experienced developer looking for a playful project, this tutorial will provide valuable insights and hands-on experience.

Learn how to manipulate the p5.js library to craft engaging visuals, control game dynamics, and handle user input. By the end of this tutorial, you’ll have not only mastered the basics of game development but also gained a solid understanding of how to build interactive and entertaining projects.

Get ready to spread your wings and embark on a coding adventure that combines creativity, skill-building, and the joy of game development! Let’s dive into the fascinating world of Flappy Bird and unlock the secrets of p5.js together. Ready, set, code! 🚀 #FlappyBird #p5js #GameDevelopment #CodingTutorial

Code with p5.js, JS and HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://toolstolearning.com/wp-content/themes/astra-child/libs/p5.js"></script>
<title>Flappy Bird</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script>
// Global variables
let bird;
let pipes = [];
let gameOver = false;
let wingFlap = 0;
let score = 0;
let highScore = 0;
let scoreRecorded = false;
let jump = false;

// Preload images before the sketch starts
function preload() {
bird_open = loadImage('https://toolstolearning.com/wp-content/uploads/2024/01/bird_open.png');
bird_closed = loadImage('https://toolstolearning.com/wp-content/uploads/2024/01/bird_closed.png');
pipe = loadImage('https://toolstolearning.com/wp-content/uploads/2024/01/pipe.png');
}

// Setup function to initialize the canvas and other elements
function setup() {
createCanvas(windowWidth, windowHeight);
bird = new Bird();
pipes.push(new Pipe());

// Load high score from local storage
let savedHighScore = localStorage.getItem('highScore');
if (savedHighScore !== null) {
highScore = parseInt(savedHighScore);
}
}

// Draw function that is continuously executed to update and render the game
function draw() {
background(0);

if (!gameOver) {
bird.update();
bird.show();

// Iterate through pipes, update and show them
for (let i = pipes.length - 1; i >= 0; i--) {
pipes[i].update();
pipes[i].show();

// Check for collision with the bird
if (pipes[i].hits(bird)) {
gameOver = true;
}

// Remove pipes that are offscreen
if (pipes[i].offscreen()) {
pipes.splice(i, 1);
scoreRecorded = false;
}

// Check if the bird passed through the pipe
if (pipes[i].pass(bird) && !scoreRecorded) {
score++;
scoreRecorded = true;
}
}

// Add a new pipe every 100 frames
if (frameCount % 100 === 0) {
pipes.push(new Pipe());
}

// Modify wing flapping for a more visible wing movement
wingFlap = sin(frameCount * 0.1) * 10;

// Display the score
textSize(32);
fill(255);
text('Score: ' + score, 10, 30);
text('High Score: ' + highScore, 10, 70);

// Jump control
if (jump) {
bird.jump();
jump = false;
}
} else {
// Display game over screen
textSize(32);
fill(255);
text('Game Over', width / 4, height / 2);
text('Score: ' + score, width / 4, height / 2 + 40);
text('High Score: ' + highScore, width / 4, height / 2 + 80);
text('Press the space bar or click to restart', width / 4, height / 2 + 120);
}
}

// Function to handle key presses
function keyPressed() {
if (!gameOver && (key === ' ' || keyCode === UP_ARROW)) {
jump = true;
} else if (gameOver && (key === ' ' || keyCode === UP_ARROW)) {
restartGame();
}
}

// Function to handle mouse clicks
function mousePressed() {
if (!gameOver) {
jump = true;
} else {
restartGame();
}
}

// Adjust canvas size when the window is resized
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}

// Function to restart the game
function restartGame() {
bird = new Bird();
pipes = [];
gameOver = false;
scoreRecorded = false;

if (score > highScore) {
highScore = score;
localStorage.setItem('highScore', highScore);
}

score = 0;
pipes.push(new Pipe());
}

// Bird class
class Bird {
constructor() {
this.y = height / 2;
this.x = 64;
this.gravity = 0.6;
this.lift = -15;
this.velocity = 0;
this.imageOpen = bird_open;
this.imageClosed = bird_closed;
}

// Display the bird
show() {
let wingPosition = this.velocity > 0 ? -wingFlap : wingFlap;

if (this.velocity > 0) {
image(this.imageClosed, this.x, this.y, 32, 32);
} else {
image(this.imageOpen, this.x, this.y + wingPosition, 32, 32);
}
}

// Make the bird jump
jump() {
this.velocity += this.lift;
}

// Update bird's position
update() {
this.velocity += this.gravity;
this.y += this.velocity;

// Keep the bird within the canvas boundaries
if (this.y > height) {
this.y = height;
this.velocity = 0;
}

if (this.y < 0) {
this.y = 0;
this.velocity = 0;
}
}
}

// Pipe class
class Pipe {
constructor() {
this.top = random(height / 2);
this.bottom = random(height / 2);
this.x = width;
this.w = 20;
this.speed = 2;
this.highlight = false;
}

// Display the pipe
show() {
if (this.highlight) {
fill(255, 0, 0);
} else {
fill(0, 255, 0);
}

image(pipe, this.x, 0, this.w, this.top);
image(pipe, this.x, height - this.bottom, this.w, this.bottom);
}

// Update pipe's position
update() {
this.x -= this.speed;
}

// Check if the pipe is offscreen
offscreen() {
return this.x < -this.w;
}

// Check if the bird hits the pipe
hits(bird) {
if (bird.y < this.top || bird.y > height - this.bottom) {
if (bird.x > this.x && bird.x < this.x + this.w) {
this.highlight = true;
return true;
}
}
this.highlight = false;
return false;
}

// Check if the bird passed through the pipe
pass(bird) {
if (bird.x > this.x + this.w && !this.highlight) {
return true;
}
return false;
}
}
</script>
</body>
</html>

Conclusion

Congratulations on completing this exhilarating journey into the creation of your very own Flappy Bird game using p5.js! We hope you’ve enjoyed the process of coding, learning, and exploring the possibilities of game development.

Now, it’s time to spread your wings and experience the fruit of your labor. Head over to the Flappy Wings Adventure and put your skills to the test! Navigate the friendly bird through the pipes, challenge your reflexes, and aim for a high score.

This hands-on project serves not only as an entertaining game but also as a valuable learning experience in the world of web-based game development. Keep refining your coding skills, exploring new projects, and most importantly, have fun with your creations!

Thank you for joining us on this coding adventure. If you found this tutorial helpful or have any feedback, feel free to share it. Stay tuned for more exciting coding projects, and happy coding! 🎮✨ #FlappyWingsAdventure #p5js #GameOn #CodingFun