Flappy Bird Game

Build the Flappy Bird Game using HTML and JavaScript Code

Hello Coder! Welcome to the Codewithrandom blog. In this Article, we Create Flappy Bird Game using HTML and JavaScript Code. What is flappy bird source code? Flappy Bird Game is an endless game that has a bird that is controlled by the user using the spacebar. The player must prevent the bird from hitting obstacles like pipes. Every time the bird moves through the pipes, the score goes up by one. When the bird hits the pipes or plummets to the ground due to gravity, the game is over. The procedures that must be performed to create this game are described in the sections below. We can learn a lot about CSS and JavaScript from the game Flappy Bird. In order to give our flappy bird game a dynamic aspect, we will examine photographs and their characteristics. Using fundamental JavaScript concepts, we will also include the control movements of the birds in our game. This tutorial will demonstrate how to make a responsive Flappy Bird game utilizing fundamental JavaScript, HTML, and CSS ideas. I hope you enjoy our blog so let’s start with a basic HTML structure for the Flappy Bird Game Code.

Читайте также:  Основы PHP и MySQL

Flappy Bird Html Code:-

        

flappyBird Game

Give our flappy bird game a framework. Using the h3 tag selector, we will give our flappy bird game’s heading inside the body section. Now using the div tag with the class «random» The Flappy Bird image’s container will be made. The canvas Method is now being used, with 512 and 288 as the width and height, respectively. There is all the HTML code & Css code for the Flappy Bird Game Code. Now you can see output without Css and JavaScript. This is only the HTML coding output for Flappy Bird Game Code. Then we write Css And JavaScript for Flappy Bird Game Code.

Flappy Bird CSS Code:-

Now applying the class selector at random 100 vh will be chosen as the height. We’ll use the width property to change the display type to «set to flex» and the width to 100%. We will put the element in the centre by using the Align item property. We’ll inside the letter from the H3 Times. Put the text in centre alignment. utilising the text-align attribute. The text’s font size is also set to 2 REM.

Flappy Bird JavaScript Code:-

"use strict"; var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); // load images var bird = new Image(); var bg = new Image(); var fg = new Image(); var pipeNorth = new Image(); var pipeSouth = new Image(); bird.src = "images/bird.png"; bg.src = "images/bg.png"; fg.src = "images/fg.png"; pipeNorth.src = "images/pipeNorth.png"; pipeSouth.src = "images/pipeSouth.png"; // some variables var gap = 85; var constant; var bX = 10; var bY = 150; var gravity = 1.5; var score = 0; // audio files var fly = new Audio(); var scor = new Audio(); fly.src = "sounds/fly.mp3"; scor.src = "sounds/score.mp3"; // on key down document.addEventListener("keydown", moveUp); function moveUp() < bY -= 25; fly.play(); >// pipe coordinates var pipe = []; pipe[0] = < x: cvs.width, y: 0, >; // draw images function draw() < ctx.drawImage(bg, 0, 0); for (var i = 0; i < pipe.length; i++) < constant = pipeNorth.height + gap; ctx.drawImage(pipeNorth, pipe[i].x, pipe[i].y); ctx.drawImage(pipeSouth, pipe[i].x, pipe[i].y + constant); pipe[i].x--; if (pipe[i].x == 125) < pipe.push(< x: cvs.width, y: Math.floor(Math.random() * pipeNorth.height) - pipeNorth.height, >); > // detect collision if ( (bX + bird.width >= pipe[i].x && bX = pipe[i].y + constant)) || bY + bird.height >= cvs.height - fg.height ) < location.reload(); // reload the page >if (pipe[i].x == 5) < score++; scor.play(); >> ctx.drawImage(fg, 0, cvs.height - fg.height); ctx.drawImage(bird, bX, bY); bY += gravity; ctx.fillStyle = "#000"; ctx.font = "20px Verdana"; ctx.fillText("Score : " + score, 10, cvs.height - 20); requestAnimationFrame(draw); > draw(); 

Use strict is the first remark in the code. This ensures that the code will execute without any issues. The object CVS, a canvas element on the page, is created in the following line. The context of this canvas is then obtained, and it is saved in the ctx variable. The next several lines also load the audio files fly and score while loading images into the variables bird, bg, fg, pipeNorth, pipeSouth, and score. Two images are loaded by the code—one for the bird and one for the background. Next, a «gap» variable is created and given a value of 85 pixels.
The x and y coordinates of the bird’s beginning place on the screen are then determined using variables called bX and bY.
When the bird is released by pressing a key on the keyboard, gravity and score will be used to determine whether it flies north or south of the pipe. It then loops through each pipe and draws it on top of the background image, using a constant height for each pipe.
The code also checks to see if there is a collision between any pipes and the bird. If so, it reloads the page with an animation that plays when you click on one of the pipes. The code is a very simple example of the use of requestAnimationFrame function. Now we have completed our Flappy Bird JavaScript Code. Here is our updated output with Html and JavaScript. Hope you like the Flappy Bird Game Source Code. you can see the output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you! In this post, we learn how to create a Flappy Bird Game Using Html and JavaScript Code. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning. Written by — CodeWithRandom/Anki

Читайте также:  Java map string and int

Источник

Игра на чистом JavaScript за 20 минут

Игра на чистом JavaScript за 20 минут

На JS можно создавать сложные и простые игры любых жанров. Мы расскажем как создать 2D игру на JavaScript и HTML5 всего за 20 минут.

Для создания веб игр на языке JavaScript используется технология Canvas , которая позволяет выполнять JavaScript код в HTML5 документе. Вы можете более детально ознакомиться с этой технологией посмотрев видео ниже:

На html странице прописывается лишь тег канвас, а также подключение JS файла, в котором будет происходить обработка всей функциональности. К примеру, HTML файл может выглядеть следующим образом:

В JS файле необходимо найти нужный канвас по id и указать способ работы с ним.

var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d");

Добавление изображений и аудио

Далее необходимо загрузить все изображения, а также аудио файлы, которые будут использоваться в игре. Для этого используйте класс Image и Audio соответсвенно. Ниже вы можете скачать все необходимые картинки, а также аудиофайлы к игре.

Код добавления изображений и аудио в игру:

var bird = new Image(); var bg = new Image(); // Создание объекта var fg = new Image(); // Создание объекта var pipeUp = new Image(); // Создание объекта var pipeBottom = new Image(); // Создание объекта bird.src = "img/bird.png"; // Указание нужного изображения bg.src = "img/bg.png"; // Аналогично fg.src = "img/fg.png"; // Аналогично pipeUp.src = "img/pipeUp.png"; // Аналогично pipeBottom.src = "img/pipeBottom.png"; // Аналогично // Звуковые файлы var fly = new Audio(); // Создание аудио объекта var score_audio = new Audio(); // Создание аудио объекта fly.src = "audio/fly.mp3"; // Указание нужной записи score_audio.src = "audio/score.mp3"; // Аналогично

Рисование объектов

Чтобы нарисовать объекты, а также добавить функционал к игре необходимо прописать функцию, которая будет постоянно вызываться. Такую функцию вы можете назвать как вам будет угодно. Главное, вам нужно вызвать эту функцию из вне её хотя бы один раз, а внутри неё прописать метод requestAnimationFrame , который будет вызывать функцию постоянно.

function draw() < // Какой-либо код requestAnimationFrame(draw); // Вызов функции постоянно >draw(); // Вызов функции из вне

Весь код игры стоит помещать в этот метод, ведь в нем он будет постоянно обрабатываться и игра будет выглядеть живой и анимированной.

Чтобы отследить нажатие игрока на какую-либо клавишу, необходимо использовать отслеживание событий — addEventListener . К примеру, чтобы отследить нажатие на любую клавишу на клавиатуре надо прописать следующий код:

// При нажатии на какую-либо кнопку document.addEventListener("keydown", someMethod); // Вызывается метод someMethod function someMethod() < // Изменяем что-то в коде >

Видео урок

Это были лишь небольшие азы перед созданием самой игры. Предлагаем вам ознакомиться с небольшим видео уроком, в ходе которого вы создадите небольшую 2D игру на чистом JavaScript’е.

Весь JS код игры

Ниже вы можете посмотреть на полностью весь код JavaScript файла, который был создан в ходе видео урока выше:

var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); var bird = new Image(); var bg = new Image(); var fg = new Image(); var pipeUp = new Image(); var pipeBottom = new Image(); bird.src = "img/bird.png"; bg.src = "img/bg.png"; fg.src = "img/fg.png"; pipeUp.src = "img/pipeUp.png"; pipeBottom.src = "img/pipeBottom.png"; // Звуковые файлы var fly = new Audio(); var score_audio = new Audio(); fly.src = "audio/fly.mp3"; score_audio.src = "audio/score.mp3"; var gap = 90; // При нажатии на какую-либо кнопку document.addEventListener("keydown", moveUp); function moveUp() < yPos -= 25; fly.play(); >// Создание блоков var pipe = []; pipe[0] = < x : cvs.width, y : 0 >var score = 0; // Позиция птички var xPos = 10; var yPos = 150; var grav = 1.5; function draw() < ctx.drawImage(bg, 0, 0); for(var i = 0; i < pipe.length; i++) < ctx.drawImage(pipeUp, pipe[i].x, pipe[i].y); ctx.drawImage(pipeBottom, pipe[i].x, pipe[i].y + pipeUp.height + gap); pipe[i].x--; if(pipe[i].x == 125) < pipe.push(< x : cvs.width, y : Math.floor(Math.random() * pipeUp.height) - pipeUp.height >); > // Отслеживание прикосновений if(xPos + bird.width >= pipe[i].x && xPos = pipe[i].y + pipeUp.height + gap) || yPos + bird.height >= cvs.height - fg.height) < location.reload(); // Перезагрузка страницы >if(pipe[i].x == 5) < score++; score_audio.play(); >> ctx.drawImage(fg, 0, cvs.height - fg.height); ctx.drawImage(bird, xPos, yPos); yPos += grav; ctx.fillStyle = "#000"; ctx.font = "24px Verdana"; ctx.fillText("Счет: " + score, 10, cvs.height - 20); requestAnimationFrame(draw); > pipeBottom.onload = draw; 

Больше интересных новостей

Принцип работы беспилотных машин

Принцип работы беспилотных машин

Как изменит мир искусственный интеллект к 2030 году?

Как изменит мир искусственный интеллект к 2030 году?

Второй язык программирования изучить легче, чем первый. Так ли это?

Второй язык программирования изучить легче, чем первый. Так ли это?

Компания Adobe внедрила в Photoshop функционал на основе ИИ

Компания Adobe внедрила в Photoshop функционал на основе ИИ

RInat 05 мая 2023 в 17:32

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Create Original Flappy Bird With JavaScript

CodeExplainedRepo/Original-Flappy-bird-JavaScript

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Create Original Flappy Bird With JavaScript

Flappy Bird was a side-scrolling mobile game featuring 2D retro style graphics. The objective was to direct a flying bird, named «Faby», who moves continuously to the right, between sets of Mario-like pipes. If the player touches the pipes, they lose. Faby briefly flaps upward each time that the player taps the screen; if the screen is not tapped, Faby falls because of gravity; each pair of pipes that he navigates between earns the player a single point, with medals awarded for the score at the end of the game. No medal is awarded to scores less than ten. A bronze medal is given to scores between ten and twenty. In order to receive the silver medal, the player must reach 20 points. The gold medal is given to those who score higher than thirty points. Players who achieve a score of forty or higher receive a platinum medal. Android devices enabled the access of world leaderboards, through Google Play.

There is no variation or evolution in gameplay throughout the game, as the pipes always have the same gap between them and there is no end to the running track, having only the flap and ding sounds and the rising score as rewards.

And today you’re going to create the Flappy Bird game using JavaScript and HTML (or HTML5 canvas).

We’re not using any framework to build the game, Just Vanilla JavaScript.

This is a beginner’s guide on how to create the flappy bird game using JavaScript and HTML.

To follow the tutorial step by step, please download the starter template, and then follow this link:

Источник

Оцените статью