【AS3代码】一个完整的游戏框架

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    
    public class Main extends Sprite
    {        
        public static const STATE_INIT:int = 10;
        public static const STATE_PLAY:int = 20;
        public static const STATE_GAME_OVER:int = 30;
        public var gameState:int = 0;                    //游戏状态
        public var clicks:int = 0;                        //游戏点击次数
        
        public function Main():void
        {
            init();
        }
        private function init():void
        {
            this.addEventListener(Event.ENTER_FRAME, gameLoop);
            gameState = STATE_INIT;
        }
        
        public function gameLoop(e:Event):void
        {
            switch(gameState)
            {
                case STATE_INIT:
                    initGame();
                    break;
                case STATE_PLAY:
                    playGame();
                    break;
                case STATE_GAME_OVER:
                    gameOver();
                    break;
            }
        }
        
        public function initGame():void
        {
            //初始化游戏,当按钮被点击后,点击次数归零,状态改为游戏开始
            stage.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
            clicks = 0;
            gameState = STATE_PLAY;
        }
        public function playGame():void
        {
            //若游戏被点击了10次,状态改为游戏结束
            if(clicks >= 10)
            {
                gameState = STATE_GAME_OVER;
            }
        }
        public function onMouseClickEvent(e:MouseEvent):void
        {
            clicks++;    //游戏点击次数+1
            trace("点击了" + clicks + "次游戏!");
        }
        public function gameOver():void
        {
            //注销游戏监听器
            stage.removeEventListener(MouseEvent.CLICK, onMouseClickEvent);
            gameState = STATE_INIT;
            trace("游戏结束!");
        }
    }
}
posted @ 2012-06-20 11:05  王翔(kingfly)  阅读(2381)  评论(0编辑  收藏  举报