Android 2d游戏开发之贪吃蛇基于surfaceview
程序员文章站
2022-03-07 07:53:06
前两个游戏是基于view游戏框架的,view游戏框架只适合做静止的,异步触发的游戏,如果做一直在动的游戏,view的效率就不高了,我们需要一种同步触发的游戏框架,也就是surfaceview游戏框架,...
前两个游戏是基于view游戏框架的,view游戏框架只适合做静止的,异步触发的游戏,如果做一直在动的游戏,view的效率就不高了,我们需要一种同步触发的游戏框架,也就是surfaceview游戏框架,你可能会问,什么乱七八糟的,啥叫同步?啥叫异步?。。。我就不告诉你。。。我们先看一下这个同步框架,看看骚年你能不能自己领悟。
gameview.java(继承自surfaceview)
package com.next.eatsnake; import android.content.context; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import android.view.motionevent; import android.view.surfaceholder; import android.view.surfaceview; import android.view.view; import android.view.view.ontouchlistener; import java.util.random; /** * created by next on 2016/3/24 0024. */ public class gameview extends surfaceview implements surfaceholder.callback,ontouchlistener,runnable { enum gamestate{ menu, playing, over; } gamestate gamestate;//游戏状态 thread thread;//游戏线程 boolean flag;//游戏循环控制标志 canvas canvas;//画布 paint paint;//画笔 surfaceholder holder;//surfaceview控制句柄 random random;//随机数 nextevent nextevent;//游戏输入事件 int scrw,scrh;//屏幕的宽和高 public gameview(context context) { super(context); gamestate = gamestate.menu; flag = true; paint = new paint(); paint.setantialias(true);//笔迹平滑 thread = new thread(this); random = new random(); nextevent = new nextevent(); holder = this.getholder(); holder.addcallback(this); this.setontouchlistener(this); setkeepscreenon(true); scrw = ((mainactivity)context).getwindowmanager().getdefaultdisplay().getwidth(); scrh = ((mainactivity)context).getwindowmanager().getdefaultdisplay().getheight(); } @override public boolean ontouch(view v, motionevent event) { if (event.getaction() == motionevent.action_down) { nextevent.setdownx((int) event.getx()); nextevent.setdowny((int) event.gety()); }else if (event.getaction() == motionevent.action_up) { nextevent.setupx((int) event.getx()); nextevent.setupy((int) event.gety()); } return true; } private void mlogic(){ switch (gamestate){ case menu: menulogic(); break; case playing: playinglogic(); break; case over: overlogic(); break; } nextevent.init();//每次逻辑循环后,清空事件 } private void menulogic(){ if(nextevent.getupx() > 0){ gamestate = gamestate.playing; } } private void playinglogic(){ if(nextevent.getdir() == nextevent.down){ gamestate = gamestate.over; } } private void overlogic(){ if(nextevent.getdir() == nextevent.right){ gamestate = gamestate.menu; } } private void mdraw(){ try { canvas = holder.lockcanvas(); canvas.drawcolor(color.white); switch (gamestate){ case menu: menudraw(canvas); break; case playing: playingdraw(canvas); break; case over: overdraw(canvas); break; } }catch (exception e){ e.printstacktrace(); }finally { holder.unlockcanvasandpost(canvas); } } private void menudraw(canvas canvas){ paint.setcolor(color.red); paint.settextsize(50); canvas.drawtext("i am in menu.touch me to next scence",100,100,paint); } private void playingdraw(canvas canvas){ paint.setcolor(color.red); paint.settextsize(50); canvas.drawtext("i am in playing,slide down to next scence ",100,100,paint); } private void overdraw(canvas canvas){ paint.setcolor(color.red); paint.settextsize(50); canvas.drawtext("i am in over,slide right to next scence",100,100,paint); } //这里就是同步触发机制了 //每一个时钟周期,执行一次逻辑方法和绘图方法 @override public void run() { while(flag){ mlogic(); mdraw(); try { thread.sleep(500); }catch (exception e){ e.printstacktrace(); } } } //surfaceview创建时调用 @override public void surfacecreated(surfaceholder holder) { thread.start(); } //surfaceview发生改变时调用 @override public void surfacechanged(surfaceholder holder, int format, int width, int height) { } //surfaceview销毁时调用 @override public void surfacedestroyed(surfaceholder holder) { flag = false; } }
这只是一个游戏框架,还没有往里写任何内容,但根据我的经验(虽然我也没有很多经验),这里已经包括了所有游戏(这里特指小游戏-_-)的主体框架代码,有了这个框架,我们就只需要写游戏的逻辑和绘图方法了,不用纠结怎么搭建游戏框架了。
这里我还加了一个nextevent的方法,在里面我封装了上个游戏用到的滑动手势,在这个挨踢圈里,人们最常说的一句话就是:不要重复造*。当我们看到写了很多重复代码时,就是我们需要精简的时候了。
上代码:
nextevent.java
package com.next.eatsnake; /** * created by next on 2016/3/24 0024. */ public class nextevent { public static final int left = 1; public static final int right = 2; public static final int up = 3; public static final int down = 4; public static final int quiet = -1;//没有滑动 private int dir; private int downx,downy,upx,upy; public nextevent() { init(); } public void init(){ this.dir = quiet; this.downx = -1; this.downy = -1; this.upx = -1; this.upy = -1; } public int getdir(){ float offsetx,offsety; offsetx = upx - downx; offsety = upy - downy; if (math.abs(offsetx) > math.abs(offsety)) { if (offsetx > 5 ) { dir = right; }else if (offsetx < -5) { dir = left; } }else { if (offsety > 5) { dir = down; }else if (offsety < -5) { dir = up; } } return dir; } public int getdownx() { return downx; } public void setdownx(int downx) { this.downx = downx; } public int getdowny() { return downy; } public void setdowny(int downy) { this.downy = downy; } public int getupx() { return upx; } public void setupx(int upx) { this.upx = upx; } public int getupy() { return upy; } public void setupy(int upy) { this.upy = upy; } }
这个nextevent是用来存储用户输入事件的,我们只是存储,而没有直接触发游戏逻辑。那么什么时候用到读取这个nextevent呢?如果你仔细看了第一段代码,应该已经知道了——在每一个时钟周期的逻辑方法里判断nextevent,并由此改变游戏逻辑。这种就是同步机制,而用户输入事件游戏逻辑就随之改变的就是异步机制。
下面我们用这个框架做一个贪吃蛇游戏,效果图如下:
mainactivity.java
package com.next.eatsnake; import android.app.activity; import android.os.bundle; import android.view.window; import android.view.windowmanager; public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen,windowmanager.layoutparams.flag_fullscreen); setcontentview(new gameview(this)); } }
gameview.java
package com.next.eatsnake; import android.content.context; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import android.view.motionevent; import android.view.surfaceholder; import android.view.surfaceview; import android.view.view; import android.view.view.ontouchlistener; import java.util.arraylist; import java.util.random; /** * created by administrator on 2016/3/24 0024. */ public class gameview extends surfaceview implements surfaceholder.callback,ontouchlistener,runnable { enum gamestate{ menu, playing, over; } gamestate gamestate;//游戏状态 thread thread;//游戏线程 boolean flag;//游戏循环控制标志 canvas canvas;//画布 paint paint;//画笔 surfaceholder holder;//surfaceview控制句柄 public static random random;//随机数 nextevent nextevent;//游戏输入事件 int scrw,scrh;//屏幕的宽和高 final int max_x = 15; int max_y;//竖向tile数量根据max_x动态计算,保证tile是正方形 public static tile[][] tiles; snake snake; public static boolean iseatfood; public gameview(context context) { super(context); gamestate = gamestate.menu; flag = true; paint = new paint(); paint.setantialias(true);//笔迹平滑 paint.settextalign(paint.align.center);//文字中间对齐 thread = new thread(this); random = new random(); nextevent = new nextevent(); holder = this.getholder(); holder.addcallback(this); this.setontouchlistener(this); setkeepscreenon(true); scrw = ((mainactivity)context).getwindowmanager().getdefaultdisplay().getwidth(); scrh = ((mainactivity)context).getwindowmanager().getdefaultdisplay().getheight(); tile.width = scrw/max_x; max_y = scrh/tile.width; tiles = new tile[max_x][max_y]; iseatfood = false; } private void newgame(){ for (int x = 0;x < max_x;x++){ for (int y = 0;y < max_y;y++){ if (x == 0||y == 0||x == max_x-1||y == max_y-1){ tiles[x][y] = new tile(x,y,tile.type_wall); }else { tiles[x][y] = new tile(x,y,tile.type_null); } } } snake = new snake(tiles[4][4],tiles[5][4],tiles[6][4], nextevent.down); addfood(); addfood(); addfood(); } public void addfood(){ arraylist<tile> nulllist = new arraylist<tile>(); for (int x = 0;x < max_x;x++){ for (int y = 0;y < max_y;y++){ if (tiles[x][y].gettype() == tile.type_null){ nulllist.add(tiles[x][y]); } } } if (nulllist.size()!=0){ nulllist.get(random.nextint(nulllist.size())).settype(tile.type_food); } } @override public boolean ontouch(view v, motionevent event) { if (event.getaction() == motionevent.action_down) { nextevent.setdownx((int) event.getx()); nextevent.setdowny((int) event.gety()); }else if (event.getaction() == motionevent.action_up) { nextevent.setupx((int) event.getx()); nextevent.setupy((int) event.gety()); } return true; } private void mlogic(){ switch (gamestate){ case menu: menulogic(); break; case playing: playinglogic(); break; case over: overlogic(); break; } nextevent.init();//每次逻辑循环后,清空事件 } private void menulogic(){ if(nextevent.getupx() > 0){ gamestate = gamestate.playing; newgame(); } } private void playinglogic(){ if (nextevent.getdir()!=nextevent.quiet){ snake.setdir(nextevent.getdir()); } snake.move(); if (iseatfood){ addfood(); iseatfood = false; } if(!snake.isalive()){ gamestate = gamestate.over; } } private void overlogic(){ if(nextevent.getupx() > 0){ gamestate = gamestate.playing; newgame(); } } private void mdraw(){ try { canvas = holder.lockcanvas(); canvas.drawcolor(color.white); switch (gamestate){ case menu: menudraw(canvas); break; case playing: playingdraw(canvas); break; case over: overdraw(canvas); break; } }catch (exception e){ e.printstacktrace(); }finally { holder.unlockcanvasandpost(canvas); } } private void menudraw(canvas canvas){ paint.setcolor(color.black); paint.settextsize(50); canvas.drawtext("eat snake,touch me and start",scrw/2,scrh/2,paint); } private void playingdraw(canvas canvas){ for (int x = 0;x < max_x;x++){ for (int y = 0;y < max_y;y++){ tiles[x][y].draw(canvas,paint); } } } private void overdraw(canvas canvas){ paint.setcolor(color.black); paint.settextsize(50); canvas.drawtext("your score is:"+snake.getlength(),scrw/2,scrh/4,paint); canvas.drawtext("touch me and try again",scrw/2,scrh/2,paint); } @override public void run() { while(flag){ mlogic(); mdraw(); try { thread.sleep(500); }catch (exception e){ e.printstacktrace(); } } } @override public void surfacecreated(surfaceholder holder) { thread.start(); } @override public void surfacechanged(surfaceholder holder, int format, int width, int height) { } @override public void surfacedestroyed(surfaceholder holder) { flag = false; } }
tile.java
package com.next.eatsnake; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; /** * created by next on 2016/3/26 0026. */ public class tile { public static final int type_null = 0;//空 public static final int type_wall = 1;//墙 public static final int type_head = 2;//蛇头 public static final int type_body = 3;//蛇身 public static final int type_tail = 4;//蛇尾 public static final int type_food = 5;//食物 private int x,y; private int type; public static int width; public tile(int x, int y, int type) { this.x = x; this.y = y; this.type = type; } public void draw(canvas canvas,paint paint){ switch (type){ case type_null: break; case type_wall: paint.setcolor(color.black); canvas.drawcircle(x*width+width/2,y*width+width/2,width/2,paint); break; case type_head: paint.setcolor(color.magenta); canvas.drawcircle(x*width+width/2,y*width+width/2,width/2,paint); paint.setcolor(color.white); canvas.drawcircle(x*width+width/2,y*width+width/2,width/8,paint); break; case type_body: paint.setcolor(color.magenta); canvas.drawcircle(x*width+width/2,y*width+width/2,width/2,paint); break; case type_tail: paint.setcolor(color.magenta); paint.setstrokewidth(10); canvas.drawline(x * width, y * width + width / 2, x * width + width / 2, y * width, paint); canvas.drawline(x*width+ width / 2,y*width,x*width+width,y*width+width/2,paint); canvas.drawline(x*width+width,y*width+width/2,x*width+width/2,y*width+width,paint); canvas.drawline(x*width+width/2,y*width+width,x*width,y*width+ width / 2,paint); break; case type_food: switch (gameview.random.nextint(3)){ case 0: paint.setcolor(color.yellow); break; case 1: paint.setcolor(color.green); break; case 2: paint.setcolor(color.cyan); break; } canvas.drawcircle(x*width+width/2,y*width+width/2,width/2,paint); break; } } public int getx() { return x; } public void setx(int x) { this.x = x; } public int gety() { return y; } public void sety(int y) { this.y = y; } public int gettype() { return type; } public void settype(int type) { this.type = type; } }
snake.java
package com.next.eatsnake; import java.util.arraylist; /** * created by administrator on 2016/3/26 0026. */ public class snake { private arraylist<tile> snake; private int dir; private boolean isalive; public snake(tile head,tile body,tile tail,int dir){ snake = new arraylist<tile>(); head.settype(tile.type_head); body.settype(tile.type_body); tail.settype(tile.type_tail); snake.add(head); snake.add(body); snake.add(tail); isalive = true; this.dir = dir; } public void move(){ if (!isalive) return; switch (dir){ case nextevent.left: switch (gameview.tiles[snake.get(0).getx()-1][snake.get(0).gety()].gettype()){ case tile.type_wall: case tile.type_body: case tile.type_tail: isalive = false; break; case tile.type_food: gameview.tiles[snake.get(0).getx()-1][snake.get(0).gety()].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx() - 1][snake.get(0).gety()]); gameview.iseatfood = true; break; case tile.type_null: gameview.tiles[snake.get(0).getx()-1][snake.get(0).gety()].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx() - 1][snake.get(0).gety()]); snake.get(snake.size()-1).settype(tile.type_null); snake.remove(snake.size()-1); snake.get(snake.size()-1).settype(tile.type_tail); break; } break; case nextevent.right: switch (gameview.tiles[snake.get(0).getx()+1][snake.get(0).gety()].gettype()){ case tile.type_wall: case tile.type_body: case tile.type_tail: isalive = false; break; case tile.type_food: gameview.tiles[snake.get(0).getx()+1][snake.get(0).gety()].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx() + 1][snake.get(0).gety()]); gameview.iseatfood = true; break; case tile.type_null: gameview.tiles[snake.get(0).getx()+1][snake.get(0).gety()].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx() + 1][snake.get(0).gety()]); snake.get(snake.size()-1).settype(tile.type_null); snake.remove(snake.size() - 1); snake.get(snake.size()-1).settype(tile.type_tail); break; } break; case nextevent.up: switch (gameview.tiles[snake.get(0).getx()][snake.get(0).gety()-1].gettype()){ case tile.type_wall: case tile.type_body: case tile.type_tail: isalive = false; break; case tile.type_food: gameview.tiles[snake.get(0).getx()][snake.get(0).gety()-1].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx()][snake.get(0).gety()-1]); gameview.iseatfood = true; break; case tile.type_null: gameview.tiles[snake.get(0).getx()][snake.get(0).gety()-1].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx()][snake.get(0).gety()-1]); snake.get(snake.size()-1).settype(tile.type_null); snake.remove(snake.size()-1); snake.get(snake.size()-1).settype(tile.type_tail); break; } break; case nextevent.down: switch (gameview.tiles[snake.get(0).getx()][snake.get(0).gety()+1].gettype()){ case tile.type_wall: case tile.type_body: case tile.type_tail: isalive = false; break; case tile.type_food: gameview.tiles[snake.get(0).getx()][snake.get(0).gety()+1].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx()][snake.get(0).gety() + 1]); gameview.iseatfood = true; break; case tile.type_null: gameview.tiles[snake.get(0).getx()][snake.get(0).gety()+1].settype(tile.type_head); gameview.tiles[snake.get(0).getx()][snake.get(0).gety()].settype(tile.type_body); snake.add(0, gameview.tiles[snake.get(0).getx()][snake.get(0).gety()+1]); snake.get(snake.size()-1).settype(tile.type_null); snake.remove(snake.size()-1); snake.get(snake.size()-1).settype(tile.type_tail); break; } break; } } public void setdir(int dir){ if (this.dir == dir||this.dir == -dir||dir == nextevent.quiet) return; else this.dir = dir; } public boolean isalive(){ return isalive; } public int getlength(){ return snake.size(); } }
nextevent.java
就是刚开始介绍的那个类,这里就不重复贴出了
到此这篇关于android 2d游戏开发之贪吃蛇基于surfaceview的文章就介绍到这了,更多相关android 贪吃蛇内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!