Pure JavaScript implementation Flappy Bird small game instance code _javascript skill

Source: Internet
Author: User
Tags rand setinterval

Objective:

"Flappy Bird" is a work developed by Dong Nguyen, an independent game developer from Vietnam, which came online on May 24, 2013 and suddenly burst red in February 2014. In February 2014, "Flappy Bird" was removed from Apple and Google App store by the developer himself. August 2014 officially returned to the app STORE, officially joined Flappy fans have been waiting for a long time multiplayer mode. In the game, the player must control a bird and cross the barrier made up of various lengths of water pipes.
Body:

The next step is to realize it

Step 1: Page layout, here is not much to say, the page content is as follows:

Step 2: How to let the birds fall and let the birds jump up

Bird descent:

Give the bird a speed, the initial value is 0, through the timer let speed every 30ms plus 1, when speed exceeds the maximum Speedmax, that is, the speed>8, let the speed keep the maximum value.

Get bird div
var bird = document.getElementById ("Flybird");
Bird Descent
function down () {
speed + + 1;
bird.id = ' Flybird_down ';
bird.style.top = bird.offsettop + speed + ' px ';
Floortext (); Landing Detection
}

Bird ascent:

Rise, which is the process of decreasing the top value of a bird. Let the speed be reduced. At the same time, when the bird rises, close the bird down the timer, as well as the last Take-off when the rise of the timer, and restart the rise timer. Here, there is a isgameover, for the game switch, the default is ture, that is, when the value is false, the game has not started, the birds can not jump.

Bird Rise
Function up () {
speed-= 0.8;
bird.id = ' flybird_up '///the ID below the style for the birds to drop the background picture, and add animation to constantly replace the bird's background image, let the bird wings move Up ~
up_bgm.play ()
if (speed <= 0) {
Speed = 0;
Clearinterval (Uptimer);
Downtimer = SetInterval (down);
Bird.style.top = bird.offsettop-speed + ' px ';
}
The method of bird beating;
function Birdjump () {
speed = Speedmax;
if (isgameover) {
//Every time you jump up, the up and down timer is clear to prevent stacking
clearinterval (uptimer);
Clearinterval (Downtimer); Clear the downward timer;
Uptimer = setinterval (up);
}
Judge the bird to the ground or the bird jumps out of bounds, at this time the game end
function Floortext () {
var t1 = bird.offsettop;
if (T1 > 396) {
//game over;
Gameover ();
}
if (T1 < 0) {
gameover ();
}
}

Step 3: Through the above steps, the bird can jump off. The next step is the creation of the pipeline. The Flappybird game knows that the height of the pipe inside is random, but the distance between the top and bottom two pipes is fixed. Use Math.random () to produce random numbers.

A random function that is used to randomly produce a steel tube. rand (min, max) {return parseint (Math.random () * (max-min) + min);}//Create pipeline. After clicking on the Start button, create a function create_pipe () {var conduit_group = Document.queryselector (". Conduit_group") by the timer; var
Conduititem = document.createelement ("div");
A style for the created pipe conduititem.classname = ' conduititem ';
Place the created pipe into the outer div conduit_group.appendchild (conduititem); var topheight = rand (60, 223); The height value of the pipe inside the pipeline var bottomheight = The height value of the lower pipe inside the 373-100-topheight;//pipe creates the up and down pipe conduititem. InnerHTML = ' <div class= ' top_conduit ' ><div style= ' height: ' + topheight + ' px ' ></div></div>< Div class= "Bottom_conduit" ><div style= "Height: ' + bottomheight + ' px ' ></div></div> '/
Gets the width of the outermost div, which is the maximum value that the pipe can move var maxwidth = canvas.offsetwidth;
Let the pipeline just started outside the canvas, a beginning to see conduitItem.style.left = maxwidth + ' px ';
Add the point switch, each through a pipe score can add 1 Conduititem.addtoscore = true;
The pipeline movement method, through the timer continuously makes its left value decrement, realizes the pipeline movement. Conduititem.movetimer = setinterval (function () {maxwidth-= 3;//per 30msMove 3 pixels to the Left conduitItem.style.left = maxwidth + ' px '//After the pipe runs out, clear the timer that moved the pipe and remove it. if (maxwidth <= -70) {clearinterval (Conduititem.movetimer); Conduit_group.removechild (Conduititem);}//
Score plus 1 if (conduititem.offsetleft <= && Conduititem.addtoscore = = True) when the offsetleft of the pipe is less than 30 o'clock, that is, after the bird has successfully passed the pipe.
score++;
Conduititem.addtoscore = false;
Scorefn (score); }}, 30)}

Step 4: With the above steps, the moving pipe is created, and the bird can jump. The next step is to carry out collision detection to determine whether the bird is touching the pipe.

//bird and pipe collision detection, obj1 for birds, obj2 for upper and lower pipe parent set//direct fetch up and down pipe, offsetleft is 0, so get its parent set; function Crashtest (
Obj1, Obj2) {//bird related amount var L1 = bird.offsetleft Console.log (L1) var r1 = L1 + bird.offsetwidth; var t1 = bird.offsettop;
var B1 = t1 + bird.offsetheight//pipeline related quantity var L2 = Obj2.offsetleft;
var r2 = L2 + obj2.offsetwidth;
var t2 = obj1.offsettop;
var b2 = t2 + obj1.offsetheight;
Judge condition if (R1 > L2 && L1 < R2 && B1 > t2 && T1 < B2) {Gameover ();}} Function judge () {//Get all pipelines created on current page, var conduititem = Document.queryselector ('. Conduit_group ') for an array.
Queryselectorall ('. Conduititem ');
Traverse the displayed pipeline and pass parameters to the Crashtest method for judgment. for (var i = 0; i < conduititem.length i++) {var top_conduit = Conduititem[i].queryselector ('. Top_conduit '); var Botto
M_conduit = Conduititem[i].queryselector ('. Bottom_conduit ');
Crashtest (Top_conduit, conduititem[i]);
Crashtest (Bottom_conduit, conduititem[i]); }
}

Step 5: Game End method. When hit the pipe, hit the upper boundary, landing, the game is over, showing the score of this Council, and showing the highest record of history.

Game End
Function Gameover () {
//Game Over background music open
gameover_bgm.play ();
Isgameover = false;
End Music
bgm.pause ();
Cleartimer ();
The bird changed back to the original style
bird.id = ' Flybird '
bird.classname = ' Birddown '
bird.style.top = ' 392px ';
Store highest record
var historyscore = Localstorage.getitem (' Maxscore ');
Creates a masscore when the history does not exist or if the history is less than the current record.
if (Historyscore = null | | Historyscore < score) {
localstorage.setitem (' Maxscore ', score);
Refresh record
Historyscore = score;
}
Historical highest record
historyscore.innerhtml = Historyscore;
Current score
thisscore.innerhtml = score;
Show game End screen
document.queryselector ('. Gameover '). style.display = ' block ';
}

Step 7: Game Start method.

Game Initialization
function init () {
//is start_btn, that is, the start create click event that the page just starts showing, that is, the begin button
Start_btn.onclick = function () {
After clicking, the start interface hides
GameStartDiv.style.display = ' none ';
Birds show up
bird.style.display = ' block ';
Make the bird in the middle show
bird.style.top = ' 200px ';
Bgm.play ();
Click to invoke the Birdjump method to make the bird rise
//start creating pipelines
Conduittimer = SetInterval (Create_pipe, Watts)
Document.addeventlistener (' Click ', Birdjump, false)
Crashtesttimer = setinterval (judge, 1000/60);
}
init ();

Step 7: Game Restart method

Restart
var game_restart = Document.queryselector (". Game_restart")
Game_restart.onclick = restart;
var conduit_group = Document.queryselector (". Conduit_group")
//back to the initial interface
function restart () {
Bird.classname = ' bird '
cleartimer ();
scorediv.innerhtml = null;
Isgameover = true;
Speed = 0;
score=0;
Speedmax = 8;
Document.queryselector ('. Gameover '). style.display = ' None ';
GameStartDiv.style.display = ' block ';
Bird.style.display = ' None ';
conduit_group.innerhtml = ';
}

The Cleartimer method used here is to clear all the timer, the code is as follows:

function Cleartimer () {
var timer = setinterval (function () {},);
for (i = 0; i < timer; i++) {
clearinterval (i);
}
}

So the game is roughly done.

The effect chart is as follows:

Download the source code below the address, please Google browser on the test.

SOURCE Download Address

The above is a small series to introduce the pure JavaScript to achieve Flappy Bird small game Instance code, I hope to help you, if you have any questions please give me a message, small set will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.