点中圆表示击中否则没有击中,击中10次为win。

主要练习的就是addEventListener的使用。

 
  
  1. var num:uint=20;//代码生成目标数量  
  2. var score:uint=0;  
  3. var miss:uint=0;  
  4. var SW:uint=stage.stageWidth;  
  5. var SH:uint=stage.stageHeight;  
  6.  
  7. var tf:TextField = new TextField();  
  8.  
  9. tf.text="开始";  
  10. tf.x = tf.y = 25;  
  11. tf.autoSize = "left";//对齐方式  
  12. tf.width = 200;  
  13. addChild(tf);  
  14.  
  15. const YOU_WIN : String ="youWin";  
  16. const YOU_LOSE : String="youLose";  
  17.  
  18. stage.addEventListener(MouseEvent.CLICK,kill);  
  19. stage.addEventListener(YOU_WIN,win);  
  20. stage.addEventListener(YOU_LOSE,lose);  
  21.  
  22. for(var i : uint = 0 ; i < num ; i++)  
  23. {  
  24.   var target:Sprite = new Sprite();  
  25.   target.graphics.beginFill(0xffffff*Math.random());  
  26.   target.graphics.drawCircle(0,0,40);  
  27.   target.graphics.endFill();  
  28.   target.scaleX=target.scaleX=Math.random()*.5+.5;  
  29.   addChildAt(target,0);  
  30.    
  31.   target.x=Math.random()*(SW-target.width)+target.width/2;  
  32.   target.y=Math.random()*(SH-target.height)+target.height/2;  
  33. }  
  34.  
  35. function kill(e:MouseEvent):void  
  36. {  
  37.   if(e.target != e.currentTarget)  
  38.   {  
  39.     e.target.parent.removeChild(e.target);  
  40.     score++;  
  41.     tf.text="打中了,已经打中了"+score+"枪";  
  42.   }  
  43.   else 
  44.   {  
  45.     miss++;  
  46.     tf.text="失误了,已经失误了"+miss+"枪";  
  47.   }  
  48.   if(score>=10)  
  49.   {  
  50.      stage.dispatchEvent(new Event(YOU_WIN));  
  51.   }  
  52.   else if(miss>=10)  
  53.   {  
  54.     stage.dispatchEvent(new Event(YOU_LOSE));  
  55.   }  
  56. }  
  57.  
  58. function win(e:Event):void  
  59. {  
  60.    tf.text="you win";  
  61.    stage.removeEventListener(MouseEvent.CLICK,kill);  
  62.    stage.removeEventListener(YOU_WIN,win);  
  63.    stage.removeEventListener(YOU_WIN,lose);  
  64. }  
  65.  
  66. function lose(e:Event):void  
  67. {  
  68.   tf.text="you lose";  
  69.   stage.removeEventListener(MouseEvent.CLICK,kill);  
  70.   stage.removeEventListener(YOU_WIN,win);  
  71.   stage.removeEventListener(YOU_WIN,lose);  
  72. }