【 introduction 】
As a front-end beginner, adhering to the idea that students who don’t want to be teachers are not good students. I used my spare time to sort out FlyBird, a small game that once made people want to smash their mobile phones, into a small tutorial for everyone to guide.
【 Home Page 】
-
First of all, we analyze the composition of the home page image, we can find the following elements ① background ②start button ③ headline ④ bird ⑤ grass (rolling) and other five plates. Here we do it with images, although it’s possible to do it in code, but it’s too much work to recommend it.
-
Start by creating a basic HTML page (shortcut keys! + TAB to quickly create the base page) We started by creating a box #wrapBg to hold the background image based on what we saw on the game cover and set the width and height.
> #wrapBg > { > height: 480px; > width:343px; > margin:0 auto; > position: relative; > top:100px; > background-image: url(../img/bg.jpg); > } Copy the code
Margin 0: auto centrizes the image horizontally on the x axis. In this case, the position attribute is relative, which is used as the parent element for other image positioning below, as will be mentioned later.
-
Place a caption in the background and position it, and place a picture of a bird in it
> <! - the title -- -- > > < div id = "headTitle" > > < img SRC = "img/bird0. PNG" Alt = "" id =" headBird "> > < / div >Copy the code
-
Set the position of the title in the CSS with absolute position. The parent container is the #wrapBg box and is positioned relative to the parent container
> #headTitle > { > width: 236px; > height:77px; > background-image: url(../img/head.jpg); > position:absolute; > left:53px; > top:100px; > } Copy the code
/ Positioned relative to the parent container. A relative container is the parent of a relative container, even absolute. If there is no parent container, use body as an example to locate /
-
Since the bird was written to the headTitle box, we can also position the bird here, but in this case we float it to the far right of the box. Run sequentially) by setting float to go to the far left or right, like pulling someone out of a queue and letting them go anywhere.
-
Position the buttons step by step
> #startBtn{ > width:85px; > height: 29px; > background-image: url(.. /img/start.jpg); > position: absolute; > left:129px; > top:250px; >}/* The button has a built-in margin of its own.Copy the code
The next stage is to make the title, the bird, the wings and the grass move
The title movement
First of all, we thought about how to make the title move up and down. In this case, we first thought about how to move the title by changing its position, so we moved it up and down by 3 pixels to move it back and forth. The first thing we need to do is move the image in the title box, and in this case we get the current DOM structure from the id property and we define jsHeadTitle to get its DOM structure
var jsHeadTitle = document.getElementById(‘headTitle’);
Define the amount of movement up and down, in this case we set it to 3 pixels
Var Y = 3// Swing up and down by 3 pixels
Let’s create a function to do this
` function headWave() { Y = Y * -1; jsHeadTitle.style.top = jsHeadTitle.offsetTop + Y + 'px' <! -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - line -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -! Jsheadbird.src = imgArr[index++] if (index == 2) {index = 0; // Assign 0} 'as soon as index becomes 2Copy the code
In the first half of this function, the position of the title box is changed by changing the upper distance between the title box and the parent box. Here, we use offsetTop to obtain the value of top in the headTitle. We take the way of setting the Y value to be negative to realize the up and down movement of the title.
The wings of a bird move
The second half of this function is to make the wings of the bird move back and forth, we take the wing image constantly change to achieve the effect.
- Let’s start by defining an array to hold pictures of bird wings
var imgArr = ['img/bird0.png', 'img/bird1.png']
- Get the current DOM structure by id
var jsHeadBird = document.getElementById('headBird');
-
Use the following code, when index is equal to 2, assign it a value of 0, and then repeat, to achieve the effect of two images constantly switching back and forth
` jsHeadBird.src = imgArr[index++] if (index == 2) { index = 0; Var headWaveTimer= setInterval(headWave, 200) 'Copy the code
Here, a timer is used to implement the function’s timing
The grass rolling
We thought, how do we make the grass roll? Let the grass grow forever? Obviously, our computer can’t hold it. The general idea is to use two pictures of the same grass to move back and forth in a fixed position on the Y axis.
The code implementation is as follows, first in HTML
<div id="grassLand1"></div> <div id="grassLand2"></div>
Then go back to the CSS and set the properties for grassland 1 and grassland 2 alignment respectively
> #grassLand1,#grassLand2
> {
> width:343px;
> height: 14px;
> background-image: url(../img/banner.jpg);
> position: absolute;
> top:423px;
> }
Copy the code
The left attribute is set to the width of the grass because the grass is rolling back and forth so one has no margin and one is just outside
> #grassLand1 > { > left:0; > } > #grassLand2 > { > left:343px; >}Copy the code
The reason why grass 1 is left is 0 is that #grassLand1 is right in the wrapBg, and the other set distance is 343px, the width of the wrapBg box, so it is right in the right of the box, so that the overflow image is not shown, we use this line here
overflow: hidden; /* Used to hide the grass outside the container */
To hide the spilled grass
(Now it’s the spilled grass)
Again, we get the current DOM structure by id
var jsGrassLand1 = document.getElementById(‘grassLand1’) var jsGrassLand2 = document.getElementById(‘grassLand2’)
The landRun function is then set up to achieve the effect
> > 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' > } > SetInterval (landRun, 30) also uses timers to run functions for effectCopy the code
The two if statements are the key to rolling the grass back and forward. We determine whether the grass is < =-343px by getting its left value. According to the relative position, the grass is just to the left of the wrapBg
At this point, the basic page of the game has been created, so we need to start a full game, click the start button, the original start page must be replaced by the game page
First again, let’s get it first
var jsStartBtn=document.getElementById(‘startBtn’)
Then create a function
` jsStartBtn. Onclick = function () {jsHeadTitle. Style. The display = 'none' / / CSS properties to add a style, Jsstartbtn.style. display='none' // ClearInterval (headWaveTimer) // Insert bird into page bird.showbird (jsWrapBg)} 'Copy the code
When the button is pressed, the button key and title disappear from the screen, and a new screen appears. Here we create a Bird object to implement
> > var bird={> flyTime:null, key: value; > wingTimer: null, / / bird swing timer > > div: document. The createElement method (' div '), / / the mean it is a container div > showBird: function (parentobj) > {> This. Div. Style. The width = '40 px / / to the above the container width is set to 40 px > this. Div. Style. The height =' 28 px '> this. Div. Style. Background = "# 000" > Parentobj.appendchild (this.div)// Add a child div >}// after calling it, a bird will appear on the page >} >Copy the code
We need a bird that, at the press of a button, appears out of thin air, freefall, and flaps its wings so let’s define a bird here
> < div style = "max-width: 100%; clear: both; min-height: 1em; 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) > },Copy the code
After setting the width and height of the bird, by default the image will be tiled horizontally or vertically in the box when it is smaller than the box. All we need in this game is a bird, So we are here to bird0. PNG setting location and not flat out > this. Div. Style.css. BackgroundRepeat = ‘no – repeat’ > this. Div. Style. The position = ‘absolute’ > this.div.style.left = ’50px’ > this.div.style.top = ‘200px’
At the same time, use the z-index attribute to set the stack order. Set bird’s Z-index to a positive value and place it in the first place. From this, you can understand the next 7 layers of stack level
The specific content is understood by myself and will not be described here. After set up good bird0, we think, what can I do for this game, we can learn that a bird in the picture in the process of advancing flying up and down between the pillars, but obviously if the manipulation of the birds are flying up and down to move forward at the same time, with the code to implement is complicated, so we will be divided into two parts. One part is to control the movement of the bird up and down, and the other part is to control the movement of the column to achieve the effect of relative movement. Here, we set the initial velocity of the bird at 0
FallSpeed: 0, // The speed at which the bird falls
Then write the function that controls the bird’s fall
> flyBird: Function () {bird.flyTime = setInterval(fly, flyTime); 60) > function fly() { > bird.div.style.top = bird.div.offsetTop + bird.fallSpeed++ + 'px' > if (bird.div.offsetTop >= // Fall to the ground, Clear timer > bird.fallSpeed = 0 > clearInterval(bird.flytime) > clearInterval(bird.wingTimer) >} > // Keep birds from flying out of bounds > if (bird.div.offsetTop < 0) { > bird.div.style.top = '0px' > bird.fallSpeed = 2 > } > if (bird.fallSpeed > 12) { > Bird. fallSpeed = 12 >}// Set maximum speed >} >},Copy the code
At this time, we have written the bird falling function, which for the bird touch the ground and the bird fly out of the upper boundary of the two cases were set with the code, which when the bird touch the upper boundary, set the speed of the bird at that time. Then write the function to control the bird’s upward flight. We control the bird’s upward flight by setting its bird.fallSpee to -8 when the button is clicked. The specific code is as follows:
` bird.showBird(jsWrapBg)
bird.flyBird()
bird.wingWave()
jsWrapBg.onclick=function(){
bird.fallSpeed=-8
}`
Copy the code
Although we can control the rising and falling of the bird at this time, we will find that the direction of the bird’s wings and head will not flap or change, so we adopt the method of the bird’s wings flapping in the cover above:
` wingWave: 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)'] bird.wingTimer = setInterval(wing, 120) var i = 0,j=0 function wing() { if(bird.fallSpeed>0){ bird.div.style.backgroundImage = down[i++] if (i == 2) { i = 0 } } if (bird.fallSpeed < 0) { bird.div.style.backgroundImage = up[j++] if (j == 2) { j = 0} } }Copy the code
HTML code implementation
var jsStartBtn = document.getElementById('startBtn') jsStartBtn.onclick = function() { jsHeadTitle.style.display = 'none' jsstartBtn.style. display = 'none' clearInterval(headWaveTimer) bird.showbird (jsWrapBg) bird.flybird () Bird.wingwave () jswrapbg.onclick = function() {bird.fallspeed = -8}Copy the code
After doing the above steps, our bird’s wings and head can change as it flies up and down. The next step is to set up the pipe for the game. For fun, we set the length of the pipe to be random.
Var baseObj={randomNum:function(min, Max){return Math. Random ()*(max-min+1)+min ParseInt (math.random ()*(max-min+1)+min)Copy the code
Then let the function get a random number to set the length and gap of the upper and lower pipes
Function Block(){this.updivWrap =null this.downDivWrap=null this.downheight = baseobj.randomNum (0,150)// Set the height between 0 and 150 This. GapHeight = baseobj. randomNum(150,160)// Set the pipe gap this.upHeight=312-this.downHeight-this.gapHeight// set the pipe gapCopy the code
Next we declare a method to generate the pipe
this.createDiv=function(url,height,positionType){
var newDiv=document.createElement('div')
newDiv.style.width='62px'
newDiv.style.height=height
newDiv.style.position=positionType
newDiv.style.left=left
newDiv.style,top=top
newDiv.style.backgroundImage=url
return newDiv
Copy the code
The value is then written to generate the pipe
this.creatBlock=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)
jsWrapBg.appendChild(this.upDivWrap)
}
Copy the code
The next step is to call them in HTML. Instantiate to generate a pipe.
Var b = new Block() // instantiate b.createBlock()Copy the code
Then set the motion of the pipe
this.moveBlock = function () {
this.upDivWrap.style.left = this.upDivWrap.offsetLeft - 3 + 'px'
this.downDivWrap.style.left = this.downDivWrap.offsetLeft - 3 + 'px'
}
}
Copy the code
Then we write the code to determine the collision in JS
// Determine whether the rectangleCrashExamine rectangles collide: 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 } }Copy the code
Write here roughly end, because the code is too long will not post the complete code, in this post link, there is a need for friends to download learning because I github side temporarily can not upload, here is the gitee address gitee.com/little-fish…