J2ME游戏开发之GameCanvas构造类

 
package com.slinw.gamecanvas;



import javax.microedition.lcdui.Graphics;

import javax.microedition.lcdui.game.GameCanvas;





public abstract class RootGameCanvas extends GameCanvas implements Runnable{



        private Graphics g = null;

        private boolean isPlay; // Game Loop runs when isPlay is true

        private long delay; // To give thread consistency

     

        // Constructor and initialization

        public RootGameCanvas() {

            super(true);

            delay = 200;

            g = getGraphics();

        }

     

        // Automatically start thread for game loop

        public void start() {

            isPlay = true;

            new Thread(this).start();

        }

     

        public void stop() {

            isPlay = false;

        }

     

        // Main Game Loop

        public void run() {

            while (isPlay) {

                keyEventInput();

                drawScreen(g);

                try {

                    Thread.sleep(delay);

                } catch (InterruptedException ie) {}

            }

        }

     

        

        

        // Method to Handle User Inputs

        public void keyEventInput(){

            int key = getKeyStates();

            if((key & LEFT_PRESSED) != 0){

                keyLeftPressedEvent();

            }

            

            if((key & RIGHT_PRESSED) != 0){

                keyRightPressedEvent();

            }

            

            if((key & UP_PRESSED) != 0){

                keyUpPressedEvent();

            }

            

            if((key & DOWN_PRESSED) != 0){

                keyDownPressedEvent();

            }

        }

     

        

        // Method to Display Graphics

        public abstract void drawScreen(Graphics g);

        

        

        public abstract void keyLeftPressedEvent();

        

        public abstract void keyRightPressedEvent();

        

        public abstract void keyUpPressedEvent();

        

        public abstract void keyDownPressedEvent();

    }

你可能感兴趣的:(canvas)