Write your own game: Flappy Bird

Source: Internet
Author: User

  START: recently idle, looked at the "C # development Flappy Bird Game" tutorial, I also tried to do a bit, to achieve a super simple version (very humble) Flappy Bird, using the language is C #, The technology uses the fast simple windowsform, the image mainly uses the GDI +, the game object creation control uses the singleton pattern, now I will briefly summarize.

First, about Flappy Bird

"Flappy Bird" is a work developed by Dong Nguyen, an independent game developer from Vietnam, in which the player must control a bird that crosses the barrier of water pipes of various lengths, and this bird is not flying at all ... So players every click on the bird will fly higher, do not click on the drop, the player must control the rhythm, touch the screen point of time, so that the birds can jump in the moment of falling, just can pass through the narrow gap of the water pipe, as long as a little distraction, immediately will fail to die. Simple but not coarse 8-bit pixel screen, Super Mario game in the water pipes, eyes a little sluggish birds and a few white clouds, daytime night two modes constitute the game of everything. Players need to constantly control the frequency of tapping the screen to adjust the bird's flight altitude and landing speed, so that the bird smoothly through the screen to the right of the gap. If the bird accidentally touches the tube, the game is over.

Second, Game Design 2.1 Summary Game impression

Flappy Bird's children's shoes should all have an impression on the game, now let's take a look at the features of this game:

(1) The screen of this game is very simple: a background map, has never changed;

(2) The object of this game is only two: a bird (with three waving wings) and a pair of pipes (with pipe up and down two directions);

Bird: ①②③

Pipeline:

2.2 Summarizing design ideas

  (1) Objects of all Things

Throughout the game, we see everything that we can understand as a game object; (in unity, Gameobject is a game object) each game object is created by a separate class; In the game, there are only two game objects: Birds and pipes, Then we can create two classes:Bird and Pipe. However, we find that birds and pipelines have some common properties and methods, such as x, y axis coordinates, length and width, as well as the method of drawing (Draw ()) and Moving (Move ()), when we can design an abstract class that encapsulates what is common, Reduce the development of redundant code, improve the scalability of the program, in line with the idea of object-oriented design:

  (2) Good family planning

Throughout the game, we have only one bird object, meaning that only one copy is needed in memory. At this time, we thought of the great family planning policy, so we thought of using a singleton model . With singleton mode, you can guarantee that only one instance of a bird is generated, that is, to provide a global access point to the program, and to avoid creating unnecessary waste of memory repeatedly.

  (3) Motion of the object

Throughout the game, the bird will fall down by the gravity default, and the user can fly up to the bird by tapping or pressing the keyboard space key, which is essentially changing the position of the game object on the y axis and moving it from bottom to top . , and the pipeline will appear from the right side of the screen, disappear from the left side of the screen, appear on the right side of the screen, and disappear from the left side of the screen. As you can see, the essence of the last period from the image is to change the position of the pipe object on the x axis so that it moves from right to left .

  (4) Design flowchart

Throughout the development and design process, we can design the development process according to the priority level, and implement the whole game step-by-step according to the process.

Iii. Key Code 3.1 design Abstract parent class encapsulation Common properties
    /// <summary>    ///Game Object base class/// </summary>     Public Abstract classGameobject {#region01. Constructors and properties Public intXGet;Set; }  Public intYGet;Set; }  Public intWidth {Get;Set; }  Public intHeight {Get;Set; }  PublicGameobject (intXinty) { This. X =x;  This. Y =y;  This. Width = This. Height =0; }         PublicGameobject (intXintYintWidthintheight) {             This. X =x;  This. Y =y;  This. Width =width;  This. Height =height; }         #endregion        #region02. Abstract Methods/// <summary>        ///Abstract Method 1: Draw itself/// </summary>         Public Abstract voidDraw (Graphics g); /// <summary>        ///Abstract Method 2: Move yourself/// </summary>         Public Abstract voidMove (); #endregion        #region03. Example Methods PublicRectangle Getrectangelearea () {return NewRectangle ( This. X This. Y This. Width, This.        Height); }         #endregion    }
View Code

Everything is object, here encapsulates the game object bird and pipeline common attributes, as well as two abstract methods, let the birds and pipelines to achieve their own.

3.2 Designing a singleton mode to reduce object creation
    /// <summary>    ///Bird Object Singleton mode class/// </summary>     Public classSingleobject {PrivateSingleobject () {}Private StaticSingleobject singleinstance;  Public StaticSingleobject getinstance () {if(SingleInstance = =NULL) {singleinstance=NewSingleobject (); }            returnsingleinstance; }         PublicBird Singlebird {Get; Set; }        /// <summary>        ///Add a Game object/// </summary>        /// <param name= "ParentObject" >Game Object Parent class</param>         Public voidAddgameobject (Gameobject parentobject) {if(ParentObject isBird) {Singlebird= ParentObject asBird; }        }        /// <summary>        ///draw a Game object/// </summary>        /// <param name= "G" ></param>         Public voidDrawgameobject (Graphics g) {Singlebird.draw (g); }    }
View Code

With the help of Singleton mode, there is always only one bird instance, and the main implementation is the aggregation of small birds and singleton patterns.

3.3 Design gravity Assist class allows birds to automatically fall

(1) Design of gravity auxiliary class

    /// <summary>    ///Gravity Assist Class/// </summary>     Public classGravity { Public Static floatGravity =9.8f; /// <summary>        ///s = 1/2*gt^2+vt/// </summary>        /// <param name= "Speed" >Speed</param>        /// <param name= "Second" >Time</param>        /// <returns>Displacement Amount</returns>         Public Static floatGetHeight (floatSpeedfloatTime ) {            floatHeight = (float)(0.5* Gravity * Time *Time )+ Speed *Time ; returnheight; }    }
View Code

Adding a rigidbody component to a game object in the Unity game engine can cause the game object to be affected by gravity, but in a normal program it is necessary to design the gravity class so that the game object is affected by gravity. The knowledge of middle school physics is used here: the displacement of gravitational acceleration is obtained;

(2) In the timer event, the bird will bear the influence of gravity always fall

        Private voidGravitytimer_tick (Objectsender, EventArgs e) {Bird Singlebird=singleobject.getinstance ().            Singlebird; //Step1: Getting the bird's descent height            floatHeight =gravity.getheight (singlebird.currentspeed, Singlebird.durationtime*0.001f); //Singlebird.durationtime * 0.001f = convert milliseconds to frames//Step2: Get the bird down backwards coordinates            inty = Singlebird.y + (int) height; //STEP3: Assigning the new y-axis coordinates to the bird            intMin = This. Size.Height- This. Pbxground.height- -; if(Y >min) {                //Limit the birds don't fall to the groundy =min; } singlebird.y=y; //Step4: Make the bird fall at the speed of acceleration [formula: V=v0+at]Singlebird.currentspeed =Singlebird.currentspeed+ gravity.gravity * Singlebird.durationtime *0.001f; }
View Code

The focus here is to convert milliseconds to frames, which is to make the durationtime*0.001f slow down;

3.4 Design Collision detection method to make the game end

(1) Intersectswith method of Rectangle

In the game interface, any game object can be viewed as a rectangular area (an instance of the rectangle class) whose coordinates are the x-axis and the y-axis, and its length and width, which makes it easy to determine the rectangular area in which it is located. Then, we can determine if there are overlaps between the two rectangle by rectangle's Intersectswith method, and this method returns true if there is overlap, Otherwise it will return false. So, in the flappybird is mainly to judge two cases: first, whether the birds fly to the border (above and below the screen), and the second is whether the bird hit the pipeline (up and down the pipeline).

(2) Cycle through timer events to determine if a bird touches a border or pipe

        Private voidPipetimer_tick (Objectsender, EventArgs e) {            //Mobile Pipeline             This.            Movepipeline (); //Collision DetectionBird Bird =singleobject.getinstance ().            Singlebird; if(Bird. Y = =0|| Bird. Y = = This. pbxground.height | |Bird. Getrectangelearea (). Intersectswith (Pipedown.getrectangelearea ())||Bird. Getrectangelearea (). Intersectswith (Pipeup.getrectangelearea ())) {//Pause Game                 This.                Pausegame (); if(MessageBox.Show ("you have been hung, whether to buy fat King's skateboard shoes continue to play? ",                    "Warm Tips", Messageboxbuttons.yesno, messageboxicon.question)==dialogresult.yes) {//re-initialize the game object                     This.                    Initialgameobjects (); //start the game again                     This.                Restoregame (); }                Else{MessageBox.Show ("your choice is sensible, Mr. Wang's skateboard shoes are too lame! ",                        "Warm Tips", MessageBoxButtons.OK, messageboxicon.information); Environment.exit (0); }            }        }
View CodeIv. Summary of development

From the running effect can be seen, the demo mainly completed a few of the core content: one is the movement of birds and pipelines, and the second is the bird and the border (the top and bottom and the pipeline) collision detection. Of course, there are a lot of core content not implemented, such as: calculation of the number of pipelines, the game welcome interface and the end of the interface. Want to be interested in children's shoes can go continue to improve the implementation, here to provide a my Flappy Bird implementation for reference only, thank you!

Resources

Zhaojianyu, "the most abusive game in the history of C # development-flappy bird Pixel Bird": http://bbs.itcast.cn/thread-42245-1-1.html

Accessories download

Simpleflappybirddemo:http://pan.baidu.com/s/1hqtchis

Zhou Xurong

Source: http://www.cnblogs.com/edisonchou/

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

Write your own game: Flappy Bird

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.