Technical Implementation Analysis of android game development

Source: Internet
Author: User

Technical Implementation Analysis of android game development

In android development, you may have the urge to develop a small game. How can you use android to develop a game? Fortunately, google provides some developed game instances. We can start with two of them to explore.

For lightweight games, we can write our own view to display the core content of the game! Then, refresh the view at a certain frequency. We call the invalidate () of the view to implement it. for details, let's take a look at a common game: Snake. Below we will analyze some key code for implementing this game.

Like other apps, Snake starts with an Activity and uses setContentView (R. layout. this line of code is used to determine the layout of the displayed content. It is necessary to check the content of this layout file (as follows ):

 

 
  
   
     
    
   
  
 
In the above Code, we need to note that the layout file is limited by merge: because our layout is framelayout, merge is used here, because the parent groupview of any view added to the activity is framelayout.

 

Here we focus on the point of view, which is the core of the game. pay attention to this line of code: app: tileSize = 24dp. this is an attribute defined by the snail view itself, used to define the size of the snake. to use this method, you must first go to attrs. in xml, this attribute is defined for the browser view. Let's see how this attribute is defined:

 

  
       
 
You must be wondering, how is TileView? In fact, snail view is a subclass of TileView, and TileView is a subclass of view.

 

So let's take a look at the implementation of the snake view. (the specific implementation of the snake is not designed. Here we only introduce the core of game development ). in fact, the animation effect of the game is to repeatedly call invalidate to make the view reproduce and draw, which is achieved by rewriting the onDraw (Canvas canvas) of the View. in this way, when invalidate () is called, The onDraw (Canvas canvas) callback of the view is triggered, and the content to be displayed every time in the game is drawn by onDraw.

The following code regularly refreshes the view:

 

    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 preceding definition is a handle, which acts as a timer. To update () the content to be drawn next time every delayMillis for such a long time, and then invalidate () to refresh.

 

The implementation of onDraw is as follows:

 

    @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] > 0) {                    canvas.drawBitmap(mTileArray[mTileGrid[x][y]], mXOffset + x * mTileSize,                            mYOffset + y * mTileSize, mPaint);                }            }        }    }
As you can see through the code above, some images are actually drawn, and these images form a snake according to certain coordinates. therefore, every time the information in the mTileGrid is accurate, the image is accurate.

 

We can do this for lightweight games such as snake and chess, but it is not practical for some fighting games, when you need to draw a large number of image resources/ringtone resources, you will not be able to meet your needs. in this case, we need a special view: SurfaceView.

Fortunately, google provides me with an example: JetBoy. Let's take a look at how to use SurfaceView.

(1) first, the SurfaceView you write needs to implement this interface SurfaceHolder. callback, whose purpose is to obtain the state changes of our SurfaceView (created successfully, size changed, and destroyed ). the following code:

 

public class JetBoyView extends SurfaceView implements SurfaceHolder.Callback {
(2) We need to get the SurfaceHolder of SurfaceView and use SurfaceHolder. Callback. You need to complete the following code in the constructor:

 

 

    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 large amount of content, we usually need to open a thread to do this work. the reason is described in detail below: we can obtain the SurfaceView Canvas through the SurfaceHolder obtained above, so we only need to use this Canvas to draw what we need, these tasks are all completed in the defined thread. Of course, all these tasks should be completed after SurfaceView is created (surfaceCreated (SurfaceHolder arg0) callback. let's take a look at the core code in run in thread:

 

 

        public void run() {            // while running do 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 that if an exception is thrown                    // during the above, we don't leave the Surface in an                    // inconsistent state                    if (c != null) {                        mSurfaceHolder.unlockCanvasAndPost(c);                    }                }// end finally block            }// end while mrun block        }

The above Code uses mSurfaceHolder. lockCanvas (null); to obtain the canvas of SurfaceView, and then draw the content to point to this line of code mSurfaceHolder. unlockCanvasAndPost (c );

 

(4) So we need to start our game when surfaceCreated:

 

    public void surfaceCreated(SurfaceHolder arg0) {        // start the thread here so that we don't busy-wait in run()        // waiting 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, it's very easy for everyone to understand it.

 

 

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.