private Sprite getCircle(uint circumference = 40)
 {
     var circle = new Sprite();
     circle.graphics.beginFill(0x1695A3);
     circle.graphics.drawCircle(0, 0, circumference);
     return circle;
 }
        private void drawImage(Event e)
        {

            var mySprite = new Sprite();
            var myBitmap = new BitmapData((int)loader.width, (int)loader.height, false);

            myBitmap.draw(loader, new Matrix());


            Action<Matrix> update =
                matrix =>
                {


                    mySprite.graphics.beginBitmapFill(myBitmap, matrix, true);
                    mySprite.graphics.drawRect(100, 50, 200, 90);
                    mySprite.graphics.endFill();
                };

            this.mouseMove +=
                ev =>
                {
                    var matrix = new Matrix();

                    matrix.rotate(Math.PI / 4 * ev.stageX / this.stage.stageWidth);
                    update(matrix);
                };

            update(new Matrix());

            addChild(mySprite);
        }
        public __PasswordBox()
        {
            // X:\jsc.svn\examples\actionscript\air\AIRAvalonPasswordField\AIRAvalonPasswordField\ApplicationCanvas.cs

            InternalTextFieldContainer = new Sprite();


            InternalTextField = new TextField
            {
                autoSize = TextFieldAutoSize.LEFT,
                type = TextFieldType.INPUT,
                displayAsPassword = true,

                background = true,
                backgroundColor = 0xffffffff,
                alwaysShowSelection = true,
                border = true,
                borderColor = 0x808080
                // http://code.hellokeita.in/public/trunk/as3/br/hellokeita/utils/TextFieldColor.as

            };

            InternalTextField.y = InternalOffsetY;



            InternalTextFieldContainer = new Sprite();
            InternalTextFieldContainer.addChild(InternalTextField);

            // http://www.typetester.org/
            //InternalTextField.defaultTextFormat.font = "Verdana";
            //LocalInternalSetFonFamily(new FontFamily("Verdana"));
        }
        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);


            //  };

        }
        public __TextBlock()
        {

            InternalTextField = new TextField
            {
                autoSize = TextFieldAutoSize.LEFT,
                type = TextFieldType.DYNAMIC,
                selectable = false,
                //background = true,
                //backgroundColor = 0xffffffff,
                //alwaysShowSelection = true,
                //border = true,
                //borderColor = 0x808080
                // http://code.hellokeita.in/public/trunk/as3/br/hellokeita/utils/TextFieldColor.as

            };

            //InternalTextField.y = InternalOffsetY;



            InternalTextFieldContainer = new Sprite();
            InternalTextFieldContainer.addChild(InternalTextField);

            // http://www.typetester.org/
            //InternalTextField.defaultTextFormat.font = "Verdana";
            LocalInternalSetFonFamily(new FontFamily("Verdana"));
        }
        public ApplicationSprite()
        {
            var s = new Sprite().AttachTo(this);
            var g = s.graphics;

            var fill = new LinearGradient();

            var g1 = new GradientEntry { color = Color1, ratio = 0.00, alpha = 0 };
            var g2 = new GradientEntry { color = Color2, ratio = 0.90, alpha = 1 };

            fill.entries = new[] { g1, g2 };
            // rotation?
            fill.angle = 45;

            // Draw a box and fill it with the LinearGradient.
            g.moveTo(0, 0);

            fill.begin(g, new Rectangle { width = DefaultWidth, height = DefaultHeight }, new Point());

            g.lineTo(DefaultWidth, 0);
            g.lineTo(DefaultWidth, DefaultHeight);
            g.lineTo(0, DefaultHeight);
            g.lineTo(0, 0);

            fill.end(g);

        }
		private void Initialize()
		{
			//stage.frameRate = 30;
			//stage.quality = StageQuality.HIGH;


			_perlinNoiseBitmapData = new BitmapData(_perlinNoiseSizeW, _perlinNoiseSizeH, false);
			for (var i = 0; i < octaves; i++)
				_offsetList[i] = new Point();


			_displacementBitmapData = new BitmapData(STAGE_W, STAGE_H, false);
			_displacementMapFilter = new DisplacementMapFilter(null, _point, 0, BitmapDataChannel.RED, 0,
									 100, DisplacementMapFilterMode.CLAMP);

			_palletBitmapData = new BitmapData(STAGE_W, STAGE_H, false);
			createGradation();



			_scaleChangeBitmapData = new BitmapData(STAGE_W, STAGE_H, false);
			_scaleChangeMatrix = new Matrix();
			_scaleChangeMatrix.scale(1 / _perlinNoiseSize, 1 / _perlinNoiseSize / _H_RATE);

			_cover = new Sprite();
			var matrix = new Matrix();
			matrix.createGradientBox(STAGE_W, STAGE_H, Math.PI / 2);

			var colors = new[] { 0x666666u, 0xaaaaaau };
			var alphas = new[] { 1.0, 1.0 };
			var ratios = new[] { 128, 255 };

			_cover.graphics.beginGradientFill(GradientType.LINEAR,
				colors,
				alphas,
				ratios, matrix
			);

			_cover.graphics.drawRect(0, 0, STAGE_W, STAGE_H);
			_cover.blendMode = BlendMode.OVERLAY;

			addChild(new Bitmap(_scaleChangeBitmapData));
			addChild(_cover);

			this.enterFrame += new Action<ScriptCoreLib.ActionScript.flash.events.Event>(TheCloudEffect_enterFrame);

			// some branding
			KnownEmbeddedResources.Default["assets/ScriptCoreLib/jsc.png"].ToBitmapAsset().AttachTo(this).MoveTo(STAGE_W - 128, STAGE_H - 128);

			this.stage.click +=
				delegate
				{
					this.stage.SetFullscreen(true);
				};
		}
		public Application()
		{
			var cloud = new TheCloudEffect(0);

			cloud.AttachTo(this);

			var cloud2 = new TheCloudEffect(1);

			cloud2.AttachTo(this);

			var t = new TextField
			{
				width = 600,
				height = 400,
				x = 20,
				y = 20,
				defaultTextFormat = new TextFormat
				{
					size = 60,
					color = 0xff,
					font = "Verdana"
				},
				text = "powered by jsc",

				filters = new BitmapFilter[] { new DropShadowFilter() },
			}.AttachTo(this);

			var r = new Sprite {  alpha = 0.5}.AttachTo(this);

			r.graphics.beginFill(0);
			r.graphics.drawRect(97, 0, 122 - 97, 500);

			this.mouseMove +=
				e =>
				{
					var x = Convert.ToInt32(e.stageX);

					t.text = "x: " + x;

					if (InRange(x))
					{
						cloud.visible = false;
						cloud2.visible = true;
					}
					else
					{
						cloud2.visible = false;
						cloud.visible = true;
					}
				};

			//KnownEmbeddedResources.Default["assets/ConditionalBranch/Preview.png"].ToBitmapAsset().AttachTo(this).MoveTo(100, 200);
		}
		public ApplicationSprite()
		{
			s = new Sprite().AttachTo(this);

			g = s.graphics;

			color1 = colors[0];


			addChild(
					new TextField
					{
						text = "powered by jsc",
						x = 20,
						y = 40,
						selectable = false,
						sharpness = -400,
						textColor = 0xffffff,
						mouseEnabled = false
					}
				);


			this.mouseMove +=
				ev =>
				{
					localX = (int)ev.stageX;
					localY = (int)ev.stageY;

					redraw();
				};

			this.click +=
				delegate
				{
					color1 = colors[++colors_index % (colors.Length - 1)];
					redraw();
				};

			var timer = new Timer(1000 / 24, 0);

			timer.timer +=
				delegate
				{
					counter++;

					redraw();
				};

			timer.start();

			redraw();
		}
		/// <summary>
		/// Default constructor
		/// </summary>
		public HyperlinkExample()
		{

	
			var s = new Sprite().AttachTo(this);
			var img = Assets.Default["assets/HyperlinkExample/plus_google.gif"].ToBitmapAsset().AttachTo(s);
			s.useHandCursor = true;

			s.click +=
				delegate
				{
					new URLRequest("http://zproxy.wordpress.com").NavigateTo("_blank");
				};

		}
		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;
		}
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151115/audio


        /// <summary>
        /// Default constructor
        /// </summary>
        public MP3PitchExample()
        {
            // http://blog.andre-michelle.com/upload/mp3pitch/MP3Pitch.as
            // http://blog.andre-michelle.com/2009/pitch-mp3/

            var Rate = new TextField
            {
                text = "1.0"
            }.AttachTo(this);

            var p = new MP3Pitch("http://visit.abstractatech.com/assets/com.abstractatech.web.design1/AbstractatechPostProductionVersion7.mp3");

            var o = new Sprite
            {

            }.AttachTo(this);

            o.click +=
                delegate
                {
                    p = new MP3Pitch("http://visit.abstractatech.com/assets/com.abstractatech.web.design1/AbstractatechPostProductionVersion7.mp3")
                    {
                        _rate = p._rate
                    };
                };

            o.graphics.beginFill(0x0, 0.5);
            o.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);

            o.mouseMove +=
                e =>
                {
                    var rate = (e.stageX / this.stage.stageWidth) * 2;
                    p._rate = rate;
                    Rate.text = "" + rate;
                };

            //KnownEmbeddedResources.Default["assets/MP3PitchExample/Preview.png"].ToBitmapAsset().AttachTo(this).MoveTo(100, 200);
        }
        /// <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);

                }
        }
		public FixedBorderCanvas(int DefaultWidth, int DefaultHeight)
		{
	
			CanvasOverlay = new Sprite();
			// canvas is not attached

			InfoOverlay = new Sprite().AttachTo(this);
			BorderOverlay = new Shape().AttachTo(this);

			#region mask
			var CanvasMask = new Shape();

			CanvasMask.graphics.beginFill(0x00ffffff);
			CanvasMask.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);

			CanvasMask.AttachTo(this);

			CanvasOverlay.mask = CanvasMask;
			#endregion


			BorderOverlay.graphics.lineStyle(1, Colors.Green, 1);
			BorderOverlay.graphics.drawRect(0, 0, DefaultWidth - 1, DefaultHeight - 1);
		}
		// port of http://www.bit-101.com/blog/?p=2339

		// how can we port this to wpf?
		// http://msdn.microsoft.com/en-us/library/ms753347.aspx
		// http://www.odewit.net/Perspective/dotnet3.5/PerspectiveDemo.xbap?page=pWpf3D/ButtonFaderKnob3D.xaml
		// http://www.odewit.net/ArticleContent.aspx?id=Wpf3DControls&format=html
		// seems like this could be done in silverlight, but not in WPF at this time.
		// not cool - WPF has no audio nor no decent easy 3D api.

		public Application()
		{
			var cloud = new TheCloudEffect().AttachTo(this);



			#region powered by jsc
			new TextField
			{
				width = 600,
				height = 400,
				x = 20,
				y = 20,
				defaultTextFormat = new TextFormat
				{
					size = 30,
					color = 0xff,
					font = "Verdana"
				},
				text = "powered by jsc",

				filters = new BitmapFilter[] { new DropShadowFilter() },
			}.AttachTo(this);
			#endregion

			#region jsc_diagram
			var jsc_diagram = KnownEmbeddedResources.Default["assets/MatrixStuffExample/jsc_diagram.png"].ToBitmapAsset();

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

			var sprite = new Sprite
			{
				x = 300,
				y = 300,
				z = 100
			}.AttachTo(this);

			jsc_diagram.filters = new BitmapFilter[] { new GlowFilter(0xffffff, 1, 12, 12) };
			jsc_diagram.AttachTo(sprite);

			#endregion

	
			this.enterFrame +=
				e =>
				{
					sprite.transform.matrix3D.pointAt(new Vector3D(mouseX, mouseY, 0),
						// fixed: an now we are not showing up in reverse
						new Vector3D(0, 0, -0.9999), new Vector3D(0,  -0.9999, 0)
					);

				
				};

			#region jsc_preview2

			var jsc_preview2 = KnownEmbeddedResources.Default["assets/MatrixStuffExample/Preview.png"].ToBitmapAsset();

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

			var sprite2 = new Sprite
			{
				x = 6 + 60,
				y = 600 - 45 - 6,
				z = 0.001
			}.AttachTo(this);

			jsc_preview2.filters = new BitmapFilter[] { new GlowFilter(0xffffff, 1, 12, 12) };
			jsc_preview2.AttachTo(sprite2);
			#endregion



			var t = new Timer(1000 / 60);

			t.timer +=
				delegate
				{
					var x = sprite2.x;
					var y = sprite2.y;

					sprite2.transform.matrix3D.appendTranslation(-x, -y, 0);
					sprite2.transform.matrix3D.appendRotation(1, Vector3D.Y_AXIS);
					sprite2.transform.matrix3D.appendTranslation(x, y, 0);

				};

			t.start();

			KnownEmbeddedResources.Default["assets/MatrixStuffExample/jsc.png"].ToBitmapAsset().AttachTo(this).MoveTo(600 - 96, 600 - 96);


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

                    //this.stage.color = 0xB38248;


                    // read more: http://www.senocular.com/flash/tutorials/contentdomains/

                    //                SecurityError: Error #3207: Application-sandbox content cannot access this feature.
                    //at flash.system::Security$/allowDomain()

                    try
                    {
                        Security.allowDomain("*");
                        Security.allowInsecureDomain("*");
                    }
                    catch
                    {
                    }

                    var yNext = default(Action);

                    #region yinit
                    Action yinit = delegate
                    {
                        ytp.Loader.content.x = (this.stage.stageWidth - 1280) / 2;
                        ytp.Loader.content.y = (this.stage.stageHeight - 720) / 2;

                        this.stage.resize += delegate
                        {
                            if (this.stage == null)
                                return;

                            ytp.Loader.content.x = (this.stage.stageWidth - 1280) / 2;
                            ytp.Loader.content.y = (this.stage.stageHeight - 720) / 2;

                        };

                        content.AttachToContainer(this);
                        content.AutoSizeTo(this.stage);

                        yNext();
                    };
                    #endregion

                    // fails on android?
                    ytp = new YouTubePlayer(
                        DefaultVideo: "f9xV-LJCmV4",
                        //DefaultVideo: "qZni5895I-M",

                        // https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/Bx5z7CrL9Cs
                        //suggestedQuality: "medium",

                        yield_init: yinit
                    );


                    var yall = ytp["all", 0, 100000];

                    #region yNext
                    yNext = delegate
                    {
                        ytp.PlayScene(
                            yall,
                            delegate
                            {
                                if (ytp.CurrentVideoId == "f9xV-LJCmV4")
                                    ytp.loadVideoById("bfTL3ZwO0tk");
                                else if (ytp.CurrentVideoId == "bfTL3ZwO0tk")
                                    ytp.loadVideoById("qZni5895I-M");
                                else
                                    ytp.loadVideoById("f9xV-LJCmV4");


                                yNext();
                            }
                        );
                    };
                    #endregion

                    var te = new TextField { autoSize = TextFieldAutoSize.LEFT };

                    //.AttachTo(this);

                    ytp.StatusToClients += xx => te.text = xx;

                    var ys = new Sprite { mouseEnabled = false, mouseChildren = false }.AttachTo(this);
                    ytp.Loader.AttachTo(ys);




                    #region ToAnimatedOpacity
                    var Container720A = content.iA;
                    Container720A.Opacity = 1.0;

                    //var VideoPlayingOpacity = 1.0;

                    ytp.Playing += delegate
                    {
                        content.VideoPlayingOpacity = 0;
                        Container720A.Opacity = content.VideoPlayingOpacity;
                    };

                    ytp.NotPlaying += delegate
                    {
                        content.VideoPlayingOpacity = 1;
                        Container720A.Opacity = content.VideoPlayingOpacity;
                    };


                    var entero = content.entero;

                    entero.Opacity = 0.8;

                    content.enter.MouseLeftButtonUp +=
                         delegate
                         {

                             if (StartClicked != null)
                                 StartClicked();

                             entero.Opacity = 0.0;
                         };

                    #endregion

                    content.AttachToContainer(this);
                    content.AutoSizeTo(this.stage);
                }
            );


        }
Example #18
0
        private Sprite getCircle(uint circumference = 40)
        {
            var h = circumference / 2;

            var circle = new Sprite();
            circle.graphics.beginFill(0x1695A3);
            circle.graphics.drawCircle(0, 0, circumference);

            circle.graphics.drawRect(-h, -circumference * 2, circumference, circumference * 2);
            return circle;
        }
        // http://blog.allanbishop.com/box2d-2-1a-tutorial-part-1/

        public ApplicationSprite()
        {

            _world = new b2World(new b2Vec2(0, 10), true);

            var groundBodyDef = new b2BodyDef();
            groundBodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE,
                          SWF_HEIGHT / PIXELS_TO_METRE - 20 / PIXELS_TO_METRE);

            var groundBody = _world.CreateBody(groundBodyDef);

            var groundBox = new b2PolygonShape();
            groundBox.SetAsBox(SWF_HALF_WIDTH / PIXELS_TO_METRE,
                           20 / PIXELS_TO_METRE);

            var groundFixtureDef = new b2FixtureDef();
            groundFixtureDef.shape = groundBox;
            groundFixtureDef.density = 1;
            groundFixtureDef.friction = 1;
            groundBody.CreateFixture(groundFixtureDef);

            var bodyDef = new b2BodyDef();
            bodyDef.type = b2Body.b2_dynamicBody;
            bodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE, 4);
            var body = _world.CreateBody(bodyDef);

            var dynamicBox = new b2PolygonShape();
            dynamicBox.SetAsBox(1, 1);

            var fixtureDef = new b2FixtureDef();
            fixtureDef.shape = dynamicBox;
            fixtureDef.density = 1;
            fixtureDef.friction = 0.3;

            body.CreateFixture(fixtureDef);

            var debugSprite = new Sprite();
            addChild(debugSprite);
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(debugSprite);
            debugDraw.SetDrawScale(PIXELS_TO_METRE);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetAlpha(1);
            debugDraw.SetFillAlpha(0.4);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
            _world.SetDebugDraw(debugDraw);


            // Add event for main loop

            this.stage.enterFrame +=
                delegate
                {
                    var timeStep = 1 / 30.0;
                    var velocityIterations = 6;
                    var positionIterations = 2;

                    _world.Step(timeStep, velocityIterations, positionIterations);
                    _world.ClearForces();
                    _world.DrawDebugData();

                };


        }
		private void EnterEndLevelMode()
		{
			var ScoreContainer = new Sprite().AttachTo(this);

			ScoreContainer.alpha = 0.8;

			var scroll = Assets.Default.scroll.AttachTo(ScoreContainer);
			var scroll_scale =  DefaultControlHeight / scroll.height;

			scroll.scaleX = scroll_scale;
			scroll.scaleY = scroll_scale;

			scroll.MoveTo(DefaultControlWidth - scroll.width, 0 );
			scroll.filters = new BitmapFilter[] { new DropShadowFilter() };

			new Bitmap(EgoView.Buffer.clone())
			{
				scaleX = DefaultScale,
				scaleY = DefaultScale
			}.AttachTo(this).FadeOutAndOrphanize(1000 / 24, 0.1);

			music.stop();

			EndLevelMode = true;
			MovementEnabled = false;

			var music_endlevel = Assets.Default.music_endlevel.play(1);


			this.EgoView.Image.filters = new BitmapFilter[] {
				Filters.GrayScaleFilter,
			};

			this.EgoView.ViewPositionLock = TheGoldStack.Position;
			this.EgoView.ViewPosition = TheGoldStack.Position;

			var FrozenLook = (45 + 180);

			var p = new PointInt32
			{
				X = (int)Math.Floor(TheGoldStack.Position.x),
				Y = (int)Math.Floor(TheGoldStack.Position.y),
			};

			// where should we look actually?
			if (EgoView.Map.WallMap[p.X - 1, p.Y] != 0)
				FrozenLook = (90 + 180);

			if (EgoView.Map.WallMap[p.X, p.Y - 1] != 0)
				FrozenLook = (0 + 180);

			this.EgoView.ViewDirection = FrozenLook.DegreesToRadians();

		

			1500.AtDelayDo(
				delegate
				{
					HudContainer.FadeOut(1000 / 15, 0.2,
						delegate
						{

						}
					);


					new TextField
					{
						defaultTextFormat = new TextFormat
						{
							size = 36,
						},
						text = "Level 7 Complete",

						textColor = 0xFFC526,
						autoSize = TextFieldAutoSize.LEFT,
						filters = new[] { new GlowFilter(0xC1931D) }
					}.AttachTo(ScoreContainer).MoveTo(scroll.x + 40, scroll.y + 64);

					// level ends for all

					// list current scores

					new TextField
					{
						defaultTextFormat = new TextFormat
						{
							size = 33,
						},
						text = "Player 1 - 1000$",

						textColor = 0xFFC526,
						autoSize = TextFieldAutoSize.LEFT,
						filters = new[] { new GlowFilter(0xC1931D) }
					}.AttachTo(ScoreContainer).MoveTo(scroll.x + 48, scroll.y + 96 + 33 * 1);

					new TextField
					{
						defaultTextFormat = new TextFormat
						{
							size = 30,
						},
						text = "Player 2 - 1200$",

						textColor = 0xbebebe,
						autoSize = TextFieldAutoSize.LEFT,
						filters = new[] { new GlowFilter(0x909090) }
					}.AttachTo(ScoreContainer).MoveTo(scroll.x + 48, scroll.y + 96 + 33 * 2);

					new TextField
					{
						defaultTextFormat = new TextFormat
						{
							size = 30,
						},
						text = "Player 3 - 1800$",

						textColor = 0xbebebe,
						autoSize = TextFieldAutoSize.LEFT,
						filters = new[] { new GlowFilter(0x909090) }
					}.AttachTo(ScoreContainer).MoveTo(scroll.x + 48, scroll.y + 96 + 33 * 3);


					music_endlevel.soundComplete +=
						delegate
						{
							// we are ready to continue...
							// are other players?

							ScoreContainer.FadeOut(1000 / 15, 0.1,
								delegate
								{
									ScoreContainer.Orphanize();

									//this.EgoView.Image.filters = null;
									//this.EgoView.ViewPositionLock = null;

									//EndLevelMode = false;
									//MovementEnabled = true;

									//HudContainer.alpha = 1;

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

		}
        public ShopExperience(Sprite that)
        {
            var currentped = default(IPhysicalUnit);

            var shopcontent = new ApplicationCanvas();
            var sb = new Soundboard();

            #region GiveMeWhatIWant
            Action GiveMeWhatIWant = delegate
            {
                shopcontent.bg_ammo.Fill = Brushes.Green;
                shopcontent.bg_shotgun.Fill = Brushes.Green;
                sb.snd_SelectWeapon.play();
                shopcontent.t2o.Opacity = 0.1;
                (currentped as PhysicalPed).With(
                    ped =>
                    {
                        ped.visual.StandWithVisibleGun = true;
                    }
                );
            };

            #endregion

            #region BuyAmmo
            shopcontent.BuyAmmo += delegate
            {
                Console.WriteLine("BuyAmmo");

                //                BuyAmmo
                //facebookOAuthConnectPopup: { facebookOAuthConnectPopup_window = _blank }
                //after facebookOAuthConnectPopup
                //still in window: { Right = 739, Left = 675 }
                //{ zombie_forceA = 4.867357484065154 }
                //facebookOAuthConnectPopup callback { connectUserId = fb1527339800, access_token = AAADLSABgZCZC0BAOroZC3jsNhsgRVFhBK4VcAT19uePwd2iZBKX8ZCVwtdu8ZBhtmU9bH6nMJHO0qJ6I5dzvhw9Ty1kt542zpH2BZCMKKPI0wZDZD, facebookuserid = 1527339800 }
                //at callback
                //BuyAmmo { facebookuserid = 1527339800, Length = 1 }
                //{ item = [playerio.VaultItem][itemKey="Shotgun3", id="403939388", purchaseDate=Mon Mar 11 21:32:08 GMT+0200 2013] = {
                //FreelyGivable:true
                //PriceUSD:99
                //} }
                //set facebookOAuthConnectPopupItems_cache


                sb.snd_click.play(
                      sndTransform: new ScriptCoreLib.ActionScript.flash.media.SoundTransform(0.5)
                  );



#if FFACEBOOK
                that.facebookOAuthConnectPopupItems(
                    (Client xclient, string access_token, string facebookuserid, object[] items) =>
                    {
                        Console.WriteLine("BuyAmmo  " + new { facebookuserid, xclient.payVault.items.Length });

                #region itemKey_exists
                        var itemKey = "Shotgun3";
                        var itemKey_exists = false;

                        foreach (var item in items)
                        {
                            var dyn = new DynamicContainer { Subject = item };

                            var dyn_itemKey = (string)dyn["itemKey"];

                            Console.WriteLine(new { item });

                            if (dyn_itemKey == itemKey)
                                itemKey_exists = true;
                        }

                        if (itemKey_exists)
                        {
                            GiveMeWhatIWant();
                            return;
                        }
                        #endregion


                        //                              facebookOAuthConnectPopup callback { connectUserId = fb1527339800, access_token = AAADLSABgZCZC0BAOroZC3jsNhsgRVFhBK4VcAT19uePwd2iZBKX8ZCVwtdu8ZBhtmU9bH6nMJHO0qJ6I5dzvhw9Ty1kt542zpH2BZCMKKPI0wZDZD, facebookuserid = 1527339800 }
                        //BuyAmmo { facebookuserid = 1527339800, Length = 1 }
                        //{ item = [playerio.VaultItem][itemKey="Shotgun3", id="403939388", purchaseDate=Mon Mar 11 21:32:08 GMT+0200 2013] = {
                        //FreelyGivable:true
                        //PriceUSD:99
                        //} }

                    }
                );
#endif

            };
            #endregion

            #region BuyShotgun
            shopcontent.BuyShotgun += delegate
            {
                Console.WriteLine("BuyShotgun");

                sb.snd_click.play(
                  sndTransform: new ScriptCoreLib.ActionScript.flash.media.SoundTransform(0.5)
              );


              //  that.facebookOAuthConnectPopupItems(
              //    (Client xclient, string access_token, string facebookuserid, object[] items) =>
              //    {
              //        Console.WriteLine("BuyShotgun  " + new { facebookuserid, xclient.payVault.items.Length });

              //        var itemKey = "Shotgun3";


              //        var BuyAnyway = false;
              //        if (BuyAnyway)
              //        {

              //        }
              //        else
              //        {

              //            #region itemKey_exists
              //            var itemKey_exists = false;

              //            foreach (var item in items)
              //            {
              //                var dyn = new DynamicContainer { Subject = item };

              //                var dyn_itemKey = (string)dyn["itemKey"];

              //                Console.WriteLine(new { item });

              //                if (dyn_itemKey == itemKey)
              //                    itemKey_exists = true;
              //            }

              //            if (itemKey_exists)
              //            {
              //                GiveMeWhatIWant();

              //                return;
              //            }
              //            #endregion

              //        }

              //        Console.WriteLine("before getBuyDirectInfo");

              //        //// Gets information about how to make a direct item purchase with the specified PayVault provider.
              //        //that.getBuyDirectInfo(
              //        //    xclient,
              //        //    facebookuserid,

              //        //    item_name: "Operation Heat Zeeker - Shotgun",
              //        //    itemKey: itemKey,

              //        //    yield_paypalurl: uri =>
              //        //    {
              //        //        Console.WriteLine("at getBuyDirectInfo");

              //        //        shopcontent.bg_shotgun.Fill = Brushes.Red;


              //        //        uri.NavigateTo();
              //        //    }
              //        //);


              //    }
              //);


            };
            #endregion


            ShopEnter =
                ped =>
                {
                    currentped = ped;


                    shopcontent.AttachToContainer(that);
                    shopcontent.AutoSizeTo(that.stage);
                };


            shopcontent.Close += delegate
            {
                if (currentped == null)
                    return;

                currentped = null;

                ScriptCoreLib.ActionScript.Extensions.CommonExtensions.Orphanize(
                    ScriptCoreLib.ActionScript.Extensions.AvalonExtensions.ToSprite(shopcontent)
                    );
            };

            ShopExit =
               delegate
               {
                   if (currentped == null)
                       return;

                   currentped = null;

                   ScriptCoreLib.ActionScript.Extensions.CommonExtensions.Orphanize(
                       ScriptCoreLib.ActionScript.Extensions.AvalonExtensions.ToSprite(shopcontent)
                       );
               };
        }
		private void Initialize()
		{
			this.music = Assets.Default.Sounds.music.play(0, 9999);




			EgoView = new ViewEngine(DefaultWidth, DefaultHeight)
			{
				FloorAndCeilingVisible = false,
				RenderLowQualityWalls = false,
				ViewDirection = 0,
				ViewPosition = new Point()
			};

			EgoView.Image.scaleX = DefaultScale;
			EgoView.Image.scaleY = DefaultScale;
			EgoView.Image.alpha = 0;
			EgoView.Image.AttachTo(this);

			// show fps
			new TextField { textColor = 0xff0000, x = DefaultControlWidth / 2 }.AttachTo(this).Do(t => EgoView.FramesPerSecondChanged += () => t.text = "fps: " + EgoView.FramesPerSecond);

			EgoView.FramesPerSecondChanged +=
				delegate
				{
					if (EgoView.FramesPerSecond < 14)
						if (!EgoView.RenderLowQualityWalls)
							EgoView.RenderLowQualityWalls = true;

					if (EgoView.FramesPerSecond > 22)
						if (EgoView.RenderLowQualityWalls)
							EgoView.RenderLowQualityWalls = false;
				};


			this.HudContainer = new Sprite().AttachTo(this);
			this.HudContainer.alpha = 0;

			getpsyched = Assets.Default.getpsyched.AttachTo(this);

			getpsyched.scaleX = 2;
			getpsyched.scaleY = 2;
			getpsyched.MoveTo((DefaultControlWidth - getpsyched.width) / 2, (DefaultControlHeight - getpsyched.height) / 2);
			getpsyched.alpha = 0;

			InitializeWriteLine();

			getpsyched.FadeIn(
				delegate
				{
					Assets.Default.Sounds.gutentag.play();


					Assets.Default.dude5.ToBitmapArray(
						Bitmaps =>
						{
							var Spawn = default(Func<SpriteInfoExtended>);

							#region figure out
							if (Bitmaps == null)
								throw new Exception("No bitmaps");

							Func<Texture64[], Texture64[]> Reorder8 =
								p =>
									Enumerable.ToArray(
										from i in Enumerable.Range(0, 8)
										select p[(i + 6) % 8]
									);

							var BitmapStream = Bitmaps.Select(i => (Texture64)i).GetEnumerator();

							Func<Texture64[]> Next8 =
								delegate
								{
									// keeping compiler happy with full delegate form

									if (BitmapStream == null)
										throw new Exception("BitmapStream is null");

									return Reorder8(BitmapStream.Take(8));
								};


							var Stand = Next8();


							//if (Bitmaps.Length == 8)
							//{
							//    Spawn = () => CreateWalkingDummy(Stand);
							//}
							//else
							//{
							var Walk = new[]
							{
								Next8(),
								Next8(),
								Next8(),
								Next8(),
							};

							var Death = new List<Texture64>
							{
								BitmapStream.Take(),
								BitmapStream.Take(),
								BitmapStream.Take(),
								BitmapStream.Take(),
								BitmapStream.Take()
							};


							var Hit = new[] { BitmapStream.Take() };

							// funny ordering huh?
							Death.Add(BitmapStream.Take());

							Spawn = () => CreateWalkingDummy(Stand, Walk, Hit, Death.ToArray());

							//}

							#endregion

							CreateGuard = Spawn;




							InitializeMap();


						}
					);
				}
			);

		}
Example #23
0
		public Statusbar()
		{
			Element = new Sprite();

			#region TextScore
			var TextScore = new TextField
			{

				y = 8,
				x = 8,
				autoSize = TextFieldAutoSize.LEFT,
				textColor = Colors.White,
				embedFonts = true,

				//background = true,
				//backgroundColor = Colors.Gray,

				defaultTextFormat = new TextFormat
				{
					font = Fonts.FontFixedSys,
					size = 28,
				},
				selectable = false,
				condenseWhite = false,
				htmlText = "Score: <font color='#00ff00'>15</font>",
			}.AttachTo(Element);
			#endregion

			Score.ValueChangedTo +=
						score => TextScore.htmlText = "Score: <font color='#00ff00'>" + score + "</font>";


			#region TextLives
			var TextLives = new TextField
			{

				y = 8,
				x = 240,
				autoSize = TextFieldAutoSize.LEFT,
				textColor = Colors.White,
				embedFonts = true,

				//background = true,
				//backgroundColor = Colors.Gray,

				defaultTextFormat = new TextFormat
				{
					font = Fonts.FontFixedSys,
					size = 28,
				},
				selectable = false,
				condenseWhite = false,
				htmlText = "Lives:  ",
			}.AttachTo(Element);
			#endregion

			#region lifebar
			Func<int, Sprite> AddLife =
				offset =>
					Animations.Spawn_BigGun((int)(TextLives.x + TextLives.width) + offset, (int)(TextLives.y + TextLives.height / 2));


			Func<int, Sprite> AddEvilLife =
				offset =>
					Animations.Spawn_UFO((int)(TextLives.x + TextLives.width) + offset, (int)(TextLives.y + TextLives.height / 2));



			var Life1 = AddLife(40 * 0);
			var Life2 = AddLife(40 * 1);
			var Life3 = AddLife(40 * 2);

			var LifeBar = new SpriteWithMovement { Life1, Life2, Life3 }.AttachTo(Element);

			var EvilLife1 = AddEvilLife(40 * 0);
			var EvilLife2 = AddEvilLife(40 * 1);
			var EvilLife3 = AddEvilLife(40 * 2);

			var EvilLifeBar = new SpriteWithMovement { EvilLife1, EvilLife2, EvilLife3 };
			#endregion

			this.Lives.ValueChangedTo +=
				i =>
				{
					LifeBar.Children().ForEach(
						(c, j) =>
						{
							c.visible = j < i;
						}
					);

					EvilLifeBar.Children().ForEach(
						(c, j) =>
						{
							c.visible = j < i;
						}
					);
				};

			var Fader = new DualFader { Value = LifeBar };

			this.EvilMode.ValueChangedToTrue +=
				delegate
				{
					Fader.Value = EvilLifeBar;
				};

			this.EvilMode.ValueChangedToFalse +=
				delegate
				{
					Fader.Value = LifeBar;
				};
		}
		// http://curtismorley.com/2008/11/01/actionscript-security-error-2060-security-sandbox-violation/
		// http://blog.deconcept.com/code/externalinterface.html
		// http://blog.warptube.com/2008/12/2/oddities-with-externalinterface-and-ie

        public ApplicationSprite()
        {
            addChild(
                    new TextField
                    {
                        text = ExternalInterface.available ?
                        "ExternalInterface available" : "ExternalInterface not available",
                        x = 20,
                        y = 20,
                        selectable = false,
                        textColor = 0xffffff,
                        autoSize = TextFieldAutoSize.LEFT,
                        mouseEnabled = false
                    }
                );

            addChild(
                    new TextField
                    {
                        text = Security.sandboxType,
                        x = 20,
                        y = 40,
                        selectable = false,
                        textColor = 0xffffff,
                        autoSize = TextFieldAutoSize.LEFT,
                        mouseEnabled = false
                    }
                );

            Security.allowDomain("*");


            var status =
                new TextField
                {
                    text = "ready",
                    x = 20,
                    y = 80,
                    selectable = false,
                    textColor = 0xffffff,
                    autoSize = TextFieldAutoSize.LEFT,
                    mouseEnabled = false
                }.AttachTo(this);

            Func<string, Sprite> CreateButton =
                text =>
                {
                    var z = new Sprite();

                    z.graphics.beginFill(0xff0000);
                    z.graphics.drawRect(0, 0, 100, 20);
                    z.graphics.endFill();
                    z.width = 100;
                    z.height = 20;
                    
                    new TextField { text = text, mouseEnabled = false, width = 100, height = 20 }.AttachTo(z);

                    return z;
                };

            Func<string, Action, Sprite> AddButton =
                (text, click) =>
                {
                    var z = CreateButton(text);

                    z.click += delegate { click(); };

                    z.AttachTo(this);

                    return z;

                };

            var s = AddButton("call function1!",
                delegate
                {
                    status.text = "click!";

					try
					{

						ExternalInterface.call("setTimeout", "document.title = 'flashed';", 0);
						status.text = ExternalInterface.call("function1", "hello world").ToString();
					}
					catch (Exception ex)
					{
						status.text = ex.Message;
					}
                }
            );

            var a = AddButton("show settings!",
              delegate
              {
                  status.text = "settings!";

                  Security.showSettings();
              }
            );

            a.x = 102;

            var b = AddButton("add callback!",
                delegate
                {
                    status.text = "new callback!";

                    Action function2 =
                       delegate
                       {
                           status.text = "function2 called";
                       };

                    ExternalInterface.addCallback("function2", function2.ToFunction());
                }
              );


            b.x = 204;

			//ExternalInterface.call("setTimeout", "document.title = 'ready';", 0);

        }
Example #25
0
		public void setSprite(Sprite sprite)
		{
		}
Example #26
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);
        }
Example #27
0
        public Menu()
        {
            CanFire = false;

            var menumusic = Sounds.snd_birds.ToSoundAsset().play(0, 999);

            Mouse.show();

            Aim.visible = false;

            GetWarzone().filters = new[] { new BlurFilter() };

            var InfoMenu = new Sprite
            {
                x = 120,
                y = 120
            }.AttachTo(this);

            var y = 0d;

            // X:\jsc.svn\examples\actionscript\FlashTowerDefense\FlashTowerDefense\ActionScript\Menu.cs
            // public override event Action<MouseEvent> contextMenu;
            // public ContextMenu contextMenu { get; set; }
            // um the jsc rewriter should rename
            // either the field or the event.
            // or the flash natives gen should stop
            // creating events that have the same name
            // as fields.
            // carlo! :)

            // can jsc send a comment?

            //"this is a comment";
            "this is a comment".Comment();


#if FContextMenu
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140402



            this.contextMenu = new ContextMenu();
            this.contextMenu.hideBuiltInItems();
#endif


            foreach (var v in this.Settings.KnownActors)
            {
                AddInfo(InfoMenu, y, v);

                y += 72;
            }

            #region Play
            var PlayButton = new TextField
            {
                defaultTextFormat = new TextFormat
                {
                    size = 36
                },
                autoSize = TextFieldAutoSize.LEFT,
                htmlText = "Play!",
                selectable = false,
                textColor = ColorBlue,
                filters = new[] { new GlowFilter(ColorBlueLight) }

            }.AttachTo(this);

            PlayButton.x = DefaultWidth - PlayButton.width - 32;
            PlayButton.y = DefaultHeight - PlayButton.height - 32;

            PlayButton.OnHoverUseColor(ColorRed);



            PlayButton.click +=
                delegate
                {
                    menumusic.stop();

                    InfoMenu.mouseEnabled = false;
                    InfoMenu.mouseChildren = false;

                    InfoMenu.FadeOutAndOrphanize(1000 / 64, 0.21);


                    GetWarzone().filters = null;

                    Action PlaySound = () => Sounds.snd_click.ToSoundAsset().play();

                    PlaySound();

                    //PlaySound.InvokeAtDelays(0, 500, 800);


                    CanFire = true;
                    PlayButton.Orphanize();
                    Aim.visible = true;
                    Mouse.hide();
                };
            #endregion

        }
		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();
									}
								);

							}
						}
					);
				};
		}
		private void Initialize()
		{
			this.stage.fullScreenSourceRect = new Rectangle
			{
				width = DefaultControlWidth,
				height = DefaultControlHeight
			};

			#region fullscreen support
			bool NextFullscreenMode = true;

			this.stage.fullScreen +=
				e =>
				{
					NextFullscreenMode = !e.fullScreen;

					// hide chat while fullscreen zoom
					this.GetStageChild().Siblings().ForEach(k => k.visible = !e.fullScreen);
				};
			
		
			this.contextMenu = new ContextMenuEx
			{
				{ "Fullscreen", 
					delegate
					{
						this.stage.SetFullscreen(NextFullscreenMode);
					}
				}
			};
			#endregion



			this.music = Assets.Default.Music.music.play(0, 9999, new SoundTransform(0.5));




			EgoView = new ViewEngine(DefaultWidth, DefaultHeight)
			{
				FloorAndCeilingVisible = false,
				RenderLowQualityWalls = false,
				ViewDirection = 0,
				ViewPosition = new Point(0, 0)
			};

			EgoView.Image.scaleX = DefaultScale;
			EgoView.Image.scaleY = DefaultScale;
			EgoView.Image.alpha = 0;
			EgoView.Image.AttachTo(this);

			EgoView.ViewPositionChanged +=
				delegate
				{
					this.NextViewPosition = EgoView.ViewPosition;
				};

			EgoView.ViewDirectionChanged +=
				delegate
				{
					this.NextViewDirection = EgoView.ViewDirection;
				};
		
			EgoView.FramesPerSecondChanged +=
				delegate
				{
					if (EgoView.FramesPerSecond < 14)
						if (!EgoView.RenderLowQualityWalls)
							EgoView.RenderLowQualityWalls = true;

					if (EgoView.FramesPerSecond > 20)
						if (EgoView.RenderLowQualityWalls)
							EgoView.RenderLowQualityWalls = false;
				};


			this.HudContainer = new Sprite().AttachTo(this);
			this.HudContainer.alpha = 0;

			getpsyched = Assets.Default.getpsyched.AttachTo(this);

			getpsyched.scaleX = 2;
			getpsyched.scaleY = 2;
			getpsyched.MoveTo((DefaultControlWidth - getpsyched.width) / 2, (DefaultControlHeight - getpsyched.height) / 2);
			getpsyched.alpha = 0;

			InitializeWriteLine();

			this.WriteLine("init: getpsyched");

			//WriteLine("with minimap");


			getpsyched.FadeIn(
				delegate
				{
					Assets.Default.Sounds.gutentag.play();

					this.WriteLine("init: gutentag");

					var TryLoad = default(Action);

					TryLoad =
						delegate
						{
							Assets.Default.dude5.ToBitmapArray(
								CachedGuardTextures,
								Bitmaps =>
								{
									TryLoad = null;
									LoadGuardTextures(Bitmaps);
								}
							);
						};


					10000.AtDelayDo(
						delegate
						{
							if (TryLoad != null)
								TryLoad();
						}
					);

					TryLoad();

				}
			);

		}
        private void InitializeMap()
        {
            if (InitializeMapDone)
                return;

            InitializeMapDone = true;

            stage.scaleMode = StageScaleMode.NO_SCALE;

            var MapContainer = new Sprite().AttachTo(this);

            Field = new MineField(FieldXCount, FieldYCount, 0.15);


            #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 = DefaultControlHeight - p.height - 32;

                    p.AddTo(ActiveMessages).AttachTo(this).MoveTo((DefaultControlWidth - p.width) / 2, DefaultControlHeight);

                    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();

                                500.AtDelayDo(
                                    delegate
                                    {
                                        p.alpha = 0.5;


                                    }
                                );
                                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

            ShowMessage("Ctrl-click for flag!");

            Action<int> AddScore =
                e =>
                {
                    if (e > 0)
                    {
                        if (e < 5)
                        {
                            //   ShowMessage("+" + e);
                        }
                        else
                            ShowMessage("Yay! +" + e);
                    }
                    else
                        ShowMessage("Booom! -" + e);

                    Messages.AddScore(e);

                };

            var DisallowClicks = default(Timer);
            var DisallowClicksMultiplierMin = 2;
            var DisallowClicksMultiplier = DisallowClicksMultiplierMin;

            

            #region OnBang
            Field.OnBang +=
                LocalPlayer =>
                {
                    ServerSendMapEnabled = false;

                    if (LocalPlayer)
                    {
                        DisallowClicksMultiplier++;


                        if (this.CoPlayerNames.Count > 0)
                        {
                            var DisallowClicksTimeout = (DisallowClicksMultiplier * 2 * (this.CoPlayerNames.Count + 1));

                            Field.DisallowClicks = true;

                            if (DisallowClicks != null && DisallowClicks.running)
                            {
                                DisallowClicks.stop();
                            }

                            DisallowClicks = (DisallowClicksTimeout * 1000).AtDelayDo(
                                () =>
                                {
                                    Field.DisallowClicks = false;

                                    ShowMessage("Your penalty multiplier is now " + DisallowClicksMultiplier);
                                }
                            );

                            ShowMessage("You must wait " + DisallowClicksTimeout + " seconds to resume!");
                        }

                        AddScore(-8);
                    }
                    else
                    {
                        RemotePlayerMustSendNewMap = true;

                        AddScore(-4);
                    }
                };
            #endregion


            var LocalPlayerFieldsOpened = 0;

            #region OnComplete
            Field.OnComplete +=
               LocalPlayer =>
               {
                   DisallowClicksMultiplier = DisallowClicksMultiplierMin;

                   ServerSendMapEnabled = false;

                   if (LocalPlayer)
                   {
                       if (LocalPlayerFieldsOpened < 10)
                       {
                           AddScore(100);
                       }
                       else
                       {
                           AddScore(150);
                           Messages.AwardAchievementFirstMinefieldComplete();
                       }

                   }
                   else
                   {
                       // give only half of points if a coplayer was not active
                       if (LocalPlayerFieldsOpened < 10)
                           AddScore(50);
                       else
                           AddScore(100);
                   }
               };
            #endregion


            Field.IsFlagChanged +=
                (button, value) =>
                {
                    Messages.SetFlag(button, value.ToInt32());
                };

            Field.OnReveal +=
                (button) =>
                {
                    Messages.Reveal(button);
                };

            Field.GameReset +=
                IsLocalPlayer =>
                {
                    LocalPlayerFieldsOpened = 0;

                    if (!IsLocalPlayer)
                    {
                        if (RemotePlayerMustSendNewMap)
                        {
                            ShowMessage("Map will come soon!");
                            // start a timer to generate a map on our own
                            CrudeMapReset = (4000 + 40.Random() * 100).ToInt32().AtDelayDo(
                                delegate
                                {
                                    RemotePlayerMustSendNewMap = false;

                                    ShowMessage("Resetting map!");
                                    Field.Reset();

                                    SendMap();



                                    StopCrudeMapReset();
                                }
                            );
                        }
                    }
                };

            Field.GameResetByLocalPlayer +=
                delegate
                {
                    SendMap();
                    ShowMessage("Try not to blow up, okay?");
                    StopCrudeMapReset();
                };

            Field.OneStepClosedToTheEnd +=
                LocalPlayer =>
                {
                  
                    if (LocalPlayer)
                    {
                        LocalPlayerFieldsOpened++;

                        // every 8 clicks gets your penalty down by one
                        if (LocalPlayerFieldsOpened % 8 == 0)
                        {
                            if (DisallowClicksMultiplier > DisallowClicksMultiplierMin)
                            {
                                DisallowClicksMultiplier = (DisallowClicksMultiplier - 1).Max(DisallowClicksMultiplierMin);

                                ShowMessage("Your penalty multiplier is " + DisallowClicksMultiplier);
                            }
                        }

                        if (LocalPlayerFieldsOpened < 10)
                            AddScore(1);
                        else
                            AddScore(2);

                  
                       
                    }

                    if (!GameIsLocked)
                    {
                        var BadState = Field.Buttons.Count(i => i.HasInvalidStateForCompletion);
                        var IsMined = Field.Buttons.Count(i => i.IsMined);
                        var HiddenMinesPercentage = (BadState / (double)IsMined).Min(1);

                        if (HiddenMinesPercentage < 0.5)
                        {
                            GameIsLocked.Value = true;

                            if (LocalPlayer)
                                Messages.LockGame();

                            ShowMessage("You are half way through! Game is locked until next map.");
                        }
                    }
                };

            Field.AttachTo(MapContainer);


            var MyColor = 0xffffff.Random().ToInt32();

            Field.mouseMove +=
                e =>
                {

                    Messages.MouseMove(e.stageX.ToInt32(), e.stageY.ToInt32(), MyColor);
                };


            //// menu for private game

            //MapContainer.filters = new[] { new BlurFilter() };
            //MapContainer.mouseChildren = false;

            //var LobbyMeny = new Sprite().AttachTo(this);

            //// http://snipplr.com/view/7050/as3-creating-a-gradient-rectangle/


            //var colors = new uint[2];
            //colors[0] = 1;
            //colors[1] = 0xffffff;

            //var alphas = new double[2];

            //alphas[0] = 0.5;
            //alphas[1] = 0.2;

            //var ratios = new int[2];

            //alphas[0] = 1;
            //alphas[1] = 255;


            //LobbyMeny.graphics.beginGradientFill("linear", colors, alphas, ratios);
            //LobbyMeny.graphics.drawRect(0, 0, stage.width, 200);


            //var Password = new TextField
            //{
            //    defaultTextFormat = new TextFormat
            //    {
            //        size = 24
            //    },
            //    text = "For private game\nenter your password:"******"thomas", "arsenal", "monkey", "charlie", "letmein", "123" }.Random(),
            //    type = TextFieldType.INPUT,
            //    background = true,
            //    backgroundColor = 0xffffff,
            //    border = true,
            //    borderColor = 0x909090,
            //};

            //var h = PasswordInput.height;

            //PasswordInput.autoSize = TextFieldAutoSize.NONE;
            //PasswordInput.width = Password.width;
            //PasswordInput.height = h;
            //PasswordInput.MoveTo(Password.x, Password.y + 8 + Password.height).AttachTo(LobbyMeny);

        }