Android game Screen class Testscreen and game class androidgame design

Source: Internet
Author: User

Android game Screen class Testscreen and game class androidgame design

1. Basic knowledge:


A. WakeLock

http://developer.android.com/reference/android/os/PowerManager.WakeLock.html
B. requestwindowfeature
http://developer.android.com/reference/android/app/Activity.html#requestWindowFeature (int)
C. GetWindow (). setflags
Http://developer.android.com/reference/android/app/Activity.html#getWindow()
http://developer.android.com/reference/android/view/Window.html#setFlags (int, int)
D. Getresources (). GetConfiguration ()
http://developer.android.com/reference/android/content/res/Configuration.html
E. Bitmap.createbitmap
http://developer.android.com/reference/android/graphics/Bitmap.html
F. Getwindowmanager (). Getdefaultdisplay ()
http://developer.android.com/reference/android/view/WindowManager.html
http://developer.android.com/reference/android/view/Display.html
G. powermanager.newwakelock
http://developer.android.com/reference/android/os/PowerManager.html#newWakeLock (int, java.lang.String)
H.bufferedreader
http://developer.android.com/reference/java/io/BufferedReader.html
I.bufferedwriter
http://developer.android.com/reference/java/io/BufferedWriter.html
J.thread
http://developer.android.com/reference/java/lang/Thread.html


2. Design screen interface screens and games interface game
Package Com.badlogic.androidgames.framework;public abstract class Screen {    protected final game game;    Public screen (game game) {        this.game = game;    }    public abstract void Update (float deltatime);    public abstract void Present (float deltatime);    public abstract void Pause ();    public abstract void Resume ();    public abstract void Dispose ();}


Package Com.badlogic.androidgames.framework;public interface Game {public    Input getinput ();    Public FileIO Getfileio ();    Public Graphics getgraphics ();    Public Audio Getaudio ();    public void Setscreen (screens screen);    Public screen Getcurrentscreen ();    Public screen Getstartscreen ();}


3. Implement screen class Testscreen and Game class Androidgame
Package Com.badlogic.androidgames.framework;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.util.list;import Android.graphics.Color; Import Android.util.log;import Com.badlogic.androidgames.framework.graphics.pixmapformat;import Com.badlogic.androidgames.framework.input.keyevent;import com.badlogic.androidgames.framework.Input.TouchEvent;    Class Testscreen extends Screen {long startTime = System.nanotime ();    int frames;    Pixmap Bob;    Pixmap Bobalpha;    Sound sound;            Music Music;            Public Testscreen (game game) {super (game);        Bob = Game.getgraphics (). Newpixmap ("Bobrgb888.png", pixmapformat.rgb565);        Bobalpha = Game.getgraphics (). Newpixmap ("Bobargb8888.png", pixmapformat.argb4444);        Music = Game.getaudio (). NewMusic ("Music.ogg");        Music.setlooping (TRUE);        Music.setvolume (0.5f);        Music.play (); Sound = Game.getaudio (). Newsound ("MUsic.ogg ");            try {BufferedReader in = new BufferedReader (New InputStreamReader (Game.getfileio (). Readasset ("Test.txt")));            String text = In.readline ();                        In.close ();            BufferedWriter out = new BufferedWriter (New OutputStreamWriter (Game.getfileio (). WriteFile ("test.txt"));            Out.write ("This is a freaking test");                        Out.close ();            in = new BufferedReader (New InputStreamReader (Game.getfileio (). ReadFile ("test.txt"));            String Text2 = In.readline ();                        In.close ();        LOG.D ("Mrnom", Text + "," + Text2);        } catch (Exception ex) {ex.printstacktrace ();  }} @Override public void update (float deltatime) {} @Override public void present (float deltatime)        {Graphics g = game.getgraphics ();        Input INP = Game.getinput ();        G.clear (color.red);        G.drawline (0,0,320, 480, Color.Blue); G.dRawrect (20,20,100,100, Color.green);        G.drawpixmap (Bob, 100, 100);        G.drawpixmap (Bobalpha, 100, 200);        G.drawpixmap (Bob, 200, 200, 0, 0, 64, 64); for (int i=0; i < 2; i++) {if (Inp.istouchdown (i)) {G.drawpixmap (Bob, Inp.gettouchx (i), INP.G            Ettouchy (i), 0, 0, 64, 64); }} g.drawpixmap (Bob, (int) (INP.GETACCELX () *) + 160-16, (int) (inp.getaccely () * 10) + 240-16                , 0, 0, 32, 32);        list<keyevent> keyevents = inp.getkeyevents ();        int len = Keyevents.size ();        for (int i = 0; i < len; i++) {log.d ("Mrnom", Keyevents.get (i). toString ());        } list<touchevent> touchevents = Inp.gettouchevents ();        Len = Touchevents.size ();            for (int i = 0; i < len; i++) {log.d ("Mrnom", Touchevents.get (i). toString ());        if (Touchevents.get (i). Type = = touchevent.touch_up) sound.play (1);             }   frames++; if (System.nanotime ()-startTime > 1000000000l) {log.d ("Mrnom", "fps:" + frames + ", Delta:" + deltatime)            ;            frames = 0;        StartTime = System.nanotime ();                    }} @Override public void Pause () {log.d ("mrnom", "pause");       } @Override public void Resume () {LOG.D ("Mrnom", "Resume");        } @Override public void Dispose () {log.d ("Mrnom", "Dispose");    Music.dispose (); }            }


 

Package Com.badlogic.androidgames.framework.impl;import Android.app.activity;import Android.content.Context; Import Android.content.res.configuration;import Android.graphics.bitmap;import android.graphics.Bitmap.Config; Import Android.os.bundle;import Android.os.powermanager;import Android.os.powermanager.wakelock;import Android.view.window;import Android.view.windowmanager;import Com.badlogic.androidgames.framework.audio;import Com.badlogic.androidgames.framework.fileio;import Com.badlogic.androidgames.framework.game;import Com.badlogic.androidgames.framework.graphics;import Com.badlogic.androidgames.framework.input;import Com.badlogic.androidgames.framework.screen;public abstract class Androidgame extends Activity implements Game {Android    Fastrenderview Renderview;    Graphics graphics;    Audio audio;    input input;    FileIO FileIO;    Screen screen;    WakeLock WakeLock; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);       Requestwindowfeature (Window.feature_no_title); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN        );        Boolean islandscape = Getresources (). GetConfiguration (). Orientation = = Configuration.orientation_landscape; int framebufferwidth = Islandscape?        480:320; int framebufferheight = Islandscape?        320:480;                Bitmap FrameBuffer = Bitmap.createbitmap (Framebufferwidth, Framebufferheight, config.rgb_565);        float ScaleX = (float) framebufferwidth/getwindowmanager (). Getdefaultdisplay (). GetWidth ();        float ScaleY = (float) framebufferheight/getwindowmanager (). Getdefaultdisplay (). GetHeight ();        Renderview = new Androidfastrenderview (this, frameBuffer);        Graphics = new Androidgraphics (Getassets (), frameBuffer);        FileIO = new Androidfileio (Getassets ());        Audio = new Androidaudio (this); Input= New Androidinput (this, Renderview, ScaleX, ScaleY);        Screen = Getstartscreen ();                Setcontentview (Renderview);        PowerManager PowerManager = (powermanager) getsystemservice (Context.power_service);    WakeLock = Powermanager.newwakelock (Powermanager.full_wake_lock, "glgame");        } @Override public void Onresume () {super.onresume ();        Wakelock.acquire ();        Screen.resume ();    Renderview.resume ();        } @Override public void OnPause () {super.onpause ();        Wakelock.release ();        Renderview.pause ();        Screen.pause ();    if (isfinishing ()) screen.dispose ();    } @Override Public Input getinput () {return input;    } @Override Public FileIO Getfileio () {return FileIO;    } @Override Public Graphics Getgraphics () {return graphics;    } @Override Public Audio Getaudio () {return audio; } @Override public void Setscreen (screens screen) {       if (screen = null) throw new IllegalArgumentException ("screen must not is null");        This.screen.pause ();        This.screen.dispose ();        Screen.resume ();        Screen.update (0);    This.screen = screen;    Getcurrentscreen () {return screen; }}


4. The game class Androidgame used to quickly redraw the view class Androidfastrenderview

Package Com.badlogic.androidgames.framework.impl;import Android.graphics.bitmap;import Android.graphics.Canvas; Import Android.graphics.rect;import Android.view.surfaceholder;import Android.view.surfaceview;public class    Androidfastrenderview extends Surfaceview implements Runnable {Androidgame game;    Bitmap framebuffer;    Thread renderthread = null;    Surfaceholder Holder;        Volatile Boolean running = false;        Public Androidfastrenderview (androidgame game, Bitmap framebuffer) {super (game);        This.game = game;        This.framebuffer = framebuffer;    This.holder = Getholder ();        } public void Resume () {running = true;        Renderthread = new Thread (this);             Renderthread.start ();        public void Run () {rect dstrect = new Rect ();        Long startTime = System.nanotime ();                                   while (running) {if (!holder.getsurface (). IsValid ()) continue; Float DEltatime = (System.nanotime ()-starttime)/1000000000.0f;            StartTime = System.nanotime ();            Game.getcurrentscreen (). Update (deltatime);                        Game.getcurrentscreen (). Present (Deltatime);            Canvas canvas = Holder.lockcanvas ();            Canvas.getclipbounds (dstrect);                                       Canvas.drawbitmap (framebuffer, NULL, dstrect, NULL);        Holder.unlockcanvasandpost (canvas);                                }} public void Pause () {running = false;                while (true) {try {renderthread.join ();            Break } catch (Interruptedexception e) {//Retry}}}}


5. Another game class glgame based on OpenGL ES (the previous game class Androidgame is based on the general Graphics graphics)

Package Com.badlogic.androidgames.framework.impl;import Javax.microedition.khronos.egl.eglconfig;import Javax.microedition.khronos.opengles.gl10;import Android.app.activity;import Android.content.context;import Android.opengl.glsurfaceview;import Android.opengl.glsurfaceview.renderer;import Android.os.Bundle;import Android.os.powermanager;import Android.os.powermanager.wakelock;import Android.view.window;import Android.view.windowmanager;import Com.badlogic.androidgames.framework.audio;import Com.badlogic.androidgames.framework.fileio;import Com.badlogic.androidgames.framework.game;import Com.badlogic.androidgames.framework.graphics;import Com.badlogic.androidgames.framework.input;import Com.badlogic.androidgames.framework.screen;public abstract class Glgame extends Activity implements Game, Renderer {en  Um glgamestate {Initialized, Running, Paused, finished, Idle} Glsurfaceview        Glview;    Glgraphics Glgraphics;    Audio audio; INput input;    FileIO FileIO;    Screen screen;    Glgamestate state = glgamestate.initialized;    Object statechanged = new Object ();    Long startTime = System.nanotime ();        WakeLock WakeLock;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FL        Ag_fullscreen);        Glview = new Glsurfaceview (this);        Glview.setrenderer (this);                Setcontentview (Glview);        Glgraphics = new Glgraphics (Glview);        FileIO = new Androidfileio (Getassets ());        Audio = new Androidaudio (this);        input = new Androidinput (this, Glview, 1, 1);        PowerManager PowerManager = (powermanager) getsystemservice (Context.power_service);            WakeLock = Powermanager.newwakelock (Powermanager.full_wake_lock, "glgame");        }public void Onresume () {super.onresume ();        Glview.onresume ();    Wakelock.acquire ();                } @Override public void onsurfacecreated (GL10 gl, EGLConfig config) {GLGRAPHICS.SETGL (GL); Synchronized (statechanged) {if (state = = glgamestate.initialized) screen = GETSTARTSC            Reen ();            state = glgamestate.running;            Screen.resume ();        StartTime = System.nanotime (); }} @Override public void onsurfacechanged (GL10 gl, int width, int height) {} @Overrid                e public void Ondrawframe (GL10 gl) {glgamestate state = null;        Synchronized (statechanged) {state = This.state; } if (state = = glgamestate.running) {Float deltatime = (system.nanotime ()-starttime)/100000000            0.0f;                        StartTime = System.nanotime ();            Screen.update (deltatime); ScrEen.present (deltatime);                        } if (state = = glgamestate.paused) {screen.pause ();                Synchronized (statechanged) {this.state = Glgamestate.idle;            Statechanged.notifyall ();            }} if (state = = glgamestate.finished) {screen.pause ();            Screen.dispose ();                Synchronized (statechanged) {this.state = Glgamestate.idle;            Statechanged.notifyall ();            }}} @Override public void OnPause () {synchronized (statechanged) {            if (isfinishing ()) state = glgamestate.finished;            else state = glgamestate.paused;                    while (true) {try {statechanged.wait ();                Break } catch (Interruptedexception e) {}}} wakeLock.release ();          Glview.onpause ();    Super.onpause ();    } public Glgraphics Getglgraphics () {return glgraphics;    } @Override Public Input getinput () {return input;    } @Override Public FileIO Getfileio () {return FileIO;    } @Override Public Graphics getgraphics () {throw new IllegalStateException ("We are using opengl!");    } @Override Public Audio Getaudio () {return audio; } @Override public void Setscreen (screens) {if (screen = null) throw new Illegalargumentex        Ception ("screen must is not NULL");        This.screen.pause ();        This.screen.dispose ();        Screen.resume ();        Screen.update (0);    This.screen = screen;    } @Override Public Screens Getcurrentscreen () {return screen; }}



This paper briefly describes the basic knowledge of "beginning-android-games" books and the design analysis of related classes,
Books and source code:http://download.csdn.net/detail/yangzhenping/8420261
The class implementation in this article is from "Beginning-android-games\ch07-gl-basics"

Android game Screen class Testscreen and game class androidgame design

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.