JavaScript implementation Fly Bird games _javascript Skills

Source: Internet
Author: User
Tags setinterval

This tutorial for you to share the fly bird small game production process, for your reference, the specific content as follows

1. Analyze page structure, clarify requirements and functions

The game has three interfaces, namely the start interface, the game interface and the game end interface.

1.1 Start interface

Start.gif

The big background of the game
Move up and down the game title and Wings swinging The birds
Start button, click to enter the game interface
The ground that has been moving

1.2 Game Interface

Play.gif

A scoreboard that shows the number of hurdles crossed
The moving obstacles, respectively, are the upper and lower pipes.
Click on the game screen, the birds fly up, and then fall under the action of gravity,
When the bird and the pipe collide, The End interface pops up, while the bird falls to the ground

1.3 End Interface

Gameover Hint Panel
OK button

2. Develop "Start interface"

Considering the effect of the lawn movement, we added two meadows to the page.

2.1 HTML

<! DOCTYPE html>
 
 

2.2 CSS

#wrapBg {/* Game background * * *
 width:343px;height:480px; 
 margin:0 Auto;
 Background-image:url (.. /img/bg.jpg);
 position:relative;
 top:100px;
 Overflow:hidden;
}
#headTitle {/* start title *
 /width:236px;height:77px;
 Background-image:url (.. /img/head.jpg);
 Position:absolute; left:53px; top:100px;
}
#headBird {/* The beginning of the title of the bird * * *
 float:right;
 margin-top:25px;
}
#startBtn {/* Start button *
 /width:85px;height:29px;
 padding:0;margin:0;
 Background-image:url (.. /img/start.jpg);
 position:absolute;left:129px;top:250px;
}
#grassLand1 {/* grassland 1*/
 height:14px;width:343px;
 Background-image:url (.. /img/banner.jpg);
 position:absolute;top:423px;
}
#grassLand2 {/* grassland 2*/
 height:14px;width:343px;
 Background-image:url (.. /img/banner.jpg);
 position:absolute;top:423px;left:343px;
}

The page effect that will be commented out in the WRAPBG Overflow:hidden

Start interface. jpg

2.3 JS

The effect of a bird fanning its wings requires the principle of frame-by-step animation.
One-frame animation is a common form of animation (frame by frame), whose principle is to decompose the animation action in "continuous keyframes", that is, to draw different content on each frame of the timeline so that it is animated continuously.

2.3.1 Start the swinging of the title

 var jsheadtitle = document.getElementById ("Headtitle");/Get title
  var Jsheadbird = document.getElementById ("HeadBird "); Get the bird

  var Y = 3;//title in the title of the swing amplitude
  var index = 0;
  var Imgarr = ["Img/bird0.png", "img/bird1.png"] 
  //Put the bird image path into an array, making use of the principle of frame animation to make the bird's wings swing the way
  var headwavetimer = SetInterval (headwave,200); Set the timer
  function Headwave () {
   Y *=-1
   ) swinging the title up and down JsHeadTitle.style.top = jsheadtitle.offsettop + Y + "px";
   JSHEADBIRD.SRC = imgarr[index++];
   if (index = = 2) {
    index = 0;
   }
  }

2.3.2 The Moving Meadows

  var jsGrassLand1 = document.getElementById ("GrassLand1"); Get grassland 1
  var jsGrassLand2 = document.getElementById ("GrassLand2");//Get Grassland 2

  var landtimer = setinterval (landrun , 30); Timer
  function Landrun () {
   if (jsgrassland1.offsetleft <= -343) {
    JsGrassLand1.style.left = " 343px ";
   }
   if (jsgrassland2.offsetleft <= -343) {
    jsGrassLand2.style.left = "343px";
   }
   JsGrassLand1.style.left = jsgrassland1.offsetleft-3 + "px";
   JsGrassLand2.style.left = jsgrassland2.offsetleft-3 + "px";
  }

2.3.3 Start button

  var jsstartbtn = document.getElementById ("startbtn");
  Jsstartbtn.onclick = function () {//Add click event handler for Start button
   JsHeadTitle.style.display = "none";//Hide title
   Clearinterval (Headwavetimer); Turn off the timer
   jsStartBtn.style.display = "None" to swing the title;//Hide key//
   Add function
   /Click Start button to enter the game interface
  }

The effect after the completion (comment out the WRAPBG in the Overflow:hidden)

Start01.gif

Next we develop the "game interface"
3. The development of "game interface"
There are three elements in the game interface, namely "Bird", "obstacle", and "scoreboard", we create the corresponding object in sequence.
3.1 Birds
First, create the object of the bird, bird.js the file.

var bird = {flytimer:null,//Bird flying timer wingtimer:null,//bird Wings swinging timer div:document.createElement ("div"), showbird:function (parentobj)
  {this.div.style.width = "40px";
  This.div.style.height = "28px";
  this.div.style.backgroundImage = "url (img/bird0.png)";
  This.div.style.backgroundRepeat = "No-repeat";
  This.div.style.position = "absolute";
  This.div.style.left = "50px";
  This.div.style.top = "200px";

  This.div.style.zIndex = "1"; Parentobj.appendchild (THIS.DIV);
  Insert the bird div into the game interface}, fallspeed:0,////Bird Drop speed flybird:function () {//The function of controlling the flying whereabouts of birds Bird.flytimer = SetInterval (fly,40);
   Function Fly () {bird.div.style.top = Bird.div.offsetTop + bird.fallspeed++ + "px";
    if (Bird.div.offsetTop < 0) {bird.fallspeed = 2;//This is used to control birds not to fly out of the interface} if (Bird.div.offsetTop >= 395) {
    bird.fallspeed = 0; Clearinterval (Bird.flytimer); Once you fly to the ground, clear the timer clearinterval (Bird.wingtimer); Clear Wings Swinging Timer} if (Bird.fallspeed >) {bird.fallspeed = 12;//the largest birdDrop speed control in the}}, Wingwave:function () {//control the bird's wing-stirring function var up = [url (img/up_bird0.png), url (img/up_bird1.png)
  ];
  var down = ["url (img/down_bird0.png)", "url (img/down_bird1.png)"];
  var i = 0, j = 0; Bird.wingtimer = SetInterval (wing,120)//Frame animation, birds incite wings function Wing () {if (Bird.fallspeed > 0) {bird.div.styl
    E.backgroundimage = down[i++];
    if (i==2) {i = 0}}if (Bird.fallspeed < 0) {bird.div.style.backgroundImage = up[j++];

 if (j==2) {j = 0}}},};

Below, when implementing click on the Start button, load the bird. (added on the basis of previous code)

Jsstartbtn.onclick = function () {//Add click event handler for Start button
 JsHeadTitle.style.display = "none";//Hide title
 Clearinterval (Headwavetimer); Turn off the timer
 jsStartBtn.style.display = "None" to swing the title;//Hide the key
 Bird.showbird (JSWRAPBG);//Insert the bird into the interface
 Bird.flybird (); Control the flying whereabouts
 of birds bird.wingwave ()///Frame animation, birds incite wings
 jswrapbg.onclick = function () {
  bird.fallspeed =-8;
 };
 To add features
 //Click Start button to enter the game interface
}

The effect of adding birds

Play01.gif

3.2 Barriers (upper and lower water pipes)

Block schematic. png

Barriers are divided into the upper pipe and the lower pipe, as shown in the schematic structure nesting, so you can randomly set DownDiv2 height and gapheight height, to change the shape of the formation of obstacles
Block.js

function block () {this.updivwrap = null;
 This.downdivwrap = null;
 This.downheight = Baseobj.randomnum (0,150);
 This.gapheight = Baseobj.randomnum (150,160);

 This.upheight = 312-this.downheight-this.gapheight; The method used to generate the div this.creatediv = function (URL, height, positiontype, left, top) {var newdiv = document.createelement ("di
  V ");
  NewDiv.style.width = "62px";
  NewDiv.style.height = height;
  NewDiv.style.position = PositionType;
  NewDiv.style.left = left;
  NewDiv.style.top = top; newDiv.style.backgroundImage = URL;
 "URL (/img/0.jpg)" Return newdiv;

 };
  This.createblock = function () {var upDiv1 = this.creatediv ("url (img/up_mod.png)", This.upheight + "px");
  var upDiv2 = this.creatediv ("url (img/up_pipe.png)", "60px");
  This.updivwrap = This.creatediv (null, NULL, "absolute", "450px");
  This.upDivWrap.appendChild (UPDIV1);
  This.upDivWrap.appendChild (UPDIV2)//Generate above pipeline var downDiv1 = this.creatediv ("url (img/down_pipe.png)", "60px"); var downDiv2 = this.crEatediv ("url (img/down_mod.png)", This.downheight + "px");
  This.downdivwrap = This.creatediv (null, NULL, "absolute", "450px", 363-this.downheight + "px");
  This.downDivWrap.appendChild (DOWNDIV1); This.downDivWrap.appendChild (DOWNDIV2);
  Generate the pipe below jswrapbg.appendchild (this.updivwrap);
 Jswrapbg.appendchild (This.downdivwrap);

 };
  This.moveblock = function () {//The method of controlling pipeline movement This.upDivWrap.style.left = this.updivwrap.offsetleft-3 + "px";
 This.downDivWrap.style.left = this.downdivwrap.offsetleft-3 + "px"; 
};

 }

Common Object file Baseobj.js, used to provide random numbers, and collision detection of two rectangular div

var baseobj = {
 //random number
 randomnum:function (min, max) {return
  parseint (Math.random () * (Max-min + 1) + min); c4/>},

 //Two rectangle element Collision detection
 rectanglecrashexamine:function (obj1, obj2) {
   var obj1left = obj1.offsetleft;
   var obj1width = obj1.offsetleft + obj1.offsetwidth;
   var obj1top = obj1.offsettop;
   var obj1height = obj1.offsettop + obj1.offsetheight;

   var obj2left = obj2.offsetleft;
   var obj2width = obj2.offsetleft + obj2.offsetwidth;
   var obj2top = obj2.offsettop;
   var obj2height = obj2.offsettop + obj2.offsetheight;

   if (!) ( Obj1left > Obj2width | | Obj1width < Obj2left | | Obj1top > Obj2height | | Obj1height < Obj2top)) {return
    true;
   }
   return false;
 }
;

My idea is to create a block when the Start button clicks, store the block in an array blocksarr, check the length of the array in the Landtimer timer's method Landrun, if the array is not an empty array, So let's move all the blocks in the array. The
checks the distance from the last block to the left, reaches a certain distance, and then new block is added to the array. The
checks the first block and, once it reaches a certain position, removes Downdivwrap and updivwrap in the structure and deletes it in the array.

  var Landtimer = setinterval (landrun,30);
   The Timer function Landrun () {if (Jsgrassland1.offsetleft <= -343) {jsGrassLand1.style.left = "343px") to move the lawn
   } if (Jsgrassland2.offsetleft <= -343) {jsGrassLand2.style.left = "343px";
   } jsGrassLand1.style.left = jsgrassland1.offsetleft-3 + "px";

   JsGrassLand2.style.left = jsgrassland2.offsetleft-3 + "px";
     if (blocksarr.length) {for (var i = 0; i < blocksarr.length; i++) {Blocksarr[i].moveblock ();
     var x =baseobj.rectanglecrashexamine (Blocksarr[i].downdivwrap, Bird.div);
     var y = baseobj.rectanglecrashexamine (Blocksarr[i].updivwrap, Bird.div);
     var z = bird.div.offsetTop >= 390; if (x | | y | | z) {window.clearinterval (Landtimer)//clear Landtimer Timer bird.fallspeed = 0; onclick = null;
      Eliminate Click events} if (Blocksarr[blocksarr.length-1].downdivwrap.offsetleft < (450-blockdistance)) { Blockdistance = Baseobj.randomnum (130,250);
      var newblock = new block ();
      Newblock.createblock ();
    Blocksarr.push (Newblock);
      } if (Blocksarr[0].downdivwrap.offsetleft < -50) {jswrapbg.removechild (blocksarr[0].downdivwrap);
      Jswrapbg.removechild (Blocksarr[0].updivwrap);
    Blocksarr.shift (Blocksarr[0]);

 }
   }
  }

The current game effect

Play02.gif

3.3 Scoring Device

The scoreboard in the game is relatively well implemented

  <div id= "Score" >
    <div id= "NUM1" ></div>
    <div id= "num2" ></div>
    <div id= "Num3" ></div>
   </div>
  var jsscore = document.getElementById ("score");
  var jsNum1 = document.getElementById ("Num1");
  var jsNum2 = document.getElementById ("num2");
  var jsNum3 = document.getElementById ("num3");
  var score = 0;

Today, I'll write it another day. Ha ha

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.