用FLASH做一个小游戏
按A或d可以向左或向右移动一个矩形,游戏开始时会监控键盘事件,圆形会在舞台下跑起来。如果矩形碰到圆,游戏就结束了,就这么简单。看代码myGame.as,可以新建一个Fla文件,然后把myGame.as作为文档类:
包{
导入flash . display . movie clip;
导入flash . events . event;
导入flash . events . mouse event;
导入flash . display . *;
导入flash . events . *;
导入flash . text . textfield;
公共类myGame扩展了MovieClip{
public const State _ init = 1;
public const State _ play = 2;
public const State _ over = 3;
公共var gamestate:uint = 0;
公共var成功:uint = 0;
公共var失败:int = 0;
公共var player 1:Sprite = new Sprite();
public var player 2:Sprite = new Sprite();
公共函数myGame(){
player 1 . graphics . begilling(0x ff 0000);
player 1 . graphics . drawrect(100,100,20,10);
player 1 . graphics . end fill();
player 2 . graphics . begilling(0);
player 2 . graphics . draw circle(200,400,10);
player 2 . graphics . end fill();
stage . addchild(player 1);
stage . addchild(player 2);
//默认情况下,将初始化并添加构造函数来监控当前游戏状态。
stage.addEventListener(事件。ENTER_FRAME,game loop);
//初始化游戏状态,或者gamestate = 0;
gamestate = State _ init
//构造函数代码
}
公共函数gameloop(e:Event):void{
开关(游戏状态){
案例状态_初始化:
init game();
打破;
案例状态_播放:
play game();
打破;
案例状态_结束:
game over();
打破;
}
}
公共函数initGame():void{
stage . addevent listener(keyboard event。KEY_DOWN,action);
成功= 0;
失败= 0;
游戏状态=状态_播放;
}
公共函数动作(e:KeyboardEvent):void{
if(e.keyCode==65){
trace(e . keycode);
player 1 . x-= 2;
}else if(e.keyCode==68){
player 1 . x+= 2;
}
if(player 1 . hittes object(player 2)){
game over();
trace("你赢了!");
}
}
公共函数playGame():void{
player 2 . y-= 4;
}
公共函数gameOver():void{
stage . removeeventlistener(keyboard event。KEY_DOWN,action);
gamestate = 0;
trace(“游戏结束”);
}
}