博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

J2ME游戏开发之GameCanvas构造类

Posted on 2011-08-19 16:27  zhangweia  阅读(230)  评论(0编辑  收藏  举报
 
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();
    }