Technology implementation analysis of Android game development

Source: Internet
Author: User
Tags finally block

In Android development, you may have the impulse to develop a small game, so how do you use Android to develop a game? Fortunately, Google offers some examples of games that have already been developed. Let's start with his two game examples to explore.

For the lightweight mini-game, the core of its game display content, we can write a own view to achieve! Then refresh the view at a certain frequency, and we'll call the view's invalidate () to implement it. Let's take a look at a common game: Snake (Snake), Here are some of the key code to implement this game.

Like other apps, Snake is also started by an activity, the same way through Setcontentview (r.layout.snake_layout); This line of code to determine the layout of the display, it is necessary to look at the contents of this layout file (see below):

<merge xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:app= "http://schemas.android.com/apk/    Res/com.example.android.snake "> <com.example.android.snake.backgroundview android:id=" @+id/background " Android:layout_width= "Match_parent" android:layout_height= "match_parent" app:colorsegmentone= "@color/muted_red" a pp:colorsegmenttwo= "@color/muted_yellow" app:colorsegmentthree= "@color/muted_blue" app:colorsegmentfour= "@color/ Muted_green "/> <com.example.android.snake.snakeview android:id=" @+id/snake "android:background=" @android : Color/transparent "android:layout_width=" match_parent "android:layout_height=" match_parent "app:tileSize=" 24DP "    /> <textview android:id= "@+id/text" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:layout_gravity= "Center" android:gravity= "center" android:textcolor= "@color/text_violet" Android:textsiz E= "24SP" android:visibility= "visible"/> <relativelayout android:id= "@+id/arrowcontainer" android:layout_width= "Match_parent" android:layout_height= " Match_parent "android:visibility=" Gone "> <imageview android:id=" @+id/imageup "android:layout_width=" Wrap_co Ntent "android:layout_height=" Wrap_content "android:layout_alignparenttop=" true "Android:layout_centerhoriz Ontal= "true" android:padding= "20DP" android:src= "@drawable/dpad_up"/> <imageview android:id= "@+id/imag Eleft "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_alignparentl Eft= "true" android:layout_centervertical= "true" android:padding= "20DP" android:src= "@drawable/dpad_left"/&    Gt <imageview android:id= "@+id/imageright" android:layout_width= "wrap_content" android:layout_height= "Wrap_conte      NT "android:layout_alignparentright=" true "android:layout_centervertical=" true "android:padding=" 20DP " Android:src= "@drawAble/dpad_right "/> <imageview android:id=" @+id/imagedown "android:layout_width=" Wrap_content "Android:      layout_height= "Wrap_content" android:layout_alignparentbottom= "true" android:layout_centerhorizontal= "true" android:padding= "20DP" android:src= "@drawable/dpad_down"/> </RelativeLayout></merge>
The above code, the first thing we need to note is that this layout file uses the merge to qualify: Because our layout is framelayout, so here is the merge, Because the parent of any view that joins the activity is framelayout. Groupview

Here we focus on Snakeview, the view is the core of this game. Here's a line of code: app:tilesize= "24DP". This is a property defined by Snakeview, which defines the size of the snake. To be able to use this, You need to define such a property for Snakeview in Attrs.xml first, and see how it is defined here:

  <declare-styleable name= "Tileview" >    <attr name= "tilesize" format= "Dimension"/>  </ Declare-styleable>
You must be wondering, how is Tileview? In fact Snakeview is a subclass of Tileview, and Tileview is a subclass of view.

So let's focus on the implementation of Snakeview. (The specific implementation of the snake is not designed, this is just to introduce a game development of the implementation of the core). In fact, the animation effect of the game is to repeatedly call invalidate to facilitate the view to reproduce the drawing, by rewriting the view of the OnDraw (canvas canvas) to implement. Since then, When invalidate () is called, the view's own callback OnDraw (canvas canvas) is triggered, and each time the game needs to be displayed is drawn by OnDraw.

Here is the code to refresh the view periodically:

    Class Refreshhandler extends Handler {        @Override public        void Handlemessage (Message msg) {            SnakeView.this.update ();            SnakeView.this.invalidate ();        }        public void sleep (long delaymillis) {            this.removemessages (0);            Sendmessagedelayed (obtainmessage (0), delaymillis);        }    ;

The above definition is a handle, the handle plays a role of timer, every delaymillis so long, to update updates () needs the next draw of the content, and then invalidate () to refresh.

Here is the realization of his OnDraw:

    @Override public    void OnDraw (canvas canvas) {        super.ondraw (canvas);        for (int x = 0; x < mxtilecount; x + = 1) {for            (int y = 0; y < mytilecount; y + = 1) {                if (Mtilegrid[x][y] &G T 0) {                    canvas.drawbitmap (Mtilearray[mtilegrid[x][y]], Mxoffset + x * mtilesize,                            myoffset + y * mtilesize, mPaint); c8/>}}}}    
Through the above code can be known, in fact, the drawing of some pictures, these pictures in accordance with a certain number of coordinates to form a snake. So every time the information inside the Mtilegrid is accurate, the image it draws is accurate.

For a lightweight game like snake/chess, we can do this, but for some fighting games it is not very useful, when you want to draw a large number of image resources/ringtones resources when it will not meet the need. We need a special view:surfaceview at this time.

Fortunately, Google provided me with an example: Jetboy. Let's look at how to use Surfaceview.

(1) First of all, you write the Surfaceview need to implement this interface Surfaceholder.callback, whose purpose is we need to get the status change of our Surfaceview (Create success/size Change/Destroy). The following code:

public class Jetboyview extends Surfaceview implements Surfaceholder.callback {
(2) We need to get Surfaceview surfaceholder, and using surfaceholder.callback, you need to complete the construction method, the following code:

    Public Jetboyview (context context, AttributeSet Attrs) {        Super (context, attrs);        Register our interest in hearing about changes to our surface        surfaceholder holder = Getholder ();        Holder.addcallback (this);

(3) Because, we need to draw a lot of content, so we generally need to open a thread to do the work. Here is a detailed explanation of why: we can get this surfaceview canvas with the Surfaceholder obtained above. So as long as we use this canvas to draw what we need, we all do it in our defined thread, and all of this should be done after Surfaceview is created (surfacecreated (Surfaceholder arg0 ) to complete. Here's the kernel code inside the run inside thread:

        public void Run () {            //while running does stuff in this loop...bzzz!            while (Mrun) {                Canvas c = null;                .........                try {                    c = Msurfaceholder.lockcanvas (null);                    Synchronized (msurfaceholder) {                    dodraw (c);                    }                } finally {                    //do-this-in a-finally so-if an exception                    is thrown//during the above, we don ' t le Ave The Surface in a                    //inconsistent state                    if (c! = null) {                        msurfaceholder.unlockcanvasandpost (c);                    }                }//End Finally block            }//End while Mrun block        }

The above code passes Msurfaceholder.lockcanvas (NULL), to get our Surfaceview canvas, and then draw the content, Draw complete point to this line of code msurfaceholder.unlockcanvasandpost (c);

(4) So we need to start our game in surfacecreated:

    public void surfacecreated (Surfaceholder arg0) {        //start of the thread here so, we don ' t busy-wait in Run ()        //W Aiting for the surface to be created        thread.setrunning (true);        Thread.Start ();    }
End our thread at surfacedestroyed:

    public void surfacedestroyed (Surfaceholder arg0) {        Boolean retry = true;        Thread.setrunning (false);        while (retry) {            try {                thread.join ();                Retry = false;            } catch (Interruptedexception e) {            }        }    }

In fact, they are very simple to use a bit to understand.


Technology implementation analysis of Android game development

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.