Android Game Development Introduction Simple Example _android

Source: Internet
Author: User
Tags android games

Developing games on Android is something that Android developers aspire to, have a sense of achievement and fun, and get financial rewards. So how do you develop Android games? Here's a simple example of getting started.

First, the creation of new projects

First, we create a new project called Movement in Eclipse and choose the right Android SDK, where we use the lower 1.5 version of the API to make it more adaptable. Next, we create two new classes, one is the Updatethread class, the other is the Surfaceview class, they are in the project is responsible for processing threads and screen two classes, in the next will be detailed, the following figure, set up these two classes, to choose the correct inheritance of their parent class:

After the setup is complete, the system's project structure should look like this:

Ii. Preparation of Movment.java initiation program

Any Android application must have a master launcher to boot, and we'll name this launcher movment, and the code is simple as follows:

Java code

public class Movement extends activity {  
 @Override public 
 void OnCreate (Bundle savedinstancestate) {  
 
   Super.oncreate (savedinstancestate);  
   Setcontentview (This) (new Movementview);  
 }  

Note that our launcher does not, like other programs, pass in the interface layout file in the Setcontentview when it starts, but instead passes the Movementview instance directly in, that is, the Movementview class is started directly in this class , we'll paint our little balls.

Third, what is Surfaceview

In Android, Surfaceview is an important drawing container that can get image data directly from hardware interfaces such as memory or DMA. Typically, the view and user responses of a program are handled in the same thread, which is why handling long time events (such as accessing a network) needs to be placed in another thread (preventing the current UI thread from being manipulated and drawn). However, you cannot modify UI elements in other threads, such as updating custom view with a background thread (calling view's OnDraw function in Custom view) is not allowed.

If it takes a long time to draw an interface on another thread, require a quick update interface, or render a UI interface, it will take surfaceview. The Surfaceview contains a surface object, and surface can be drawn in a background thread.

In this article, we will use it, directly through the code to create a small ball, and with the Updatethread thread update, constantly changing the position of the ball, we began to learn the movementview of writing, first look at how to use the Surfaceview.

First, import the Surfaceview and related library files for the drawing, as follows:

Java code

Package example.movement;  
 
Import Android.content.Context;  
Import Android.graphics.Canvas;  
Import Android.graphics.Color;  
Import Android.graphics.Paint;  
Import Android.graphics.Rect;  
Import Android.view.SurfaceHolder;  

Next, we're going to inherit Surfaceview and implement the Surfaceholder.callback interface, which is a surfaceholder internal interface that enables the interface to get information about the changes to the interface, code as follows, and we declare some member variables:

Java code

public class Movementview extends Surfaceview implements Surfaceholder.callback {  
  private int xpos;  
  private int yPos;  
 
  private int xvel;  
  private int yvel;  
 
  private int width;  
  private int height;  
 
  private int Circleradius;  
  Private Paint Circlepaint;  
 
  Updatethread updatethread;  
}  

In the Movementview constructor, we set the size of the ball and the initial coordinates in the x,y direction, as follows:

Java code

Public Movementview {   
  super (context);   
  Getholder (). Addcallback (this);   
   
  Circleradius = ten;   
  Circlepaint = new Paint ();   
  Circlepaint.setcolor (Color.Blue);   
   
  Xvel = 2;   
  Yvel = 2;   
}   

And then we'll look at how the OnDraw method is written, where we'll paint the ball, and each time we'll set the canvas canvas background color to white to overwrite the previous frame with the following code:

Java code

protected void OnDraw (Canvas Canvas) {  
 
    canvas.drawcolor (color.white);  
 
    Canvas.drawcircle (xpos, YPos, Circleradius, circlepaint);  
  

Let's look at how updatephysics this method is written. This method has two functions: one is to deal with the movement of the ball, the second is to update the real time position of the ball, because the small ball in the screen constantly moving, so when the ball reached such as screen painting area of the top, to be bounced back, so the code is as follows:

Java code

public void Updatephysics () {  
 
//update the current x,y coordinates  
    xpos + = Xvel;  
    YPos + = Yvel;  
 
    if (Ypos-circleradius < 0 | | YPos + Circleradius > Height) {if  
 
        
      (Ypos-circleradius < 0) {  
 
        //If the ball reaches the canvas area The top of the field, bounce back  
 
        yPos = Circleradius;  
      } else{  
 
        //If the ball reaches the lower boundary of the canvas, it bounces back to  
 
        yPos = Height-circleradius;  
      }  
 
      Set the Y coordinate to the opposite direction  
      Yvel *=-1;  
    }  
    if (Xpos-circleradius < 0 | | xpos + Circleradius > width) {if  
 
        
      (Xpos-circleradius < 0) {  
 
        //If the ball arrives left Edge  
 
        xpos = Circleradius  
      } else {  
 
        //If the ball reaches the right edge  
 
        xpos = Width-circleradius;  
      }  
 
      Reset X-axis coordinates  
      xvel *=-1;  
    }  
  }  

Finally, let's look at the code for Surfacecreated this method, which is mainly to get the height and width of the available Surfaceview area, and then set the starting coordinates of the ball (set it in the center of the screen), and started the Updatethread thread, the code is as follows:

Java code

public void surfacecreated (Surfaceholder holder) {  
 
    Rect surfaceframe = Holder.getsurfaceframe ();  
    width = Surfaceframe.width ();  
    Height = surfaceframe.height ();  
 
    Xpos = WIDTH/2;  
    YPos = Circleradius;  
 
    Updatethread = new Updatethread (this);  
    Updatethread.setrunning (true);  
    Updatethread.start ();  
  }  

In addition, we are going to make up the Surfacechanged method, which means that when the interface is changed in size, it is not used in our application, so we leave it to the Null method implementation:

Java code

public void surfacechanged (surfaceholder holder, int format, int width, int height)  
  {  
 
  }  

The main implementation of the Surfacedestroyed method is when the interface is destroyed, and here we stop the task the current thread is working on, where the thread join method is used:

Java code

public void surfacedestroyed (Surfaceholder holder) {  
 
    Boolean retry = true;  
 
    Updatethread.setrunning (false);  
    while (retry) {  
      try {  
        updatethread.join ();  
        Retry = false;  
      } catch (Interruptedexception e) {  
 
      }  
    }  
  }  

In summary, the complete Movementview code is as follows:

Java code

Package example.movement;  
Import Android.content.Context;  
Import Android.graphics.Canvas;  
Import Android.graphics.Color;  
Import Android.graphics.Paint;  
Import Android.graphics.Rect;  
Import Android.view.SurfaceHolder;  
 
Import Android.view.SurfaceView;  
  public class Movementview extends Surfaceview implements Surfaceholder.callback {private int xpos;  
 
  private int yPos;  
  private int xvel;  
 
  private int yvel;  
  private int width;  
 
  private int height;  
  private int Circleradius;  
 
  Private Paint Circlepaint;  
 
  Updatethread Updatethread;  
    Public Movementview {Super (context);  
 
    Getholder (). Addcallback (this);  
    Circleradius = 10;  
    Circlepaint = new Paint ();  
 
    Circlepaint.setcolor (Color.Blue);  
    Xvel = 2;  
  Yvel = 2;  
    } @Override protected void OnDraw (Canvas Canvas) {canvas.drawcolor (color.white);  
  Canvas.drawcircle (xpos, YPos, Circleradius, Circlepaint); }  
 
  public void Updatephysics () {xpos + = Xvel;  
 
    YPos + = Yvel; if (Ypos-circleradius < 0 | | YPos + Circleradius > height) {if (Ypos-circleradius < 0) {y  
      Pos = Circleradius;  
      }else{YPos = Height-circleradius;  
    } yvel *=-1;  
        } if (Xpos-circleradius < 0 | | xpos + Circleradius > width) {if (Xpos-circleradius < 0) {  
      Xpos = Circleradius;  
      else {xpos = Width-circleradius;  
    } xvel *=-1;  
    } public void surfacecreated (Surfaceholder holder) {Rect surfaceframe = Holder.getsurfaceframe ();  
    width = Surfaceframe.width ();  
 
    Height = surfaceframe.height ();  
    Xpos = WIDTH/2;  
 
    YPos = Circleradius;  
    Updatethread = new Updatethread (this);  
    Updatethread.setrunning (TRUE);  
  Updatethread.start (); } public void Surfacechanged (surfaceholder holder, int format, int width, int height) {} public void surfacedestroyed (Surfaceholder holder) {Boolean retry = true;  
    Updatethread.setrunning (FALSE);  
        while (retry) {try {updatethread.join ();  
      Retry = false;  
 The catch (Interruptedexception e) {}}}}

Four, Updatethread thread routines

Below, we begin to write Updatethread thread program. This program is mainly to start a thread to constantly update the position of the current ball. Look at the Declaration and the constructor section first:

Java code

Package licksquid.movement;  
 
Import Android.graphics.Canvas;  
Import Android.view.SurfaceHolder;  
 
public class Updatethread extends Thread {  
  private long time;  
  private final int fps =;  
  Private Boolean Torun = false;  
  Private Movementview Movementview;  
  Private Surfaceholder surfaceholder;  
 
}  
Public Updatethread (Movementview rmovementview) {  
    movementview = Rmovementview;  
    Surfaceholder = Movementview.getholder ();  
  }  
public void Setrunning (Boolean run) {  
    Torun = run;  
  }  

Note that the Setrunning method here sets the tag that the thread should stop, and here's the important method run:

Java code

public void Run () {  
 
    Canvas C;  
    while (Torun) {  
 
      Long cTime = System.currenttimemillis ();  
 
      if ((ctime-time) <= (1000/fps)) {  
 
        c = null;  
        try {  
          c = Surfaceholder.lockcanvas (null);  
 
          Movementview.updatephysics ();  
          Movementview.ondraw (c);  
        } Finally {  
          if (c!= null) {  
            surfaceholder.unlockcanvasandpost (c);  
          }  
      }} Time = CTime;  
    }  
  } 

In the Run method, the following tasks are primarily implemented: first check to see if it is allowed to start the thread (after starting the run, the value is set to True when the Updatethread is started in Movementview. That is, updatethread.setrunning (true), and then check to see if, in the specified time frame, 20 frames per second is set, and if so, call the Surfaceholder Lockcanvas method to lock the current canvas painting area. and call the Movementview Updatephysics method and OnDraw method to draw a small ball and judge the movement of the ball, finally remember to call the Unlockcanvasandpost method in finally.

V. Start and run the program

Finally start and run the program, you can see the following effect, you can see the ball in all directions of the bounce movement.

This is the beginning of an example of Android game development, but it's easy to write Android games.

The above is a simple game development program, follow-up to continue to collate relevant knowledge, thank you for your support to this site!

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.