In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to use surfaceviewAndroid to develop the 2d game Snake? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Let's take a look at this synchronization framework and see if you can figure it out for yourself.
GameView.java (inherited from 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;// Game status Thread thread;// Game Thread Boolean flag;// Game Loop Control Mark Canvas canvas;// canvas Paint paint;// Brush SurfaceHolder holder;//SurfaceView Control handle Random random;// Random number NextEvent nextEvent / / width and height of the game input event int scrW,scrH;// screen public GameView (Context context) {super (context); gameState = GameState.Menu; flag = true; paint = new Paint (); paint.setAntiAlias (true); / / handwriting smoothing 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 (); / / clear event} private void menuLogic () {if (nextEvent.getUpX () > 0) {gameState = GameState.Playing after each logical loop }} 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.setColor (Color.RED); paint.setTextSize (50); canvas.drawText ("I am in menu.Touch me to next scence") } private void playingDraw (Canvas canvas) {paint.setColor (Color.RED); paint.setTextSize (50); canvas.drawText ("I am in playing,Slide down to next scence", 100emergency100paint);} private void overDraw (Canvas canvas) {paint.setColor (Color.RED); paint.setTextSize (50); canvas.drawText ("I am in over,Slide right to next scence", 100Pertin100paint) } / / here is the synchronous trigger mechanism / / for each clock cycle, execute the logical method and drawing method @ Override public void run () {while (flag) {mLogic (); mDraw (); try {Thread.sleep (500) } catch (Exception e) {e.printStackTrace ();} / / call @ Override public void surfaceCreated (SurfaceHolder holder) {thread.start () when SurfaceView is created @ Override public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {} / / SurfaceView is called @ Override public void surfaceDestroyed (SurfaceHolder holder) {flag = false;}} when SurfaceView changes
This is just a game framework, and I haven't written anything into it yet, but according to my experience (although I don't have a lot of experience), it already includes the main frame code of all games (specifically Mini Game -). With this framework, we just need to write the logic and drawing methods of the game, without worrying about how to build the game framework.
Here I also add a NextEvent method, in which I encapsulate the sliding gestures used in the last game, in this kick circle, one of the most common words is: do not repeat the wheel. When we see that a lot of repetitive code has been written, it is time for us to simplify.
The above code:
NextEvent.javapackage 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 this.dir / No sliding 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.javapackage 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.javapackage 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 nullList = new ArrayList(); 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() >Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.