Android uses Surfaceview to write a simple and interesting game--one of the digital combinations

Source: Internet
Author: User

Recently there is an idea-to do a simple Android game practiced hand, both to achieve simple (after all, there is only one person, the framework of what is not considered), but also to achieve the Android knowledge framework of the review and play to have fun, and finally spent a few weeks to finish. Share the experience with everyone.

I was going to write a column. Look at the next time.

First introduce the main idea of the game and Surfaceview is the game main interface code sharing, the next part of the update it.

After clicking to start the game, the combination of number selection, according to the system default selection of 2 and 8, select the middle of the interface to display the selected combination of numbers, the first number represents the first combination of numbers,
That is, the number that can be divisible in the course of the game, the second number represents the second combined number, that is, the number that cannot be divisible in the course of a game. Start the game after the selection is over.
After the game is ready to play, randomly fall within a certain range of numbers, determine whether the number is divisible by the first combination of numbers and not divisible by the second number, if, click on the number, the score plus the corresponding value, otherwise the fractional minus the corresponding value.
The range of drop numbers increases as the level increases. Falling speed and the speed of the numbers are also accelerating. When the score is less than 0 or missed the correct value is greater than 5 o'clock game ends!

1. Game Main interface Activity

Package Com.gymyang.number.views;import Android.graphics.bitmapfactory;import Android.view.keyevent;import Android.view.view;import Com.gymyang.number.baseactivity;import Com.gymyang.number.r;import Com.gymyang.number.utils.devicetools;import com.gymyang.number.utils.globalfields;/** * Class Name: Numbergameactivity.java * Function: * Main logic activity * Modifications: * * @author Administrator * @DateTime 201 4-11-11 pm 8:09:55 * @version 1.0 */public Class Numbergameactivity extends Baseactivity{private gameview gameview;// Private TextView noticetx; @Overrideprotected void Initview () {LoadResource ();//setcontentview (R.layout.game_view); /gameview = (Gameview) Findviewbyid (r.id.game_view_main);//noticetx = (TextView) Findviewbyid (R.id.game_view_notice) ; gameview = new Gameview (this,this); Setcontentview (Gameview);} /** * Function: * Load Resources * @author Administrator * @DateTime 2014-11-12 a.m. 9:22:40 */private void LoadResource () {Globalfi ELDs. Device_width = devicetools.getdeviceiNFO (this) [0]; Globalfields.device_height = Devicetools.getdeviceinfo (this) [1]; Globalfields.bg_gray = Bitmapfactory.decoderesource (Getresources (), R.drawable.number_bg_gray); Globalfields.bg_green = Bitmapfactory.decoderesource (Getresources (), r.drawable.number_bg_green); Globalfields.bg_white = Bitmapfactory.decoderesource (Getresources (), r.drawable.number_bg_white); globalfields.bg_red = Bitmapfactory.decoderesource (Getresources (), r.drawable.number_bg_red); globalfields.number_1 = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.NUM1); globalfields.number_2 = Bitmapfactory.decoderesource (Getresources (), r.drawable.num2); Globalfields.number_3 = Bitmapfactory.decoderesource (Getresources (), r.drawable.num3); GLOBALFIELDS.PAUSE_BG = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.PAUSE_BG); GLOBALFIELDS.PAUSE_BTNBG = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.PAUSE_BUTTON_BG); Globalfields.scalewidth = globalfields.device_width/(float) GlobalFields.BG_GRAY.getWidth(); Globalfields.scaleheight = globalfields.device_height/(float) GlobalFields.BG_GRAY.getHeight (); Globalfields.bg_gray = Devicetools.resizebitmap (Globalfields.bg_gray); GLOBALFIELDS.PAUSE_BG = Devicetools.resizebitmap (GLOBALFIELDS.PAUSE_BG,GLOBALFIELDS.DEVICE_WIDTH/5, GLOBALFIELDS.DEVICE_HEIGHT/4); GLOBALFIELDS.PAUSE_BTNBG = Devicetools.resizebitmap (GLOBALFIELDS.PAUSE_BTNBG,GLOBALFIELDS.DEVICE_WIDTH/5 *2-10, GlobalFields.PAUSE_BG.getHeight ()/4);} @Overrideprotected void Setlistener () {} @Overrideprotected void Logicwork () {} @Overridepublic void OnClick (View v) {}@ Overridepublic boolean onKeyDown (int keycode, keyevent event) {if (keycode = = Keyevent.keycode_back) {if ( Gameview.current_state = = gameview.prepare_finish) {gameview.current_state = Gameview.game_pause;} Mywindowmanager.showerrordialog (Getbasecontext (), "Game paused!"); return true;} Return Super.onkeydown (KeyCode, event);}}


2. The main game interface Surfaceview specifically implemented

Package Com.gymyang.number.views;import Java.util.arraylist;import Java.util.linkedlist;import java.util.List; Import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.rect;import Android.graphics.paint.align;import Android.view.motionevent;import Android.view.surfaceholder;import Android.view.surfaceview;import Com.gymyang.number.sprite.basesprite;import Com.gymyang.number.sprite.leveltext;import Com.gymyang.number.sprite.numberblock;import Com.gymyang.number.sprite.numberblockmanager;import Com.gymyang.number.sprite.scoretext;import Com.gymyang.number.sprite.statebar;import Com.gymyang.number.sprite.touchable;import Com.gymyang.number.utils.devicetools;import  Com.gymyang.number.utils.globalfields;import com.gymyang.number.utils.levelmanager;/** * Class Name:GameView.java * Function: * Grand Butler * Modifications: * * @author Administrator * @DateTime 2014-11-11 pm 10:36:53 * @version 1.0 */public Class Gameview extends Surfaceview implements Surfaceholder.callback, runnable{/** gameview Singleton existence */private STA Tic Gameview gameview;public static Gameview getinstance () {return gameview;} Private numbergameactivity activity;private surfaceholder surfaceholder;private Paint paint;//Game Status Private Boolean  Flag = true;private Canvas canvas;/** lattice width */public int block_width;/** grid height */public int block_height;/** ready to start */private Final int prepare_start = 200;/** ready to complete */public final int prepare_finish = 201;/** Game over */private final int game_over = 20 2;/** pause */public Final int game_pause = 203;/** current progress status */public int current_state = prepare_start;/** * Lattice Object collection */private Linkedlist<basesprite> blocksprites;/** dead elf */private list<basesprite> deadSprites;/** Digital lattice Management */ Private Numberblockmanager numberblockmanager;private Statebar statebar;private Float dp = 1;public GameView (Context Context,numbergameactivity activity) {super (context); this.activity = Activity;paint = new Paint (); Getholder (). Addcallback (this), Surfaceholder = Getholder (); gameview = this; GLOBALFIELDS.DP = devicetools.getscreendensity (context);DP = GLOBALFIELDS.DP;} Public Gameview (Context context) {Super (context);p aint = new paint (), Getholder (). Addcallback (this); Surfaceholder = Getholder (); gameview = this; GLOBALFIELDS.DP = devicetools.getscreendensity (context);DP = GLOBALFIELDS.DP;} @Overridepublic void surfacecreated (Surfaceholder holder) {paint.setcolor (color.white);p aint.settextsize (30*DP); Globalfields.score = 0; Levelmanager.initchildren (); Block_width = Globalfields.device_width/globalfields.current_columns; Block_height = Globalfields.device_height/globalfields.current_lines;blocksprites = new LinkedList<BaseSprite > ();d eadsprites = new arraylist<basesprite> (); numberblockmanager = new Numberblockmanager (); statebar = new Statebar (); Resetbitmap (); new Thread (this) {}.start ();} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {} @OverridepublIC void surfacedestroyed (Surfaceholder holder) {}/** * Function: * Stretch Grid background resource * @author Administrator * @DateTime 2014-11 -12 pm 2:57:30 */private void Resetbitmap () {globalfields.bg_green = Devicetools.resizebitmap (Globalfields.bg_green, Block_width,block_height); globalfields.bg_red = Devicetools.resizebitmap (globalfields.bg_red,block_width,block_height); Globalfields.bg_white = Devicetools.resizebitmap (globalfields.bg_white,block_width,block_height);} @Overridepublic void Run () {while (flag) {synchronized (Surfaceholder) {try {canvas = Surfaceholder.lockcanvas (); Canvas.drawbitmap (globalfields.bg_gray, 0, 0, paint); Updatestate (); OnDraw (canvas);} catch (Exception e) {//Todo:handle Exception} finally {if (canvas! = null) {surfaceholder.unlockcanvasandpost (canvas);}}} try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();}}} /** * Function: * Update status * @author Administrator * @DateTime 2014-11-12 pm 3:37:47 */private void Updatestate () {Deadsprit Es.clear (); for (Basesprite SPRIte:blocksprites) {if (!sprite.isalive ()) {Deadsprites.add (sprite);}} Blocksprites.removeall (deadsprites);} /** * Function: * * @author Administrator * @DateTime 2014-11-11 pm 11:31:45 * @param canvas2 */private void OnDraw (C Anvas canvas) {if (current_state = = Prepare_start) {drawdevidelines (canvas);} else if (current_state = = prepare_finish) {drawdevidelines (canvas);//Draw a digital lattice numberblockmanager.drawself (canvas, Paint ); for (Basesprite sprite:blocksprites) {sprite.drawself (canvas, paint);} Draw the status bar Drawstatebar (canvas); if (globalfields.missed < 0 | | Globalfields.score < 0) {current_state = Game_over;}} else if (current_state = = Game_pause) {//TODO Games pause drawpause (canvas);//canvas.drawtext ("Game paused", Globalfields.device_ WIDTH/2 -20, GLOBALFIELDS.DEVICE_HEIGHT/2 -20, paint);} else if (current_state = = Game_over) {//TODO game end drawgameover (canvas);}} private int overheight = 0;/** * Function: * Game Over * @author Administrator * @DateTime 2014-11-16 pm 2:36:52 */private V OID Drawgameover (Canvas canvas) {int precolor = Paint.getcolor (); Float textSize = Paint.gettextsize (); Align Pretextstyle = paint.gettextalign ();p aint.setcolor (color.red);p aint.settextsize (32*DP);p aint.settextalign ( Paint.Align.CENTER); Canvas.drawtext ("Game over!", Globalfields.device_width/2,overheight, Paint);p Aint.setcolor ( Precolor);p aint.settextsize (textSize);p aint.settextalign (Pretextstyle); if (Overheight < Globalfields.device_ HEIGHT/2) {overheight + = 50;} else if (overheight >= globalfields.device_height/2 && overheight < GLOBALFIELDS.DEVICE_HEIGHT/2 +) {ov Erheight + = 5;} else if (overheight >= GLOBALFIELDS.DEVICE_HEIGHT/2 + && Overheight < globalfields.device_height) {OverH eight + = 50;} else if (overheight >= globalfields.device_height) {//TODO back to main interface flag = False;activity.finish ();}} private int pauseheight = 0;private int pausewidth = (globalfields.device_width-globalfields.pause_bg.getwidth ())/2;PR ivate int pausetextheight = Pauseheight + (GlobalFields.PAUSE_BG.getHeiGht ()-GlobalFields.PAUSE_BTNBG.getHeight ())/** exit game Touch Area */private rect exittoucharea;/** continue game Touch area */private Rect Goon toucharea;/** * Function: * Draw Pause Status * @author Administrator * @DateTime 2014-11-16 pm 1:33:12 */private void Drawpause (C Anvas canvas) {if (Exittoucharea! = null) {Exittoucharea = null;} if (Goontoucharea! = null) {Goontoucharea = null;} Exittoucharea = new Rect (Pausewidth + 5, (Pauseheight +pausetextheight-5), (Pausewidth + 5) + GlobalFields.PAUSE_BTNBG.ge Twidth (), (pauseheight +pausetextheight-5) + GlobalFields.PAUSE_BTNBG.getHeight ()); Goontoucharea = new Rect (( Pausewidth + GlobalFields.PAUSE_BG.getWidth ()/2 + 5), (Pauseheight +pausetextheight-5), (Pausewidth + Globalfields.paus E_bg.getwidth ()/2 + 5) + GlobalFields.PAUSE_BTNBG.getWidth (), (pauseheight +pausetextheight-5) + GLOBALFIELDS.PAUSE_BT Nbg.getheight ()); int precolor = Paint.getcolor (); Float textSize = Paint.gettextsize (); Align Pretextstyle = Paint.gettextalign (); Canvas.drawbitmap (GLOBALFIELDS.PAUSE_BG,Pausewidth, pauseheight, paint); Canvas.drawbitmap (GLOBALFIELDS.PAUSE_BTNBG, Pausewidth + 5, Pauseheight + pauseTextHeight-5, paint); Canvas.drawbitmap (GLOBALFIELDS.PAUSE_BTNBG, Pausewidth + GlobalFields.PAUSE_BG.getWidth ( )/2 + 5,pauseheight +pausetextheight-5, paint);p Aint.setcolor (color.blue);p aint.settextsize (28*DP); Paint.settextalign (Paint.Align.CENTER); Canvas.drawtext ("Game paused", Pausewidth + GlobalFields.PAUSE_BG.getWidth ()/2, Pauseheight + GlobalFields.PAUSE_BG.getHeight ()/2, paint);p aint.settextsize (18*DP); Canvas.drawtext ("Back to Menu", Pausewidth + 5 + GlobalFields.PAUSE_BTNBG.getWidth ()/2, pauseheight +pausetextheight + globalfields.pause_ Btnbg.getheight ()/2, paint); Canvas.drawtext ("Continue game", Pausewidth + GlobalFields.PAUSE_BTNBG.getWidth ()/2*3 + 5, Pauseheight +pausetextheight + GlobalFields.PAUSE_BTNBG.getHeight ()/2, paint);p Aint.setcolor (Precolor); Paint.settextsize (textSize);p aint.settextalign (Pretextstyle); if (Pauseheight < GLOBALFIELDS.DEVICE_HEIGHT/2- Globalfields.pausE_bg.getheight ()/2) {pauseheight + = 60;}} /** * Function: * Draw status bar * @author Administrator * @DateTime 2014-11-12 pm 7:50:30 */private void Drawstatebar (Canvas CA Nvas) {statebar.drawself (canvas, paint);} Private Boolean isaddnumber = false;/** * Function: * Request to add grid * @author Administrator * @DateTime 2014-11-12 3:22:09  */public void Apply2addnumber () {synchronized (surfaceholder) {int raceway = 0, number = 0;raceway = (int) (Math.random () * Globalfields.current_columns); number = (int) (Math.random () * globalfields.max_number + 1); Isaddnumber = false;//TODO Add Digital Lattice if (blocksprites.size () > 0) {//basesprite sprite = Blocksprites.getlast (); for (int i=blocksprites.size ()-1; I >0; i--) {Basesprite sprite = Blocksprites.get (i); if (Sprite.locationx = = Raceway) {if (Sprite.locationy > Block_ HEIGHT) {Blocksprites.add (New Numberblock (Raceway, number));} Isaddnumber = True;break;}} if (!isaddnumber) {Blocksprites.add (New Numberblock (Raceway, number)); isaddnumber = True;}} Else{blocksprites.add (NEW Numberblock (Raceway, number)); isaddnumber = True;}}} /** * Function: * Request Add points display * @author Administrator * @DateTime 2014-11-12 pm 3:22:09 */public void Apply2addscoretext (in T x,int y,string msg,int flag) {synchronized (Surfaceholder) {//TODO request Add add-on display Blocksprites.add (new Scoretext (x, Y, MSG, Fla g));}} /** * Function: * level rise * @author Administrator * @DateTime 2014-11-13 pm 12:07:36 */public void Requestaddlevel () {synch Ronized (Surfaceholder) {//TODO request Add-on display Blocksprites.add (New Leveltext ());}} /** * Function: * Request Redraw lattice * @author Administrator * @DateTime 2014-11-13 pm 12:07:36 */public void Requestredraw () {BLO Ck_width = Globalfields.device_width/globalfields.current_columns; Block_height = Globalfields.device_height/globalfields.current_lines;draw_devide_line = 1;DRAW_DEVIDE_COLUMN = 1;D Raw_time = 1;i=1;j=1;k=1; space=6; Globalfields.bg_white = Devicetools.resizebitmap (Globalfields.bg_white, Block_width, BLOCK_HEIGHT); Globalfields.bg_green = Devicetools.resizebitmap (GlobalfielDs.bg_green, Block_width, block_height); globalfields.bg_red = Devicetools.resizebitmap (globalfields.bg_red, Block_width, block_height); Current_state = Prepare_start;} /********************************** Pass-through touch event **************************************/@Overridepublic Boolean Ontouchevent (Motionevent event) {if (current_state = = game_pause) {int x = (int) event.getx (); int y = (int) event.gety (); if ( Exittoucharea.contains (x, y)) {current_state = Game_over;pauseheight = 0;return true;} if (Goontoucharea.contains (x, y)) {current_state = Prepare_finish;pauseheight = 0;return true;}} Else{for (Basesprite sprite:blocksprites) {if (sprite instanceof touchable) {if (((touchable) sprite). OnTouch (Event)) {R Eturn true;}}}} return false;} /******************************** Draw split line ****************************************///column split line cursor private int DRAW_DEVIDE_ line = 1;//row split line cursor private int draw_devide_column = 1;//countdown cursor private int draw_time = 1;//column traverse max int i=1,j=1,k=1,space=6; /** * Function: * Draw Split Line * @author ADMInistrator * @DateTime 2014-11-12 a.m. 9:31:11 */private void Drawdevidelines (canvas canvas) {drawnotice ();p Aint.setstyle ( Paint.Style.STROKE);p Aint.setcolor (Color.ltgray);//Draw column split line for (int x=1;x<=i;x++) {canvas.drawline (Block_width * x , 0, Block_width * x, Globalfields.device_height, paint);} if (draw_devide_line% SPACE = = 0) {i++;} if (i >= globalfields.current_columns) {//regression i,j avoid overflow i = globalfields.current_columns-1;} else{draw_devide_line++;} Draw line Split line if (Draw_devide_line >= (globalfields.current_columns-1) *space) {for (int y=1;y<=j;y++) { Canvas.drawline (0, Block_height * y, globalfields.device_width, block_height * y, paint);} if (draw_devide_column% SPACE = = 0) {j + +;} if (J >= globalfields.current_lines) {//regression i,j Avoid overflow j = globalfields.current_lines-1;} else{draw_devide_column++;}} Prepare the countdown if (Draw_devide_column >= (globalfields.current_lines-1) *space) {int left = GLOBALFIELDS.DEVICE_WIDTH/2-Glo BalFields.NUMBER_1.getWidth ()/2; int top = GLOBALFIELDS.DEVICE_HEIGHT/2-GloBalFields.NUMBER_1.getHeight ()/2; if (k = = 1) {Canvas.drawbitmap (globalfields.number_3, left, top, paint);} else if (k = = 2) {Canvas.drawbitmap (globalfields.number_2, left, top, paint);} else if (k = = 3) {Canvas.drawbitmap (globalfields.number_1, left, top, paint); Current_state = Prepare_finish;} if (draw_time% SPACE = = 0) {k++;} if (K < 3) {draw_time++;}}} private int noticeheight = Globalfields.device_height/4*3;private void Drawnotice () {int precolor = Paint.getcolor (); float textSize = Paint.gettextsize (); Align Pretextstyle = paint.gettextalign ();p aint.settextalign (Paint.Align.CENTER);p aint.settextsize (16*DP); Paint.setcolor (Color.rgb (8, 103, 23°c)) Canvas.drawtext ("Click can be combined number one:" "+globalfields.sensetive_number+" "", Globalfields.device_width/2,noticeheight, paint); Canvas.drawtext ("but cannot be combined number two:" "+globalfields.sensetive_number2+" "Number", GLOBALFIELDS.DEVICE_WIDTH/2, noticeheight+30, paint); Canvas.drawtext ("The higher the rank! The faster it gets! The bigger the number! ", GLOBALFIELDS.DEVICE_WIDTH/2, noticeheight+60, paint); Canvas.drawtext (" Are You Ready? " ", GLOBALFIELDS.DEVICE_WIDTH/2, noticeheight+90, paint); noticeheight-= 20;paint.setcolor (Precolor); Paint.settextsize (textSize);p aint.settextalign (Pretextstyle);}}


Android uses Surfaceview to write a simple and interesting game--one of the digital combinations

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.