How to build your own game framework and make a game (1) (with source code)

Source: Internet
Author: User

This tutorial allows us to learn how to use this game framework to develop a simple Air Combat Game! Due to limited materials, they are all online materials. This game can be transformed into a development type game, such as air combat or Plants vs. Zombies, or more, with similar principles. A superior person is always a patient person! A game is often created in Small accidents, and an impatient person is often overwhelmed. I have seen Li huamingHis book introduces the game framework in detail, but it is not comprehensive. Many of the current game books seldom involve the construction of the game framework. I hope you can learn more and give more comments!
First:

In the first tutorial, we will first build our game framework.:
Com. mocn. Framework is a framework package.
Com. mocn. airbottle contains a game package.

 

First, let's take a look at the baseactivity class in the frame package. It is mainly used to set the horizontal and vertical screen, full screen, and screen width and height.

Package COM. mocn. framework; import android. r; import android. app. activity; import android. content. PM. activityinfo; import android. OS. bundle; import android. util. displaymetrics; import android. view. window; import android. view. windowmanager;/*** activity base class. In this class, you only need to set the screen to a portrait screen, full screen, obtain the screen height and width ** @ author administrator **/public class baseactivity extends activity {/*** method executed when the activity is created */@ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setfullscreen (); // set setlandscape () in full screen; // set global in Landscape mode. context = This; // get the context event // get the screen width and height displaymetrics dm = new displaymetrics (); getwindowmanager (). getdefadisplay display (). getmetrics (DM); Global. screenwidth = DM. widthpixels; // obtain the global screen width. screenheight = DM. heightpixels; // obtain the screen height}/*** set to full screen */Public void setfullscreen () {requestwindowfeature (window. feature_no_title); getwindow (). addflags (windowmanager. layoutparams. flag_fullscreen);}/*** method of setting to portrait screen */Public void setportrait () {setrequestedorientation (activityinfo. screen_orientation_portrait);}/*** method for setting it to landscape screen */Public void setlandscape () {setrequestedorientation (activityinfo. screen_orientation_landscape );}}

baseview, mainly used to set thread switches and draw game interfaces

Package COM. mocn. framework; import android. content. context; import android. graphics. canvas; import android. graphics. paint; import android. view. surfaceholder; import android. view. surfaceholder. callback; import android. view. surfaceview;/*** base class surfaceholder on the game interface, enabling and disabling threads, and adding components drawsurfaceview ** @ author administrator **/public abstract class baseview extends surfaceview implements callback, runnable {PRI Vate surfaceholder holder; // reference of surfaceholder private thread currentthread; // reference of thread public int sleeptime = 20; // set the sleep time public baseview (context) {super (context); holder = This. getholder (); // get the holder object holder. addcallback (this); // get the call function object}/*** Method for enabling the thread */Public void startthread () {currentthread = new thread (this ); // obtain the thread object currentthread. start (); // enable the thread}/*** method of disabling the thread */Public Vo Id stopthread () {currentthread = NULL; // sets the thread to null}/*** method executed when the interface changes */@ override public void surfacechanged (surfaceholder holder, int format, int width, int height) {}/ *** method executed when the interface is created */@ override public void surfacecreated (surfaceholder holder) {startthread (); // enable the game thread}/*** method of executing the game when the game is destroyed */@ override public void surfacedestroyed (surfaceholder holder) {stopthread (); // close the game thread}/*** draw the interface Method ** @ Param canvas * @ Param paint */Public void drawsurfaceview (canvas, paint) {layermanager. drawlayermanager (canvas, paint); // draw component}/*** thread control method */@ override public void run () {canvas; paint paint = new paint (); While (currentthread! = NULL) {canvas = holder. lockcanvas (); drawsurfaceview (canvas, paint); holder. unlockcanvasandpost (canvas); try {thread. sleep (sleeptime);} catch (interruptedexception e) {e. printstacktrace ();}}}}

Global class, used to set some constants

 
Package COM. mocn. framework; import android. content. context;/*** get the screen width and height. The context object ** @ author administrator **/public class global {public Static Context context; // obtain the Context Reference public static int screenwidth; // The Screen width public static int screenheight; // The screen height}

Layer class, so the base class of the component is drawn, including the coordinates, width and height of the component, and the method of drawing.

Package COM. mocn. framework; import android. graphics. bitmap; import android. graphics. canvas; import android. graphics. paint; import android. graphics. rect;/*** layer class, the parent class of the component, add the component, set the component location, and draw your own, is the base class of all characters and backgrounds ** @ author administrator **/public abstract class layer {public float X; // The X coordinate of the layer public float y; // layer y coordinate public int W; // Layer Width public int h; // Layer Height public rect SRC, DST; // reference rect class public Bitmap bitmap; // reference the bitmap class protected layer (Bitmap bitmap, int W, int H, Boolean autoadd) {This. bitmap = bitmap; this. W = W; this. H = H; src = new rect (); DST = new rect (); If (autoadd) {layermanager. addlayer (this ); // Add this component to the layermanager class}/*** method for setting the component Position ** @ Param x * @ Param y */Public void setposition (float X, float y) {This. X = x; this. y = y;}/*** draw your own abstract interface ** @ Param canvas * @ Param paint */public abstract void drawself (canvas, paint );}

The backgroundlayer class is mainly used for background rendering and can be used for static plotting.

 
Package COM. mocn. framework; import android. graphics. bitmap; import android. graphics. canvas; import android. graphics. paint;/*** game background component. Add the game background component to layermanager and draw the ** @ author administrator **/public class backgroundlayer extends layer {public backgroundlayer (Bitmap bitmap, int W, int h) {super (bitmap, W, H, true) ;}@ override public void drawself (canvas, paint) {SRC. left = 0; SRC. top = 0; SRC. right = W; SRC. bottom = H; DST. left = (INT) x; DST. top = (INT) y; DST. right = DST. left + W; DST. bottom = DST. top + H; canvas. drawbitmap (bitmap, SRC, DST, paint );}}

Sprite class, Sprite class, used to draw dynamic characters

Package COM. mocn. framework; import Java. util. hashtable; import android. graphics. bitmap; import android. graphics. canvas; import android. graphics. paint;/*** the genie component class. Add the genie component, set the action, draw the genie, and add an action sequence, sprite extends class ** @ author administrator **/public class sprite extends layer {public int frameidx; // The subscript of the current frame public int currentframe = 0; // public hashtable of the current frame <string, spriteaction> actions; // action set public spriteaction Curren Taction; // current action public sprite (Bitmap bitmap, int W, int H, Boolean autoadd) {super (bitmap, W, H, autoadd); Actions = new hashtable <string, sprite. spriteaction> (); // use hashtable to save the action set}/*** to set the action method ** @ Param actionname */Public void setaction (string actionname) {currentaction = actions. get (actionname); // obtain the action from the action set}/*** method of drawing the genie */@ override public void drawself (canvas, paint) {If (currentaction! = NULL) {currentframe = currentaction. frames [frameidx]; // get the currently required frame} // capture the required frame Src in the image. left = currentframe * w; // left side width: the width of the current frame multiplied by the previous frame SRC. top = 0; // top height: 0 SRC. right = SRC. left + W; // width of the right side: the width of the left side plus the width of the frame SRC. bottom = H; // The bottom height is the frame height. // draw the frame height on the interface and draw the DST from the center. left = (INT) x-W/2; DST. top = (INT) Y-H/2; DST. right = DST. left + W; DST. bottom = DST. top + H; canvas. drawbitmap (bitmap, SRC, DST, paint); // draw the current frame if (Currentaction! = NULL) {currentaction. nextframe (); // draw the next frame}/*** Method for adding an action set ** @ Param name * @ Param frames * @ Param frametime */Public void addaction (string name, int [] frames, int [] frametime) {spriteaction sp = new spriteaction (); // create the spiteaction object sp. frames = frames; // number of current frames, which is indicated by subscript sp. frametime = frametime; // the time when each frame is switched to actions. put (name, SP); // a set of actions whose names are "name, an action set with a value of SP is put into acitons}/*** Genie's moving method ** @ Param DX * @ Param dy */Public void move (INT dx, int Dy) {This. X + = DX; this. Y + = Dy;} // The spriteaction class spriteaction {public int [] frames; // The frame sequence public int [] frametime of the action; // The time for switching each frame in the frame sequence private long updatetime; // record the last expiration time/*** Method for switching to the next frame */Public void nextframe () {If (system. currenttimemillis ()> updatetime) {frameidx ++; // Add frameidx % = frames to the frame subscript. length; updatetime = system. currenttimemillis () + frametime [frameidx]; // time required to switch the next frame }}}}

layermanager class, Component Management class, used to manage components

Package COM. mocn. framework; import Java. util. vector; import android. graphics. canvas; import android. graphics. paint;/*** component management class, used to store components, draw all components, add a component, delete a component, insert a component *** @ author administrator **/public class layermanager {public static vector <layer> VEC = new vector <layer> (); // The vector object is used to store all components./*** Method for drawing all components ** @ Param canvas * @ Param paint */public static void drawlayermanager (canvas, pain T paint) {for (INT I = 0; I <Vec. size (); I ++) {Vec. elementat (I ). drawself (canvas, paint ); // draw the component that exists in the vector object}/*** Method for adding a component ** @ Param Layer */public static synchronized void addlayer (layer Layer) {Vec. add (layer); // Add this component to the vector object}/*** Method for deleting a component ** @ Param Layer */public static synchronized void deletelayer (layer Layer) {Vec. remove (layer); // Delete this component from the vector object}/*** insert it at the position specified by before Input layer. The original and subsequent objects are postponed in turn. ** @ Param Layer * @ Param before */public static void insert (layer Layer, layer before) {for (INT I = 0; I <Vec. size (); I ++) {// traverse the vector object if (before = Vec. elementat (I) {Vec. insertelementat (layer, I); // insert a layer before the before object. The object is located on top of the before return ;}}}}

the last, utilsl, and tool class, including methods for obtaining images and detecting collision events

Package COM. mocn. framework; import Java. io. ioexception; import Java. io. inputstream; import android. graphics. bitmap; import android. graphics. bitmapfactory;/*** tool class to obtain an image and determine whether the two rectangles overlap, determine whether a vertex is in the rectangle ** @ author administrator **/public class utils {/*** how to obtain an image ** @ Param path * @ return */public static bitmap getbitmap (string path) {try {inputstream is = Global. context. getassets (). open (PATH); Return bitmapfactory. decodestream (is);} catch (ioexception e) {e. printstacktrace ();} return NULL ;} /*** method for determining whether two rectangles are intersecting ** @ Param x * @ Param y * @ Param w * @ Param H * @ Param X2 * @ Param Y2 * @ Param W2 * @ Param H2 * @ return */public static Boolean collisewidth (float X, float y, float W, float H, float X2, float Y2, float W2, float H2) {If (x> X2 + W2 | X2> X + w | Y> Y2 + H2 | Y2> Y + H) {return false;} return true ;} /*** method for determining whether a vertex is in a rectangle ** @ Param x * @ Param y * @ Param w * @ Param H * @ Param PX * @ Param py *@ return */public static Boolean inrect (float X, float y, float W, float H, float PX, float Py) {If (PX> X & PX <X + W & py> Y & py <Y + H) {return true ;}return false ;}}

After the framework is set up, the second part is the game rendering. If you have any questions about the framework, please ask me.
The source code is provided below:

Http://files.cnblogs.com/feifei1010/AirBottle.zip

Also see a lot of excellent post http://www.apkbus.com/blog-15060-40268.html

Do you welcome anyone who loves Android development to join the Group for discussion and progress !!Chengdu group 252743807 Wuhan group 121592153

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.