用FLASH 做一个 小游戏

用As 3做的第一个Flash最简单的小游戏2011-01-30 17:17:43| 分类: Actionscript 3.0 阅读50 评论0 字号:大中小 订阅

一个长方形可以按A或者D左移右移,在游戏开始会监听键盘事件,圆形在舞台下面往上跑,如果长方形碰到圆,游戏结束,就这么简单。看代码myGame.as,你可以新建一个Fla文件,然后以myGame.as为文档类:

package {

import flash.display.MovieClip;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.display.*;

import flash.events.*;

import flash.text.TextField;

public class myGame extends MovieClip{

public const State_init=1;

public const State_play=2;

public const State_over=3;

public var gamestate:uint=0;

public var success:uint=0;

public var fail:int=0;

public var player1:Sprite=new Sprite();

public var player2:Sprite=new Sprite();

public function myGame(){

player1.graphics.beginFill(0xFF0000);

player1.graphics.drawRect(100,100,20,10);

player1.graphics.endFill();

player2.graphics.beginFill(0);

player2.graphics.drawCircle(200,400,10);

player2.graphics.endFill();

stage.addChild(player1);

stage.addChild(player2);

//默认会初始化构造函数,添加监听当前的游戏状态

stage.addEventListener(Event.ENTER_FRAME,gameloop);

//初始化游戏状态,要不gamestate=0;

gamestate=State_init;

// constructor code

}

public function gameloop(e:Event):void{

switch(gamestate) {

case State_init:

initGame();

break;

case State_play:

playGame();

break;

case State_over:

gameOver();

break;

}

}

public function initGame():void{

stage.addEventListener(KeyboardEvent.KEY_DOWN,action);

success=0;

fail=0;

gamestate=State_play;

}

public function action(e:KeyboardEvent):void{

if(e.keyCode==65){

trace(e.keyCode);

player1.x-=2;

}else if(e.keyCode==68){

player1.x+=2;

}

if(player1.hitTestObject(player2)){

gameOver();

trace("you win!");

}

}

public function playGame():void{

player2.y-=4;

}

public function gameOver():void{

stage.removeEventListener(KeyboardEvent.KEY_DOWN,action);

gamestate=0;

trace("game over");

}

}