public ApplicationSprite()
        {



            InternalContent = new global::FlashTreasureHunt.ActionScript.FlashTreasureHunt();
            InternalContent.AttachTo(this);


            //this.click +=
            //  e =>
            //  {
            //      e.stopImmediatePropagation();


            //      //this.stage.fullScreenSourceRect = new ScriptCoreLib.ActionScript.flash.geom.Rectangle(
            //      //     0, 0, DefaultWidth, DefaultHeight
            //      // );



            //      this.stage.SetFullscreen(true);


            //  };

        }
Ejemplo n.º 2
0
		public UltraSprite()
		{
			this.graphics.beginFill(0xffffff);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);
			this.graphics.lineStyle(2, 0xa0, 1);
			this.graphics.beginFill(0xffffff, 0);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);

			t = new TextField
			{
				width = DefaultWidth,
				height = DefaultHeight
			};

			t.AttachTo(this);

			this.AppendLine("This is flash.display.Sprite (version 101)");

			var Button1 = new Sprite();

			Button1.graphics.beginFill(0xff00);
			Button1.graphics.drawRect(0, 0, 64, 24);
			Button1.useHandCursor = true;
			Button1.buttonMode = true;

			Button1.AttachTo(this).MoveTo(DefaultWidth - 64 - 8, 8);

			Button1.click +=
				delegate
				{
					// jsc.meta should use Convert type for us
					if (Convert.ToBoolean(this.WebServiceEnabled.IsEnabled))
					{
						this.WebService.GetTime("[flash client time]: " + DateTime.Now + " [server time]",
							x =>
							{
								this.AppendLine(x);
							}
						);
					}
					else
					{
						this.AppendLine("WebService is disabled!");
					}
				};
		}
		public void InitializeCompass()
		{
			var compass = Assets.Default.compasscolor;
			var container = new Sprite();

			container.alpha = 0;

			CompassContainer = container;

			compass.AttachTo(container);
			container.AttachTo(HudContainer);

			Action Update =
				delegate
				{
					// compass must show us where the goal is

					var delta = new Point(maze.Width - 1.5 - EgoView.ViewPositionX, maze.Height - 1.5 - EgoView.ViewPositionY);

					container.rotation = (delta.GetRotation() - EgoView.ViewDirection).RadiansToDegrees();


				};

			EgoView.ViewDirectionChanged += Update;

			EgoView.ViewPositionChanged += Update;

			Update();

			compass.scaleX = 0.5;
			compass.scaleY = 0.5;

			compass.x = -compass.width / 2;
			compass.y = -compass.height / 2;

			container.filters = new[] { new ScriptCoreLib.ActionScript.flash.filters.DropShadowFilter() };

			container.x = DefaultControlWidth - compass.width / 2;
			container.y = compass.height / 2;
		}
        /// <summary>
        /// Default constructor
        /// </summary>
        public Sudoku()
        {
            var t = new SudokuFile(Assets.Level1.ToStringAsset());

            t.Mappings.Randomize();

            const int padding = 2;
            const int w = 28;
            const int h = 28;

            for (int y = 1; y < 10; y++)
                for (int x = 1; x < 10; x++)
                {
                    var s = new Sprite();


                    var text = new TextField
                    {
                        text = t[x, y].ToString(),
                        mouseEnabled = false
                    }.AttachTo(s);

                    text.autoSize = TextFieldAutoSize.LEFT;
                    text.x = -text.width / 2;
                    text.y = -text.height / 2;

                    s.graphics.lineStyle(3, 0xff5300, 1);
                    s.graphics.drawRect(-w / 2, -h / 2, w, h);
                    
                    // s.filters = new[] { new BevelFilter() };

                    s.x = (w + padding) * x;
                    s.y = (h + padding) * y;

                    s.AttachTo(this);

                }
        }
Ejemplo n.º 5
0
        //[Script(IsDebugCode = true)]
        private static void AddInfo(Sprite InfoMenu, double y, Actor v)
        {
            v.CanMakeFootsteps = false;


            var h = new Sprite();

            Action<uint> Draw =
                color =>
                {
                    h.graphics.clear();
                    h.graphics.beginFill(color, 0.5);
                    h.graphics.drawRect(-32, -32, 64, 64);
                    h.graphics.endFill();
                    //h.graphics.lineStyle(1, 0x808080, 0.8);
                    //h.graphics.drawRect(-32, -32, 64, 64);

                    h.graphics.beginFill(color, 0.5);
                    h.graphics.drawRect(48, -32, 180, 64);
                    h.graphics.endFill();
                    //h.graphics.lineStyle(1, 0x808080, 0.8);
                    //h.graphics.drawRect(48, -32, 180, 64);
                };

            Draw(ColorBlueLight);

            h.click +=
                delegate
                {

                    if (0.5.ByChance())
                    {
                        if (v.PlayHelloSound != null)
                            v.PlayHelloSound();
                    }
                    else
                    {
                        if (v.PlayDeathSound != null)
                            v.PlayDeathSound();
                    }
                };

            h.mouseChildren = false;

            //h.filters = new[] { new GlowFilter(0x808080) };
            h.mouseOver += e => Draw(ColorBlue);
            h.mouseOut += e => Draw(ColorBlueLight);

            var t = new TextField
            {
                x = 64,
                text = v.ActorName + "\n" + v.ScoreValue + " points\n" + v.Description,
                autoSize = TextFieldAutoSize.LEFT,

            }.AttachTo(h);

            t.y -= t.height / 2;

            v.AttachTo(h);

            h.AttachTo(InfoMenu).MoveTo(0, y);
        }
		private void InitializeWeaponOverlay(Dictionary<string, Bitmap> f)
		{
			Func<int, Bitmap> id = _id => f[_id + ".png"];

			var hand = new Sprite();

			var noweapon = f["hand.png"].AttachTo(hand);

			var gun_index = 0;

			var gun = new[]
				{
					id(326),
					id(327),
					id(328),
					id(329),
					id(330),
				};


			//var hand = f["330.png"];
			const int handsize = 4;

			var hand_x = (DefaultControlWidth - 64 * handsize) / 2;
			var hand_y_default = DefaultControlHeight - 64 * handsize;

			var hand_y = hand_y_default;

			hand.x = hand_x;
			hand.y = hand_y;
			hand.scaleX = handsize;
			hand.scaleY = handsize;
			hand.AttachTo(HudContainer);

			#region make it float
			(1000 / 24).AtInterval(
				tt =>
				{
					hand.x = hand_x + Math.Cos(tt.currentCount * 0.2) * 6;
					hand.y = hand_y + Math.Abs(Math.Sin(tt.currentCount * 0.2)) * 4;
				}
			);
			#endregion


			var WeaponChangeSpeed = handsize * 4;

			Action<Action> BringWeaponUp =
				ChangeDone =>
				{


					(1000 / 24).AtInterval(
						tt =>
						{
							hand_y -= WeaponChangeSpeed;

							if (hand_y <= hand_y_default)
							{
								tt.stop();

								hand_y = hand_y_default;

								// ready to fire

								ChangeDone();
							}
						}
					);
				};

			Action<Action, Action> BringWeaponDown =
				(MomentOfChange, ChangeDone) =>
				{
					(1000 / 24).AtInterval(
						tt =>
						{
							hand_y += WeaponChangeSpeed;

							if (hand_y >= DefaultControlHeight - (32 * handsize))
							{
								// hand is off screen
								// lets switch to a weapon

								MomentOfChange();

								tt.stop();

								BringWeaponUp(ChangeDone);
							}
						}
					);
				};

			Action SwitchToWeaponDefault =
				delegate
				{
					// disable this function
					SwitchToWeapon = delegate { };


					BringWeaponDown(
						delegate
						{
							noweapon.Orphanize();
							gun.First().AttachTo(hand);
						}
						,
						delegate
						{
							WeaponIsActive = true;
						}
					);
				};


			SwitchToWeapon = SwitchToWeaponDefault;


			Action<Action> PlayFireAnimation =
				done =>
				{

					(1000 / 15).AtInterval(
						tt =>
						{
							gun[gun_index].Orphanize();

							gun_index++;

							if (gun_index == gun.Length)
							{
								// done

								gun_index = 0;
								tt.stop();

								done();
							}

							gun[gun_index].AttachTo(hand);

						}
					);
				};

			FireWeapon =
				delegate
				{
					if (EndLevelMode)
						return;

					if (!WeaponIsActive)
						return;

					// we can fire only if the animation has stopped
					if (gun_index != 0)
						return;

					Assets.Default.Sounds.gunshot.play();

					WeaponAmmo--;

					// add damage to sprites

					// we need to find out the one we are shooting at!

					// try adding damage to all

					//WriteLine("fire:");


					var query = 
						from k in EgoView.GetVisibleSprites(15.DegreesToRadians(),
							from p in EgoView.Sprites
							let fragile = p as SpriteInfoExtended
							where fragile != null
							where fragile.Health > 0
							where fragile.TakeDamage != null
							select p
						)
						orderby k.Distance
						let fragile = k.Sprite as SpriteInfoExtended
						select new { k, fragile };




					var first = query.FirstOrDefault();

					if (first != null)
					{
						var DamageToBeTaken = 1 / first.k.Distance;

						//WriteLine("hit: " + DamageToBeTaken);

						first.fragile.TakeDamage(DamageToBeTaken);
					}


					PlayFireAnimation(
						delegate
						{
							if (WeaponAmmo <= 0)
							{
								// dude, we are out of ammo!!

								WeaponIsActive = false;

								Action ReadyForMoreAmmo =
									delegate
									{
										SwitchToWeapon = SwitchToWeaponDefault;
									};

								SwitchToWeapon =
									delegate
									{
										SwitchToWeapon = delegate { };

										// the animation has not yet stopped but we found the ammo
										// when we are ready we switch back for the gun
										// this can be tested if the hand movement is really slow
										ReadyForMoreAmmo = SwitchToWeaponDefault;
									};

								BringWeaponDown(
									delegate
									{
										gun.First().Orphanize();
										noweapon.AttachTo(hand);
									}
									,
									delegate
									{
										ReadyForMoreAmmo();
									}
								);

							}
						}
					);
				};
		}
Ejemplo n.º 7
0
        public MySprite1()
        {
            // http://forums.adobe.com/thread/986019
            // wont run on AIR anymore?
            //TypeError: Error #1009: Cannot access a property or method of a null object reference.
            //    at Main/frame1()


            var q = (WidescreenWidth - ContentWidth) / 2;
            var c = new Sprite();

            c.graphics.beginFill(0);
            c.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);

            c.AttachTo(this);

            //        TypeError: Error #1009: Cannot access a property or method of a null object reference.
            //at Main/frame1()

            //V:\web\IntegrationToSkyIsland\Assets\sky_island_10899.as(10): col: 9: Error: unable to resolve '/assets/IntegrationToSkyIsland/sky-island-10899.swf' for transcoding

            //        [Embed(source = "/assets/IntegrationToSkyIsland/sky-island-10899.swf", mimeType = "application/x-shockwave-flash")]
            //        ^

            //V:\web\IntegrationToSkyIsland\Assets\sky_island_10899.as(10): col: 9: Error: Unable to transcode /assets/IntegrationToSkyIsland/sky-island-10899.swf.


            Sprite x = null;


            try
            {
                x = Assets.sky_island_10899.Source;
                x.AttachTo(this).MoveTo(q, 0);
            }
            catch
            {
                // can we skip?
            }



            #region buttons
            Action<Sprite, uint> bind = (s, keyCodeValue) =>
            {
                s.click +=
                    e =>
                    {
                        e.stopImmediatePropagation();


                        // a glitch?
                        //this.stage.fullScreenSourceRect = new ScriptCoreLib.ActionScript.flash.geom.Rectangle(
                        //     0, 0, DefaultWidth, DefaultHeight
                        // );

                        //this.stage.SetFullscreen(true);
                    };

                s.mouseDown +=
                  e =>
                  {
                      e.stopImmediatePropagation();
                      x.dispatchEvent(
                          new KeyboardEvent(KeyboardEvent.KEY_DOWN,
                              keyCodeValue: keyCodeValue /* left */
                          )
                      );
                  };

                s.mouseUp +=
                      e =>
                      {
                          e.stopImmediatePropagation();

                          x.dispatchEvent(
                             new KeyboardEvent(KeyboardEvent.KEY_UP,
                                 keyCodeValue: keyCodeValue /* left */
                             )
                         );
                      };

            };

            new Sprite().With(
                GoLeft =>
                {

                    GoLeft.graphics.beginFill(0);
                    GoLeft.graphics.drawRect(0, 0, q, DefaultHeight);
                    GoLeft.alpha = 0.9;

                    bind(GoLeft, 37);


                    GoLeft.AttachTo(this);
                }
          );

            new Sprite().With(
                GoRight =>
                {

                    GoRight.graphics.beginFill(0);
                    GoRight.graphics.drawRect(WidescreenWidth - q, 0, q, DefaultHeight);
                    GoRight.alpha = 0.9;

                    bind(GoRight, 39);

                    GoRight.AttachTo(this);
                }
            );

            new Sprite().With(
                GoUp =>
                {

                    GoUp.graphics.beginFill(0);
                    GoUp.graphics.drawRect(0, DefaultHeight - q, WidescreenWidth, q);
                    GoUp.alpha = 0.05;

                    bind(GoUp, 38);

                    GoUp.AttachTo(this);
                }
            );
            #endregion


            //var t = new TextField().AttachTo(this);
            //t.autoSize = TextFieldAutoSize.LEFT;

            #region Accelerometer - AIR?
            if (Accelerometer.isSupported)
            {
                a = new Accelerometer();

                var ax = 0.0;
                var az = 0.0;

                a.update +=
                  e =>
                  {
                      var wx = 0.15;
                      var wz = 0.5;

                      if (e.accelerationZ > wz)
                      {
                          if (az > wz)
                          {
                              // nop
                          }
                          else
                          {
                              x.dispatchEvent(
                                  new KeyboardEvent(KeyboardEvent.KEY_DOWN,
                                      keyCodeValue: 38
                                  )
                              );
                          }
                      }
                      else
                      {
                          if (az > wz)
                          {
                              x.dispatchEvent(
                                 new KeyboardEvent(KeyboardEvent.KEY_UP,
                                     keyCodeValue: 38
                                 )
                             );
                          }
                      }

                      if (e.accelerationX < -wx)
                      {
                          if (ax < -wx)
                          {
                              // nop
                          }
                          else
                          {
                              x.dispatchEvent(
                                  new KeyboardEvent(KeyboardEvent.KEY_DOWN,
                                      keyCodeValue: 39
                                  )
                              );
                          }
                      }
                      else
                      {
                          if (ax < -wx)
                          {
                              x.dispatchEvent(
                                 new KeyboardEvent(KeyboardEvent.KEY_UP,
                                     keyCodeValue: 39
                                 )
                             );
                          }
                      }


                      if (e.accelerationX > wx)
                      {
                          if (ax > wx)
                          {
                              // nop
                          }
                          else
                          {
                              x.dispatchEvent(
                                  new KeyboardEvent(KeyboardEvent.KEY_DOWN,
                                      keyCodeValue: 37
                                  )
                              );
                          }
                      }
                      else
                      {
                          if (ax > wx)
                          {
                              x.dispatchEvent(
                                 new KeyboardEvent(KeyboardEvent.KEY_UP,
                                     keyCodeValue: 37
                                 )
                             );
                          }
                      }

                      ax = e.accelerationX;
                      az = e.accelerationZ;

                      //t.text = "" + new
                      //{
                      //    //Multitouch.maxTouchPoints,
                      //    ax,
                      //    e.accelerationY,
                      //    e.accelerationZ
                      //};
                  };

                a.setRequestedUpdateInterval(1000 / 60);
            }
            #endregion


        }
        public FlashTowerDefenseSized(int DefaultWidth, int DefaultHeight)
        {

            var bg = new Sprite { x = 0, y = 0 };

            //bg.graphics.beginFill(0xffffff);
            //bg.graphics.beginFill(0x808080);
            //bg.graphics.drawRect(0, 0, Width / 2, Height);



            var warzone = new Sprite { x = 0, y = 0 };

            warzone.graphics.beginFill(ColorWhite);
            warzone.graphics.drawRect(-OffscreenMargin, -OffscreenMargin, DefaultWidth + 2 * OffscreenMargin, DefaultHeight + 2 * OffscreenMargin);

            warzone.mouseChildren = false;


            GetWarzone = () => warzone;

            bg.AttachTo(GetWarzone());
            warzone.AttachTo(this);

            #region create aim
            this.Aim = new Shape();

            Aim.graphics.lineStyle(4, 0, 1);

            Aim.graphics.moveTo(-8, 0);
            Aim.graphics.lineTo(8, 0);

            Aim.graphics.moveTo(0, -8);
            Aim.graphics.lineTo(0, 8);

            Aim.filters = new[] { new DropShadowFilter() };
            Aim.AttachTo(GetWarzone());
            #endregion


            #region BlurWarzoneOnHover
            this.BlurWarzoneOnHover =
                (txt, HideAim) =>
                {


                    txt.mouseOver +=

                        delegate
                        {
                            if (!txt.mouseEnabled)
                                return;

                            txt.textColor = ColorBlue;
                            txt.filters = null;

                            if (CanFire)
                            {
                                warzone.filters = new[] { new BlurFilter() };

                                if (HideAim)
                                    Aim.visible = false;
                            }
                        };

                    txt.mouseOut +=
                        delegate
                        {

                            txt.filters = new[] { new BlurFilter() };
                            txt.textColor = ColorBlack;

                            if (CanFire)
                            {
                                warzone.filters = null;

                                if (HideAim)
                                    Aim.visible = true;
                            }
                        };
                };
            #endregion


            #region ScoreBoard
            var ScoreBoard = new TextField
            {
                x = 24,
                y = 24,

                defaultTextFormat = new TextFormat
                {
                    size = 12
                },
                autoSize = TextFieldAutoSize.LEFT,
                text = "Defend yourself by shooting those mad sheep.",
                filters = new[] { new BlurFilter() },
                selectable = false,
            };

            //ScoreBoard.AttachTo(this);


            BlurWarzoneOnHover(ScoreBoard, true);
            #endregion



            Action<double, Action> Times =
                (m, h) => (DefaultWidth * DefaultHeight * m).Times(h);

            Action<double, Func<BitmapAsset>> AddDoodads =
                (m, GetImage) => Times(m, () => GetImage().AttachTo(bg).SetCenteredPosition(DefaultWidth.Random(), DefaultHeight.Random()));

            AddDoodads(0.0001, () => Images.grass1.ToBitmapAsset());
            AddDoodads(0.00005, () => Images.bump2.ToBitmapAsset());

            Action StartIngameMusic =
                delegate
                {
                    if (this.IngameMusic != null)
                        this.IngameMusic.stop();

                    this.IngameMusic = Sounds.snd_world.ToSoundAsset().play(0, 999, new SoundTransform(IngameMusicVolume));
                };

            StartIngameMusic();

            Func<Animation> AddCactus = () =>
                new Animation(null, Images.img_cactus)
                {
                    FrameRate = 1000 / 7,
                    AnimationEnabled = true
                };




            Action<double> AddCactusAt = y =>
                {
                    var x = DefaultWidth.Random();

                    AddCactus().AttachTo(GetWarzone()).MoveTo(
                        x, y + Math.Cos(x + y) * DefaultHeight * 0.03);
                };

            (3 + 3.Random()).Times(AddCactusAt.FixParam(DefaultHeight * 0.06));
            (3 + 3.Random()).Times(AddCactusAt.FixParam(DefaultHeight * 0.94));

            PrebuiltTurret = new Animation(Images.img_turret1_gunfire_180, Images.img_turret1_gunfire_180_frames);

            PrebuiltTurret.x = (DefaultWidth - PrebuiltTurret.width) * 0.9;
            PrebuiltTurret.y = (DefaultHeight - PrebuiltTurret.height) / 2;

            PrebuiltTurret.AttachTo(GetWarzone());

            #region Messages
            var ActiveMessages = new List<TextField>();
            var ShowMessageNow = default(Action<string, Action>);

            ShowMessageNow =
                (MessageText, Done) =>
                {

                    var p = new TextField
                    {
                        textColor = ColorWhite,
                        background = true,
                        backgroundColor = ColorBlack,
                        filters = new[] { new GlowFilter(ColorBlack) },
                        autoSize = TextFieldAutoSize.LEFT,
                        text = MessageText,
                        mouseEnabled = false
                    };

                    var y = DefaultHeight - p.height - 32;

                    p.AddTo(ActiveMessages).AttachTo(this).MoveTo((DefaultWidth - p.width) / 2, DefaultHeight);

                    Sounds.snd_message.ToSoundAsset().play();

                    var MessagesToBeMoved = (from TheMessage in ActiveMessages select new { TheMessage, y = TheMessage.y - TheMessage.height }).ToArray();



                    (1000 / 24).AtInterval(
                        t =>
                        {
                            foreach (var i in MessagesToBeMoved)
                            {
                                if (i.TheMessage.y > i.y)
                                    i.TheMessage.y -= 4;

                            }

                            p.y -= 4;

                            if (p.y < y)
                            {
                                t.stop();

                                if (Done != null)
                                    Done();

                                9000.AtDelayDo(
                                    () => p.RemoveFrom(ActiveMessages).FadeOutAndOrphanize(1000 / 24, 0.21)
                                );
                            }
                        }
                    );
                };


            var QueuedMessages = new Queue<string>();

            this.ShowMessage =
                Text =>
                {
                    if (QueuedMessages.Count > 0)
                    {
                        QueuedMessages.Enqueue(Text);
                        return;
                    }

                    // not busy
                    QueuedMessages.Enqueue(Text);

                    var NextQueuedMessages = default(Action);

                    NextQueuedMessages =
                        () => ShowMessageNow(QueuedMessages.Peek(),
                            delegate
                            {
                                QueuedMessages.Dequeue();

                                if (QueuedMessages.Count > 0)
                                    NextQueuedMessages();
                            }
                        );

                    NextQueuedMessages();
                };
            #endregion

            var StatusBar = new Sprite
            {
                mouseEnabled = false,
                mouseChildren = false,
            }.MoveTo(DefaultWidth - 96, DefaultHeight - 64).AttachTo(this);



            #region  WeaponBar
            var WeaponBar = new Sprite
            {
            }.AttachTo(StatusBar);


            var AmmoAvatar = new Sprite().MoveTo(38, 24).AttachTo(WeaponBar);

            Images.Avatars.avatars_ammo.ToBitmapAsset().MoveToCenter().AttachTo(AmmoAvatar);

            var AmmoText = new TextField
            {
                defaultTextFormat = new TextFormat
                {
                    bold = true,
                    size = 20,
                    font = "_sans"
                },
                text = "200000",
                filters = new[] { new GlowFilter(ColorBlack, 0.5) },
                autoSize = TextFieldAutoSize.RIGHT,
                x = 0,
                width = 0
            }.AttachTo(AmmoAvatar);




            var WeaponAvatar = new Sprite().AttachTo(WeaponBar);
            #endregion

            var CurrentTarget = default(Point);
            var CurrentTargetTimer = default(Timer);

            #region Ego
            Ego = new PlayerWarrior
                {
                    filters = new[] { new GlowFilter(ColorGreen) }
                };

            EgoIsOnTheField = () => Ego.parent != null;
            EgoIsAlive = () => Ego.IsAlive;

            Func<bool> EgoCanManTurret = () => !PrebuiltTurretInUse; // look up if there is somebody else in it
            Func<bool> EgoIsCloseToTurret = () => new Point { x = Ego.x - PrebuiltTurret.x, y = Ego.y - PrebuiltTurret.y }.length < 32;

            var EgoAimDistance = 48;
            var EgoAimMoveSpeed = 0.1;
            var EgoMoveSpeed = 3.0;
            var EgoMoveToMouseTarget = false;

            UpdateEgoAim =
                delegate
                {
                    Aim.MoveTo(Ego.x + Math.Cos(EgoAimDirection) * EgoAimDistance, Ego.y + Math.Sin(EgoAimDirection) * EgoAimDistance);
                };


            EgoMovedSlowTimer = new Timer(200, 1);

            Ego.FoundNewWeapon +=
                weapon => ShowMessage("You found " + weapon.Name);

            Ego.FoundMoreAmmo +=
                weapon => ShowMessage("Got ammo for " + weapon.Name);



            Action Reorder =
                delegate
                {
#if Z
                    GetWarzone().Children().OrderBy(i => (double)i.y).
                       ForEach(
                        (k, i) =>
                            k.parent.setChildIndex(k, i)
                    );
#endif

                };

            Action ReorderThrottle = Reorder.ThrottleTo(1000);

            var EgoMoveUpTimer = (1000 / 30).AtInterval(
                delegate
                {
                    if (EgoMoveToMouseTarget)
                    {
                        var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };

                        if (p.length <= EgoMoveSpeed)
                        {
                            // run one the pointer
                            return;
                        }

                        Ego.MoveToArc(p.GetRotation(), EgoMoveSpeed);
                    }
                    else
                        Ego.MoveToArc(EgoAimDirection, EgoMoveSpeed);

                    Ego.x = Math.Min(Math.Max(Ego.x, 0), DefaultWidth);
                    Ego.y = Math.Min(Math.Max(Ego.y, 0), DefaultHeight);
                    ReorderThrottle();

                    UpdateEgoAim();

                    EgoMovedSlowTimer.start();

                    // we moved now let's check for boxes
                    foreach (var BoxToTake in
                                     from ss in Boxes
                                     where new Point { x = Ego.x - ss.x, y = Ego.y - ss.y }.length < 32
                                     select ss)
                    {
                        BoxToTake.RemoveFrom(Boxes).Orphanize();

                        Sounds.sound20.ToSoundAsset().play();

                        if (BoxToTake.WeaponInside == null)
                        {
                            // add stuff, so the player doesn't get bored:D
                            // maybe implment them too? see Diablo.
                            var PowerUps = new[] { 
                                // gta
                                "Double Damage", 
                                "Fast Reload", 
                                "Respect",
                                "Armour",

                                // diablo
                                "Defense", 
                                "Mana", 
                                "Dexerity", 
                                "Experience", 
                                "Stamina", 
                                "Strength", 
                                "Life", 
                                "Replenish Life" 
                            };


                            ShowMessage("+1 " + PowerUps.Random());
                        }
                        else
                        {
                            Ego.AddWeapon(BoxToTake.WeaponInside);
                        }

                        if (NetworkTakeCrate != null)
                            NetworkTakeCrate(BoxToTake.NetworkId);
                    }
                });

            EgoMoveUpTimer.stop();

            var EgoAimMoveTimer = (1000 / 30).AtInterval(
                 delegate
                 {
                     EgoAimDirection += EgoAimMoveSpeed * EgoMoveSpeed;

                     if (EgoAimDirection < 0)
                         EgoAimDirection += Math.PI * 4;

                     EgoAimDirection %= Math.PI * 2;

                     UpdateEgoAim();
                 });
            EgoAimMoveTimer.stop();


            #endregion


            Ego.CurrentWeaponChanged +=
                delegate
                {
                    Sounds.SelectWeapon.ToSoundAsset().play();

                    if (WeaponAvatar.numChildren > 0)
                        WeaponAvatar.getChildAt(0).Orphanize();

                    Ego.CurrentWeapon.Type.Avatar.ToBitmapAsset().MoveToCenter().AttachTo(WeaponAvatar);
                    WeaponBar.filters = new[] { new GlowFilter(Ego.CurrentWeapon.Color) };
                };

            Ego.CurrentWeaponAmmoChanged += () => AmmoText.text = "" + Ego.CurrentWeapon.Ammo;

            SetDefaultWeapon();

            Ego.Die +=
                () =>
                {
                    ShowMessage("Meeeediiic!");
                    ShowMessage("You died a painful death");

                    PlayerWarrior.AutoResurrectDelay.AtDelayDo(
                        delegate
                        {
                            Ego.Revive();

                            if (EgoResurrect != null)
                                EgoResurrect();
                        }
                    );
                };

            #region HealthBar
            var HealthBar = new Sprite
            {
                filters = new[] { new GlowFilter(ColorRed) }
            }.MoveTo(-20, 0).AttachTo(StatusBar);

            var Hearts = new[] 
            {
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(20.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(7.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(353.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(340.DegreesToRadians(), 90).AttachTo(HealthBar),
            };

            var EgoHeartBeat = default(SoundChannel);

            Ego.HealthChanged +=
                delegate
                {
                    if (EgoHeartBeat == null)
                    {
                        EgoHeartBeat = Sounds.heartbeat3.ToSoundAsset().play();
                        EgoHeartBeat.soundComplete +=
                            e =>
                            {
                                EgoHeartBeat = null;
                            };
                    }

                    if (Ego.Health > 0)
                    {

                        var z = (Ego.Health / Ego.MaxHealth) * Hearts.Length;
                        var f = Math.Floor(z).ToInt32();
                        var a = z % 1;

                        for (int i = 0; i < f; i++)
                        {
                            Hearts[i].alpha = 1;
                        }

                        if (f < Hearts.Length)
                        {
                            Hearts[f].alpha = a;

                            for (int i = f + 1; i < Hearts.Length; i++)
                            {
                                Hearts[i].alpha = 0;
                            }

                        }
                    }
                    else
                    {
                        for (int i = 0; i < Hearts.Length; i++)
                        {
                            Hearts[i].alpha = 0;
                        }
                    }

                    //ShowMessage("h: " + f + " " + a);
                };

            #endregion

            var PrebuiltTurretSound = default(SoundChannel);

            var runaways = 0;
            var score = 0;

            Action UpdateScoreBoard =
                delegate
                {
                    if (!CanFire) return;

                    ScoreBoard.text =
                        new
                        {
                            runaways,
                            gore = (100 * (double)BadGuys.Count(i => !i.IsAlive) / (double)BadGuys.Count()).Round() + "%",
                            score,
                            level = CurrentLevel
                        }.ToString();
                };

            Action<Point> DoMachineGunFire =
                e =>
                {
                    if (Ego.CurrentWeapon.Ammo <= 0)
                        return;


                    Ego.CurrentWeapon.Ammo--;



                    var DamagePointOfOrigin = new Point { x = PrebuiltTurret.x, y = PrebuiltTurret.y };
                    var DamageDirection = new Point { x = e.x - PrebuiltTurret.x, y = e.y - PrebuiltTurret.y }.GetRotation();

                    DoSomeDamage(DamagePointOfOrigin, DamageDirection, WeaponInfo.Machinegun);

                    if (Ego.CurrentWeapon.Ammo <= 0)
                    {
                        Sounds.OutOfAmmo.ToSoundAsset().play();
                        PrebuiltTurret.AnimationEnabled = false;
                        return;
                    }
                };



            PrebuiltTurret.AnimationEnabledChanged +=
                delegate
                {

                    if (PrebuiltTurret.AnimationEnabled)
                    {
                        if (PrebuiltTurretSound == null)
                            PrebuiltTurretSound = Sounds.gunfire.ToSoundAsset().play(0, 999);

                        PrebuiltTurret.filters = new[] { new GlowFilter() };
                    }
                    else
                    {
                        if (PrebuiltTurretSound != null)
                            PrebuiltTurretSound.stop();

                        PrebuiltTurretSound = null;
                        PrebuiltTurret.filters = null;
                    }

                };

            GetWarzone().mouseDown +=
                e =>
                {
                    if (!CanFire) return;

                    // the turret cannot fire without a man behind it
                    if (EgoIsOnTheField())
                        return;

                    if (Ego.CurrentWeapon.Ammo <= 0)
                    {
                        Sounds.OutOfAmmo.ToSoundAsset().play();
                        return;
                    }


                    PrebuiltTurret.AnimationEnabled = true;

                    var p = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(p);


                    CurrentTargetTimer =
                        (1000 / 10).AtInterval(
                            delegate
                            {
                                if (!PrebuiltTurret.AnimationEnabled)
                                {
                                    CurrentTargetTimer.stop();

                                    return;
                                }

                                DoMachineGunFire(CurrentTarget);
                            }
                        );

                };

            GetWarzone().mouseUp +=
                 e =>
                 {
                     PrebuiltTurret.AnimationEnabled = false;
                 };

            GetWarzone().mouseOut +=
                delegate
                {
                    PrebuiltTurret.AnimationEnabled = false;
                };

            GetWarzone().mouseMove +=
                e =>
                {
                    if (!CanFire)
                        return;

                    var p = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(p);


                    if (EgoIsOnTheField())
                    {
                        Mouse.show();
                        return;
                    }


                    Mouse.hide();

                    Aim.x = CurrentTarget.x;
                    Aim.y = CurrentTarget.y;
                };





            Func<double> GetEntryPointY = () => (DefaultHeight * 0.8).FixedRandom() + DefaultHeight * 0.1;



            #region AttachRules
            Func<Actor, Actor> AttachRules =
                a =>
                {
                    if (a == null)
                        throw new Exception("AttachRules");

                    var an = a;

                    //Console.WriteLine("attached KilledByLocalPlayer");


                    a.KilledByLocalPlayer +=
                        delegate
                        {
                            //Console.WriteLine("KilledByLocalPlayer: " + an.ScoreValue);

                            if (NetworkAddKillScore != null)
                                NetworkAddKillScore(an.ScoreValue);
                        };

                    if (a.NetworkId == 0)
                    {
                        a.NetworkId = int.MaxValue.FixedRandom();

                        if (0.5.ByChance())
                        {
                            a.Crate = new Crate
                                {
                                    NetworkId = int.MaxValue.FixedRandom()
                                }.AddTo(Boxes);

                            if (0.7.ByChance())
                            {
                                // add random weapon, note that this is
                                // not a fixed random, so each player
                                // gets different weapon
                                a.Crate.WeaponInside = Weapon.PredefinedWeapons.Random().Clone();
                            }
                        }
                    }

                    a.CorpseAndBloodGone += () => BadGuys.Remove(a);
                    a.Moved +=
                        delegate
                        {
                            if (a.x > (DefaultWidth + OffscreenMargin))
                            {
                                a.Crate = null;

                                a.RemoveFrom(BadGuys).Orphanize();

                                if (CanFire)
                                {
                                    WaveEndCountdown--;
                                    runaways++;

                                    ScoreBoard.textColor = ColorRed;
                                    UpdateScoreBoard();
                                }

                                a.IsAlive = false;
                                // this one was able to run away
                            }
                        };





                    a.Die +=
                        delegate
                        {
                            WaveEndCountdown--;

                            score += a.ScoreValue;
                            UpdateScoreBoard();


                            if (a.Crate != null)
                            {
                                a.Crate.MoveTo(a.x, a.y).AttachTo(GetWarzone());
                            }
                        };

                    a.AttachTo(GetWarzone()).AddTo(BadGuys);

                    if (a.PlayHelloSound != null)
                        a.PlayHelloSound();

                    return a;
                };
            #endregion

            Action EgoTakeNextWeapon = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.Next(i => i == Ego.CurrentWeapon);
            Action EgoTakePreviousWeapon = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.Previous(i => i == Ego.CurrentWeapon);






            GetWarzone().mouseWheel +=
                e =>
                {
                    if (e.delta > 0)
                        EgoTakeNextWeapon();
                    else
                        EgoTakePreviousWeapon();
                };

            var EgoMoveToMouseTargetAntiDoubleClick = default(Timer);

            GetWarzone().mouseDown +=
                e =>
                {
                    if (!EgoIsOnTheField())
                        return;

                    if (!EgoIsAlive())
                        return;

                    var pp = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(pp);

                    var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };

                    EgoAimDirection = p.GetRotation();



                    UpdateEgoAim();

                    EgoMoveToMouseTarget = true;

                    EgoMoveToMouseTargetAntiDoubleClick =
                        200.AtDelayDo(
                        delegate
                        {
                            if (!EgoIsAlive())
                            {
                                Ego.RunAnimation = false;
                                EgoMoveUpTimer.stop();
                                return;
                            }

                            if (!EgoMoveToMouseTarget)
                                return;

                            Ego.RunAnimation = true;
                            EgoMoveSpeed = 2.5;
                            EgoMoveUpTimer.start();
                        }
                    );
                };


            GetWarzone().mouseMove +=
                e =>
                {
                    if (!EgoMoveToMouseTarget)
                        return;

                    if (!EgoIsOnTheField())
                        return;

                    if (!EgoIsAlive())
                        return;

                    var pp = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(pp);

                    var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };


                    EgoAimDirection = p.GetRotation();


                    UpdateEgoAim();
                };

            GetWarzone().mouseUp +=
                e =>
                {
                    if (!EgoMoveToMouseTarget)
                        return;

                    if (!EgoIsAlive())
                        return;

                    if (EgoMoveToMouseTargetAntiDoubleClick != null)
                    {
                        EgoMoveToMouseTargetAntiDoubleClick.stop();
                        EgoMoveToMouseTargetAntiDoubleClick = null;
                    }

                    EgoMoveUpTimer.stop();
                    Ego.RunAnimation = false;
                    EgoMoveToMouseTarget = false;
                };

            GetWarzone().doubleClickEnabled = true;
            GetWarzone().doubleClick +=
              e =>
              {
                  if (!EgoIsOnTheField())
                      return;

                  if (!EgoIsAlive())
                      return;

                  var pp = new Point
                  {
                      x = e.stageX,
                      y = e.stageY,
                  };

                  CurrentTarget = this.globalToLocal(pp);


                  EgoAimDirection = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y }.GetRotation();

                  UpdateEgoAim();

                  EgoDoFireWeapon();
              };

            Action StageIsReady =
                delegate
                {

                    //stage.scaleMode = StageScaleMode.NO_BORDER;

                    // multiplay ?


                    var WeaponShortcutButtons = new[]
                    {
                        Keyboard.NUMBER_1,
                        Keyboard.NUMBER_2,
                        Keyboard.NUMBER_3,
                        Keyboard.NUMBER_4,
                        Keyboard.NUMBER_5,
                        Keyboard.NUMBER_6,
                        Keyboard.NUMBER_7,
                        Keyboard.NUMBER_8,
                        Keyboard.NUMBER_9,
                        Keyboard.NUMBER_0,
                    }.Select(
                        (Button, Index) =>
                            new KeyboardButton(stage)
                            {
                                Buttons = new[] { Button },
                                Filter = EgoIsAlive,
                                Up = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.AtOrDefault(Index, Ego.CurrentWeapon)
                            }
                    ).ToArray();

                    var KeySpace = new KeyboardButton(stage)
                     {
                         Buttons = new[] { Keyboard.SPACE },
                         Filter = EgoIsOnTheField.And(EgoIsAlive),
                         Up =
                             delegate
                             {
                                 // car brakes, open door, take item

                                 // Add Ammo

                                 foreach (var BarrelToTake in this.Barrels.Where(i => (i.ToPoint() - Ego.ToPoint()).length < 32))
                                 {
                                     Sounds.sound20.ToSoundAsset().play();
                                     Ego.AddWeapon(BarrelToTake.ExplosiveMaterialType);
                                     BarrelToTake.RemoveFrom(Barrels).Orphanize();

                                     if (NetworkUndeployExplosiveBarrel != null)
                                         NetworkUndeployExplosiveBarrel(BarrelToTake.NetworkId);

                                 }
                             }
                     };


                    var KeyLeft = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.A],
                            MovementArrows[Keyboard.LEFT],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                EgoAimMoveSpeed = -0.1;
                                EgoAimMoveTimer.start();
                            },
                        Up = EgoAimMoveTimer.stop,
                    };

                    var KeyRight = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.D],
                            MovementArrows[Keyboard.RIGHT],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                EgoAimMoveSpeed = +0.1;
                                EgoAimMoveTimer.start();
                            },
                        Up = EgoAimMoveTimer.stop,
                    };

                    var KeyUp = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.W],
                            MovementArrows[Keyboard.UP],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                if (!Ego.IsAlive)
                                    return;

                                Ego.RunAnimation = true;
                                EgoMoveSpeed = 2.5;
                                EgoMoveUpTimer.start();
                            },
                        Up =
                            delegate
                            {
                                EgoMoveUpTimer.stop();
                                Ego.RunAnimation = false;
                            }
                    };

                    var KeyDown = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.S],
                            MovementArrows[Keyboard.DOWN],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                if (!Ego.IsAlive)
                                    return;

                                Ego.RunAnimation = true;
                                EgoMoveSpeed = -1.5;
                                EgoMoveUpTimer.start();
                            },
                        Up =
                            delegate
                            {
                                EgoMoveSpeed = 1;
                                EgoMoveUpTimer.stop();
                                Ego.RunAnimation = false;
                            }
                    };

                    var KeyWeaponNext = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.X],
                            MovementArrows[Keyboard.PAGE_UP],
                        },

                        Up = EgoTakeNextWeapon,
                    };

                    var KeyWeaponPrevious = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.Z],
                            MovementArrows[Keyboard.PAGE_DOWN],
                        },
                        Up = EgoTakePreviousWeapon
                    };

                    var KeyControl = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[ new KeyboardKeyInfo { Button = Keyboard.CONTROL, Location = KeyLocation.LEFT } ],
                            MovementArrows[ new KeyboardKeyInfo { Button = Keyboard.CONTROL, Location = KeyLocation.RIGHT  } ],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Up = EgoDoFireWeapon
                    };


                    var KeyMusic = new KeyboardButton(stage)
                    {
                        Buttons = new[] { Keyboard.M },
                        Up = () => ToggleMusic()
                    };




                    var KeyEnter = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.F],
                            MovementArrows[Keyboard.ENTER],
                        },
                        Filter = EgoIsAlive,
                        Up =
                            delegate
                            {
                                if (EgoIsOnTheField())
                                {
                                    if (EgoIsCloseToTurret())
                                    {
                                        if (EgoCanManTurret())
                                        {


                                            Ego.Orphanize();
                                            Ego.RunAnimation = false;
                                            EgoMoveUpTimer.stop();
                                            EgoAimMoveTimer.stop();
                                            PrebuiltTurretBlinkTimer.stop();
                                            PrebuiltTurret.alpha = 1;

                                            Ego.CurrentWeapon = Ego.Weapons.FirstOrDefault(i => i.SelectMode == Weapon.SelectModeEnum.Turret);

                                            ShowMessage("Machinegun manned!");
                                            Mouse.hide();

                                            if (CurrentTarget != null)
                                            {
                                                Aim.x = CurrentTarget.x;
                                                Aim.y = CurrentTarget.y;
                                            }

                                            Sounds.door_open.ToSoundAsset().play();

                                            if (EgoEnteredMachineGun != null)
                                                EgoEnteredMachineGun();
                                        }
                                        else
                                        {
                                            ShowMessage("Cannot man the machinegun!");
                                        }
                                    }
                                    else
                                    {
                                        ShowMessage("The machinegun is too far! Get closer!");
                                    }
                                }
                                else
                                {
                                    Sounds.door_open.ToSoundAsset().play();


                                    ShowMessage("Machinegun unmanned!");

                                    TeleportEgoNearTurret();
                                    PrebuiltTurret.AnimationEnabled = false;

                                    PrebuiltTurret.alpha = 0.5;
                                    Mouse.show();
                                    PrebuiltTurretBlinkTimer.start();



                                    if (EgoExitedMachineGun != null)
                                        EgoExitedMachineGun();
                                }
                            }
                    };



                };

            PrebuiltTurretBlinkTimer = 500.AtInterval(t => PrebuiltTurret.alpha = ((t.currentCount % 2) + 1) / 2);
            PrebuiltTurretBlinkTimer.stop();

            #region readiness
            if (stage == null)
            {
                this.addedToStage +=
                    delegate
                    {
                        StageIsReady();
                    };
            }
            else
            {
                StageIsReady();
            }
            #endregion

            //Mouse.hide();



            ShowMessage("Aim at the enemy unit and hold down the mouse!");
            ShowMessage("Press 'Enter' to exit the machinegun");
            //ShowMessage("Day " + CurrentLevel);

            GameEvent =
                delegate
                {
                    // do not add if the day is over...
                    //if (WaveEndCountdown <= 0)
                    //    return;

                    AddNewActorsToMap(UpdateScoreBoard, GetEntryPointY, AttachRules);

                };




            ReportDays =
                delegate
                {
                    if (WaveEndCountdown < 0)
                    {
                        if (InterlevelMusic == null)
                        {
                            InterlevelMusic = Sounds.snd_birds.ToSoundAsset().play(0, 999);
                            ShowMessage("Day " + CurrentLevel + " is ending...");

                            if (GameInterlevelBegin != null)
                                GameInterlevelBegin();
                        }

                        if (WaveEndsWhenAllBadGuysAreDead)
                        {
                            // wait for all actors get off stage
                            if (BadGuys.Where(i => i.IsAlive).Any())
                                return;
                        }


                        // show "level END"
                        ShowMessage("Day " + CurrentLevel + " Survived!");

                        ReportDaysTimer.stop();



                        InterlevelTimeout.AtDelayDo(
                            delegate
                            {
                                if (GameInterlevelEnd != null)
                                    GameInterlevelEnd();


                                // maybe higher levels will have more enemies?
                                WaveEndCountdown = 15;
                                CurrentLevel++;

                                // show "level START"
                                ShowMessage("Day " + CurrentLevel);
                                ReportDaysTimer.start();

                                var InterlevelMusicStopping = InterlevelMusic;
                                InterlevelMusic = null;
                                2000.AtDelayDoOnRandom(InterlevelMusicStopping.stop);
                            }
                        );


                        UpdateScoreBoard();

                        return;
                    }


                    if (CanAutoSpawnEnemies)
                    {
                        // new actors if we got less 10 
                        if (InterlevelMusic != null)
                            return;

                        if (BadGuys.Where(i => i.IsAlive).Count() < 8)
                        {

                            GameEvent();
                        }
                    }
                };

            ReportDaysTimer = 1500.AtIntervalDo(ReportDays);


            (1000 / 15).AtInterval(
                delegate
                {


                    Aim.rotation += 1;

                    foreach (var s in
                           from ss in BadGuys
                           where ss.IsAlive
                           select ss)
                        s.x += s.speed;
                }
            );

            //#region powered_by_jsc
            //var powered_by_jsc = new TextField
            //{

            //    x = 32,

            //    defaultTextFormat = new TextFormat
            //    {
            //        size = 24
            //    },
            //    autoSize = TextFieldAutoSize.LEFT,

            //    // how to make a link
            //    // http://www.actionscript.com/Article/tabid/54/ArticleID/actionscript-quick-tips-and-gotchas/Default.aspx
            //    htmlText = "<a href='http://jsc.sf.net' target='_blank'>powered by <b>jsc</b></a>",
            //    selectable = false,
            //    filters = new[] { new BlurFilter() },
            //    textColor = ColorBlack
            //}.AttachTo(this);

            //powered_by_jsc.y = DefaultHeight - powered_by_jsc.height - 32;

            //// make it fade/show in time
            //200.AtInterval(t => 
            //    {
            //        var a = (Math.Sin(t.currentCount * 0.05) + 1) * 0.5;

            //        powered_by_jsc.alpha = a;
            //        powered_by_jsc.mouseEnabled = a > 0.8;
            //    }
            //);

            //#endregion

            ScoreBoard.AttachTo(this);

            //BlurWarzoneOnHover(powered_by_jsc, true);

            40000.AtIntervalOnRandom(
                delegate
                {
                    Sounds.snd_bird2.ToSoundAsset().play();
                }
            );


            #region music on off
            var MusicButton = new Sprite
            {
                x = DefaultWidth - 32,
                y = 32,
                filters = new[] { new GlowFilter(ColorBlueLight) },

            };

            var MusicOn = Images.music_on.ToBitmapAsset().MoveToCenter();
            var MusicOff = Images.music_off.ToBitmapAsset().MoveToCenter();

            MusicButton.mouseOver +=
                delegate
                {
                    Mouse.show();
                    Aim.visible = false;
                };

            MusicButton.mouseOut +=
              delegate
              {
                  Mouse.hide();
                  Aim.visible = true;
              };

            ToggleMusic =
                delegate
                {
                    if (MusicOn.parent == MusicButton)
                    {
                        MusicOn.Orphanize();
                        MusicOff.AttachTo(MusicButton);
                        ShowMessage("Music silenced");
                        IngameMusic.soundTransform = new SoundTransform(0);
                    }
                    else
                    {
                        IngameMusic.soundTransform = new SoundTransform(IngameMusicVolume);
                        ShowMessage("Music activated");

                        MusicOff.Orphanize();
                        MusicOn.AttachTo(MusicButton);
                    }
                };

            MusicButton.click +=
                delegate
                {
                    ToggleMusic();
                };

            MusicOn.AttachTo(MusicButton);

            MusicButton.AttachTo(this);
            #endregion

            Action<InteractiveObject, InteractiveObject> OnMouseDownDisableMouseOnTarget =
                (subject, target) =>
                {
                    subject.mouseDown += delegate { target.mouseEnabled = false; };
                    subject.mouseUp += delegate { target.mouseEnabled = true; };
                };

            OnMouseDownDisableMouseOnTarget(GetWarzone(), MusicButton);
            OnMouseDownDisableMouseOnTarget(GetWarzone(), ScoreBoard);
            //OnMouseDownDisableMouseOnTarget(GetWarzone(), powered_by_jsc);
        }
		public FlashSoundFileExample()
		{
			var m = new MemoryStream();
			var ba = new BinaryWriter(m);
			var d = 1.0/44100.0;
			var g = 1.0;

			foreach (int _i in Enumerable.Range(0, 44100))
			{
				var i = 44100 - _i;

				var f = ((Math.Sin(i * Math.PI / 10) + 1.0) / 2.0) * 0.5 +
							  ((Math.Sin((i + 1000) * Math.PI / 20) + 1.0) / 2.0) * 0.5 +
							  ((Math.Sin((i + 2000) * Math.PI / 40) + 1.0) / 2.0) * 0.5;

				f = f * (1.0 - (d * i));
				if (f > 1) f = 1; else if (f < 0) f = 0;
				ba.Write(Convert.ToByte(255.0 * f));
			}


	        
			foreach (int i in Enumerable.Range(0, 44100))
			{
				var f = ((Math.Sin(i*Math.PI/10) + 1.0)/2.0)*0.5 +
							  ((Math.Sin((i+1000)*Math.PI/20) + 1.0)/2.0)*0.5 +
							  ((Math.Sin((i+2000)*Math.PI/40) + 1.0)/2.0)*0.5;
	            
				f = f*(1.0-(d*i));
				if (f > 1) f=1; else if (f < 0) f=0;
				ba.Write(Convert.ToByte(255.0*f));
			}

			foreach (int _i in Enumerable.Range(0, 44100))
			{
				var i = 44100 - _i;

				var f = ((Math.Sin(i * Math.PI / 10) + 1.0) / 2.0) * 0.5 +
							  ((Math.Sin((i + 1000) * Math.PI / 20) + 1.0) / 2.0) * 0.5 +
							  ((Math.Sin((i + 2000) * Math.PI / 40) + 1.0) / 2.0) * 0.5;

				f = f * (1.0 - (d * i));
				if (f > 1) f = 1; else if (f < 0) f = 0;
				ba.Write(Convert.ToByte(255.0 * f));
			}

		

			//trace("Playing the wave...");
			DynSound.playSound(m);
			//trace("Done");
	        
			var spr  = new  Sprite();
			spr.graphics.beginFill(0x00CCFF);
			spr.graphics.drawRect(0, 100, 512, 184);
			spr.graphics.endFill();
	        
			spr.AttachTo(this);

			spr.click +=
				delegate
				{
					DynSound.playSound(m);
				};

		}
        public ApplicationSprite()
        {
            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            #region bg fill
            var fill = new Sprite().AttachTo(this);

            fill.graphics.beginFill(0xA26D41);
            fill.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);

            this.stage.resize +=
                delegate
                {
                    fill.graphics.beginFill(0xA26D41);
                    fill.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);
                };
            #endregion

            var egocenter = new Sprite();
            var egorotation = new Sprite().AttachTo(egocenter);

            var map = new Sprite().AttachTo(egorotation);

            map.graphics.beginFill(0xB27D51);
            map.graphics.drawRect(0, 0, 4000, 400);


            // http://wiki.openoffice.org/wiki/SVG_User_Experiences
            //Enclosed Exception:
            //The current document is unable to create an element of the requested type (namespace: http://www.w3.org/2000/svg, name: flowRoot).

            //        [Embed(source = "/assets/FlashHeatZeeker/touchdown.svg", mimeType = "image/svg-xml")]
            //        ^

            //U:\web\FlashHeatZeeker\ApplicationSprite.as(104): col: 9: Error: Unable to transcode /assets/FlashHeatZeeker/touchdown.svg.



            KnownEmbeddedResources.Default["assets/FlashHeatZeeker/touchdown.svg"].ToSprite().AttachTo(map).MoveTo(100, 0).With(
                svg =>
                {
                    svg.scaleX = 0.5;
                    svg.scaleY = 0.5;
                }
            );


            // unit 1

            Func<GameUnit> greentank = delegate
            {
                var unit1_loc = new Sprite().AttachTo(map);
                var unit1_rot = new Sprite().AttachTo(unit1_loc);

                KnownEmbeddedResources.Default["assets/FlashHeatZeeker/greentank.svg"].ToSprite().AttachTo(unit1_rot).MoveTo(-200, -200);

                return new GameUnit { loc = unit1_loc, rot = unit1_rot };
            };

            var unit1 = greentank();
            var unit2 = greentank();
            var unit3 = greentank();

            unit1.loc.MoveTo(300, 200);
            unit2.loc.MoveTo(0, 400);

            var CurrentUnit = unit1;



            KnownEmbeddedResources.Default["assets/FlashHeatZeeker/hill0.svg"].ToSprite().AttachTo(map).MoveTo(0, 0).With(
                svg =>
                {
                    svg.scaleX = 0.2;
                    svg.scaleY = 0.2;
                }
            );

            for (int iy = 0; iy < 128; iy++)
            {
                KnownEmbeddedResources.Default["assets/FlashHeatZeeker/tree0.svg"].ToSprite().AttachTo(map).MoveTo(400, 0).With(
                    svg =>
                    {
                        svg.cacheAsBitmap = true;

                        svg.scaleX = 0.2;
                        svg.scaleY = 0.2;

                        if (iy % 3 == 0)
                            svg.y += 50;

                        if (iy % 3 == 1)
                            svg.y += 100;


                        svg.x += 15 * iy;
                    }
                );
            }

            for (int iy = 0; iy < 128; iy++)
            {
                KnownEmbeddedResources.Default["assets/FlashHeatZeeker/tree0.svg"].ToSprite().AttachTo(map).MoveTo(400, 0).With(
                    svg =>
                    {
                        svg.y += 300;

                        svg.cacheAsBitmap = true;

                        svg.scaleX = 0.2;
                        svg.scaleY = 0.2;

                        if (iy % 3 == 0)
                            svg.y += 50;

                        if (iy % 3 == 1)
                            svg.y += 100;


                        svg.x += 15 * iy;
                    }
                );
            }



            // ego is in center
            map.MoveTo(-300, -200);

            this.stage.keyUp +=
                e =>
                {

                    //Console.WriteLine("keyUp " + new { e.keyCode });

                    if (e.keyCode == (uint)System.Windows.Forms.Keys.D3)
                    {
                        CurrentUnit = unit3;
                        egorotation.rotation = -CurrentUnit.rot.rotation;
                        map.MoveTo(-CurrentUnit.loc.x, -CurrentUnit.loc.y);
                    }

                    if (e.keyCode == (uint)System.Windows.Forms.Keys.D1)
                    {
                        CurrentUnit = unit1;
                        egorotation.rotation = -CurrentUnit.rot.rotation;
                        map.MoveTo(-CurrentUnit.loc.x, -CurrentUnit.loc.y);
                    }

                    if (e.keyCode == (uint)System.Windows.Forms.Keys.D2)
                    {
                        CurrentUnit = unit2;
                        egorotation.rotation = -CurrentUnit.rot.rotation;
                        map.MoveTo(-CurrentUnit.loc.x, -CurrentUnit.loc.y);
                    }


                    if (e.keyCode == (uint)System.Windows.Forms.Keys.F11)
                    {
                        this.stage.SetFullscreen(true);
                    }
                };

            this.stage.keyDown +=
              e =>
              {
                  //Console.WriteLine("keyDown " + new { e.keyCode });

                  if (e.keyCode == (uint)System.Windows.Forms.Keys.Up)
                  {
                      CurrentUnit.loc.x += 2 * Math.Cos((CurrentUnit.rot.rotation + 270).DegreesToRadians());
                      CurrentUnit.loc.y += 2 * Math.Sin((CurrentUnit.rot.rotation + 270).DegreesToRadians());
                  }

                  if (e.keyCode == (uint)System.Windows.Forms.Keys.Down)
                  {
                      CurrentUnit.loc.x += -2 * Math.Cos((CurrentUnit.rot.rotation + 270).DegreesToRadians());
                      CurrentUnit.loc.y += -2 * Math.Sin((CurrentUnit.rot.rotation + 270).DegreesToRadians());
                  }

                  if (e.keyCode == (uint)System.Windows.Forms.Keys.Left)
                  {
                      CurrentUnit.rot.rotation -= 5;
                  }

                  if (e.keyCode == (uint)System.Windows.Forms.Keys.Right)
                  {
                      CurrentUnit.rot.rotation += 5;
                  }


                  egorotation.rotation = -CurrentUnit.rot.rotation;
                  map.MoveTo(-CurrentUnit.loc.x, -CurrentUnit.loc.y);
              };

            #region egocrosshair
            var egocrosshair = new Sprite().AttachTo(egocenter);

            egocrosshair.graphics.lineStyle(2, 0x007f00, 1);

            egocrosshair.graphics.moveTo(-32, 0);
            egocrosshair.graphics.lineTo(32, 0);


            egocrosshair.graphics.moveTo(0, -32);
            egocrosshair.graphics.lineTo(0, 32);
            #endregion

            egocenter.AttachTo(this);



            egocenter.MoveTo(this.stage.stageWidth / 2, this.stage.stageHeight / 2);
            this.stage.resize +=
               delegate
               {
                   egocenter.MoveTo(this.stage.stageWidth / 2, this.stage.stageHeight / 2);
               };


            #region AtInitializeConsoleFormWriter
            this.AtInitializeConsoleFormWriter = (
                Action<string> Console_Write,
                Action<string> Console_WriteLine
            ) =>
            {

                try
                {
                    var w = new __OutWriter();

                    var o = Console.Out;

                    var __reentry = false;

                    w.AtWrite =
                        x =>
                        {
                            o.Write(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_Write(x);
                                __reentry = false;
                            }
                        };

                    w.AtWriteLine =
                        x =>
                        {
                            o.WriteLine(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_WriteLine(x);
                                __reentry = false;
                            }
                        };

                    Console.SetOut(w);

                    Console.WriteLine("flash Console.WriteLine should now appear in JavaScript form!");
                }
                catch
                {

                }
            };
            #endregion

            var info = new TextField
            {
                selectable = false,
                mouseEnabled = false,
                autoSize = TextFieldAutoSize.LEFT
            }.AttachTo(this).MoveTo(8, 8);


            var maxframe = new Stopwatch();
            var maxframe_elapsed = 0.0;

            #region fps
            var sw = new Stopwatch();

            sw.Start();

            var ii = 0;

            maxframe.Start();
            this.enterFrame +=
                delegate
                {
                    maxframe.Stop();

                    //                    System.TimeSpan for Boolean op_GreaterThan(System.TimeSpan, System.TimeSpan) used at
                    //FlashHeatZeeker.ApplicationSprite+<>c__DisplayClass11.<.ctor>b__d at offset 001e.

                    //                TypeError: Error #1009: Cannot access a property or method of a null object reference.
                    //at FlashHeatZeeker::ApplicationSprite___c__DisplayClass11/__ctor_b__d_100663322()[U:\web\FlashHeatZeeker\ApplicationSprite___c__DisplayClass11.as:141]

                    if (maxframe.Elapsed.TotalMilliseconds > maxframe_elapsed)
                        maxframe_elapsed = maxframe.Elapsed.TotalMilliseconds;

                    if (sw.ElapsedMilliseconds < 1000)
                    {
                        ii++;

                        maxframe.Restart();

                        return;
                    }

                    info.text = new { fps = ii, maxframe_elapsed }.ToString();

                    //if (fps != null)
                    //    fps("" + ii);

                    ii = 0;
                    maxframe_elapsed = 0;
                    sw.Restart();
                };
            #endregion

        }
Ejemplo n.º 11
0
        private void SpawnSheep(int offsetx, int offsety)
        {
            var sheep = new[]
                {
                    sheep1.ToBitmapAsset(),
                    sheep2.ToBitmapAsset(),
                    sheep3.ToBitmapAsset(),
                    sheep4.ToBitmapAsset()
                };


            var f = new[] { new GlowFilter() };
            var circle2 = new Sprite();



            circle2.click += sound1.ToSoundAsset().ToMouseEvent();

            circle2.mouseOver +=
                delegate
                {
                    for (int i = 0; i < sheep.Length; i++)
                    {
                        var v = sheep[i];
                        sheep[i].filters = f;
                    }
                };

            circle2.mouseOut +=
              delegate
              {
                  for (int i = 0; i < sheep.Length; i++)
                  {
                      var v = sheep[i];
                      sheep[i].filters = null;
                  }
              };



            circle2.graphics.beginFill(0xFFCC00, 0.0);
            circle2.graphics.drawRect(0, 0, 64, 64);

            circle2.AttachTo(this);

            (1000 / 15).AtInterval(
                t =>
                {
                    circle2.x = ((t.currentCount + offsetx + g_offsetx) % stage.stageWidth) - 32;
                    circle2.y = ((offsety + g_offsety) % stage.stageHeight) - 32;

                    for (int i = 0; i < sheep.Length; i++)
                    {
                        var v = sheep[i];



                        if (t.currentCount % sheep.Length == i)
                            v.AttachTo(circle2);
                        else
                            v.Dipsose();
                    }
                }
            );
        }
Ejemplo n.º 12
0
        public const uint ForegroundColor = 0x202020;//(uint)(0xffffff ^ BackgroundColor);

        /// <summary>
        /// Default constructor
        /// </summary>
        public FlashZIndex()
        {
            var c = new Sprite
            {
            };


            //c.graphics.beginFill(BackgroundColor);
            //c.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
            //c.graphics.endFill();

            Func<string, string, string> ToSize =
                (e, size) => "<font size='" + size + "'>" + e + "</font>";

            Func<string, string, string> ToColor =
                (e, color) => "<font color='#" + color + "'>" + e + "</font>";

            var keywords = new[] { "from", "this", " in", "orderby", " is", " descending", "select" };

            Func<string, string> Colorize =
                e =>
                {
                    foreach (var keyword in keywords.OrderByDescending(i => i.Length))
                    {
                        e = e.Replace(keyword, ToColor(keyword, "0000ff"));
                    }

                    return e;
                };

            var t = new TextField
            {
                autoSize = TextFieldAutoSize.LEFT,
                defaultTextFormat = new TextFormat
                {
                    size = 15,
                    color = ForegroundColor
                },
                mouseEnabled = false,
                filters = new[] { new DropShadowFilter() },
                multiline = true,
                condenseWhite = true,
                x = 8,
           
                htmlText =

                Colorize(

                    ToSize("flash zIndex example powered by <b>jsc</b>", "24") + "<br />"
                    + @"click on the background to create<br /> or drag to see zIndex in effect<br /><br />"
                    + ToColor(@"
                        from v in this.Children() <br />
                        orderby v is TextField descending, v.y, v.x <br />
                        select v
                    ", "000000")
                )
            };

            c.AttachTo(this);
            t.AttachTo(this);

            c.doubleClickEnabled = true;

            Action Reorder =
                delegate
                {
                    Action<DisplayObject, int> SetZIndex =
                        (k, i) => k.parent.setChildIndex(k, i);

                    SetZIndex.ForEach(
                        from v in this.GetChildren()
                        orderby v is TextField descending, v.y, v.x
                        select v
                    );



                };

            Action ReorderThrottle = Reorder.ThrottleTo(500);

            c.click +=
                q =>
                {
                    var x = q.stageX;
                    var y = q.stageY;

                    AddSprite(ReorderThrottle, x, y);

                    ReorderThrottle();
                };

            10.To(90)(i => AddSprite(
                ReorderThrottle, 
                stage.stageWidth * i / 100, 
                stage.stageHeight.Random(0.6, 0.9)
                )
                );

            Reorder();
        }
		private void Initialize()
		{
			Canvas = new Sprite();

			//s.bitmapData.setPixel(1, 1, ColorGreen);
			Canvas.scaleX = DefaultZoom;
			Canvas.scaleY = DefaultZoom;

			Canvas.graphics.beginFill(ColorBlack);
			Canvas.graphics.drawRect(0, 0, RoomWidth, RoomHeight);


			Canvas.AttachTo(this);

			// add scull ani here
			// add status text here

			//var Status = new TextField { autoSize = TextFieldAutoSize.LEFT, textColor = 0xffffff }.AttachTo(this);

			Func<Point> GetRandomLocation =
				() => new Point
				{
					x = (RoomWidth - 1).Random(),
					y = (RoomHeight - 1).Random()
				};



			Func<Apple> CreateApple =
				   () => new Apple
				   {
					   GetRandomLocation = GetRandomLocation,
					   Wrapper = Wrapper
				   }.MoveToRandomLocation();


			AddApples = delegate
			{
				20.Times(() =>
					CreateApple().AttachTo(Canvas).AddTo(Apples)
				);
			};

			AddApples();

			Ego = new Worm
			{
				Wrapper = Wrapper,
				Location = GetRandomLocation(),
				Canvas = Canvas,
				Vector = Worm.VectorRight
				// Color = game_colors.worm.active
			}
			.AddTo(Worms)
			 .Grow();
			//.GrowToVector()
			//.GrowToVector();



			#region keyboard

			MovementWASD = new KeyboardButtonGroup { Name = "WASD" };
			MovementArrows = new KeyboardButtonGroup { Name = "Arrows" };

			var GoLeft = new KeyboardButton(stage)
			{
				Groups = new[]
                {
                    MovementWASD[Keyboard.A],
                    MovementArrows[Keyboard.LEFT],
                },
				Up = () => { Ego.Vector = Worm.VectorLeft; },
			}.Up;

			var GoRight = new KeyboardButton(stage)
			{
				Groups = new[]
                {
                    MovementWASD[Keyboard.D],
                    MovementArrows[Keyboard.RIGHT],
                },
				Up = () => { Ego.Vector = Worm.VectorRight; },
			}.Up;

			var GoUp = new KeyboardButton(stage)
			{
				Groups = new[]
                {
                    MovementWASD[Keyboard.W],
                    MovementArrows[Keyboard.UP],
                },
				Up = () => { Ego.Vector = Worm.VectorUp; },
			}.Up;

			var GoDown = new KeyboardButton(stage)
			{
				Groups = new[]
                {
                    MovementWASD[Keyboard.S],
                    MovementArrows[Keyboard.DOWN],
                },
				Up = () => { Ego.Vector = Worm.VectorDown; },

			}.Up;

			#endregion

			Ego.VectorChanged +=
				delegate
				{
					Sounds.flag.ToSoundAsset().play();
				};
			//var info = new TextField
			//{
			//    textColor = 0xffffff,
			//    autoSize = TextFieldAutoSize.LEFT,
			//}.AttachTo(this);

			Action<MouseEvent> Go =

				e =>
				{
					#region Diaww
					var x = e.stageX;
					var y = e.stageY;


					var A = x > y;
					var B = x > (stage.height - y);

					var DiaClipLeft = !A && !B;
					var DiaClipRight = A && B;
					var DiaClipTop = A && !B;
					var DiaClipBottom = !A && B;
					#endregion

					//info.text = new { e.stageX, stage.width, e.stageY }.ToString();

					if (DiaClipLeft) GoLeft();
					else if (DiaClipRight) GoRight();
					else if (DiaClipTop) GoUp();
					else if (DiaClipBottom) GoDown();
				};

			stage.click += Go;
			stage.mouseMove +=
				e =>
				{
					if (e.buttonDown) Go(e);
				};


			Sounds.reveal.ToSoundAsset().play();

			(1000 / 20).AtInterval(
			   t =>
			   {
				   foreach (var p in Worms)
				   {
					   var worm = p;

					   if (Apples.Count > 0)
						   if (worm.IsAlive)
						   {

							   //Status.text = "";


							   worm.GrowToVector();

							   if (worm.ThisNetworkInstanceCannotEat)
							   {
								   worm.Shrink();
							   }
							   else
							   {
								   // is there a worm smaller than us that we can eat?
								   if (worm.Parts.Count > 1)
								   {
									   var OtherWorms = Worms.Where(k => k != worm).ToArray();



									   //Status.appendText("others: " + OtherWorms.Length);

									   var ToBeEaten = OtherWorms.FirstOrDefault(k => k.Parts.Any(i => i.Location.IsEqual(worm.NextLocation) || i.Location.IsEqual(worm.Location)));

									   if (ToBeEaten != null)
									   {


										   if (ToBeEaten.IsAlive)
										   {
											   if (ToBeEaten.Parts.Count < worm.Parts.Count)
											   {
												   ToBeEaten.Color = 0x8f8f8f;

												   worm.EatThisWormSoon(ToBeEaten);
											   }
											   else
											   {
												   //Status.appendText(" target not smaller");
											   }
										   }
										   else
										   {
											   //Status.appendText(" target not alive");
										   }


									   }
									   else
									   {
										   //Status.appendText(" noone in range");
									   }
								   }

								   // did we find an apple?
								   var a = Apples.Where(i => i.Location.IsEqual(worm.Location)).ToArray();

								   if (a.Length > 0)
								   {
									   foreach (var v in a)
									   {
										   v.Control.Orphanize();
										   Apples.Remove(v);

										   if (worm.HasEatenAnApple != null)
											   worm.HasEatenAnApple(v);
									   }

									   Sounds.sound20.ToSoundAsset().play();
									   // AddScore(1);
								   }
								   else
								   {
									   worm.Shrink();
								   }
							   }
						   }
				   }



			   }
			);
		}