Exemplo n.º 1
0
        public HudScore()
        {
            Graphic = TextScore;

            X = Game.Instance.Width - 100;
            Y = 10;

            TextScore.DefaultShadowX = 1;
            TextScore.DefaultShadowY = 1;
            TextScore.TextAlign      = TextAlign.Right;

            TextScore.TextWidth = 200;

            EventRouter.Subscribe(Events.ScoreUpdated, (EventRouter.Event e) => {
                var score           = e.GetData <float>(0);
                var scoreMultiplier = e.GetData <float>(1);

                TextScore.String = string.Format("{0:0,0} x {1:0,0}", score, scoreMultiplier);

                TextScore.X = -120;
            });

            EventRouter.Subscribe(Events.ShowFinalScore, (EventRouter.Event e) => {
                var score = e.GetData <float>(0);
                TextScore.DefaultCharColor = Color.Gold;
                TextScore.String           = string.Format("{0:0,0}", score);
            });

            EventRouter.Subscribe(Events.GameStarted, (EventRouter.Event e) => {
                TextScore.DefaultCharColor = Color.White;
            });

            Layer = -1000;
        }
Exemplo n.º 2
0
        void UpdatePlaying()
        {
            if (GameStateMachine.Timer % 75 == 0)
            {
                float wallY = 0, secondWallY = 0;
                wallY       = Rand.Float(-430, -210);
                secondWallY = wallY + CurrentGap + 480;

                if (CurrentGap > 60)
                {
                    CurrentGap -= 5;
                }
                else
                {
                    CurrentGap -= 2;
                }

                CurrentGap = (int)Util.Clamp(CurrentGap, MinGap, MaxGap);

                Scene.Add(new Wall(700, wallY));
                Scene.Add(new Wall(700, secondWallY));
            }
            if (GameStateMachine.Timer % 60 == 0)
            {
                Score++;
            }

            EventRouter.Publish(Events.ScoreUpdated, Score, ScoreMultiplier);
        }
Exemplo n.º 3
0
        public GameManager() : base()
        {
            Session = Game.Instance.Session(0);
            AddComponent(GameStateMachine);
            Session.LoadData();

            BestScore = float.Parse(Session.GetData("best", "0"));

            EventRouter.Subscribe(Events.FlippyFlipped, (EventRouter.Event e) => {
                ScoreMultiplier += 1;
            });

            EventRouter.Subscribe(Events.FlippyDied, (EventRouter.Event e) => {
                GameStateMachine.ChangeState(GameState.End);
            });

            EventRouter.Subscribe(Events.UpdateBestScore, (EventRouter.Event e) => {
                Session.Data["best"] = BestScore.ToString();
                Session.SaveData();
            });

            R = Game.Instance.Color.R;
            G = Game.Instance.Color.G;
            B = Game.Instance.Color.B;
        }
Exemplo n.º 4
0
        public HudHighScore()
        {
            AddGraphic(TextScore);

            TextScore.DefaultShadowX = 1;
            TextScore.DefaultShadowY = 1;

            TextScore.X = 10;
            TextScore.Y = 10;

            EventRouter.Subscribe(Events.UpdateBestScore, (EventRouter.Event e) => {
                var score = e.GetData <float>(0);
                var last  = e.GetData <float>(1);

                if (last > 0)
                {
                    TextScore.String = string.Format("BEST {0:0,0} LAST {1:0,0}", score, last);
                }
                else
                {
                    if (score > 0)
                    {
                        TextScore.String = string.Format("BEST {0:0,0}", score);
                    }
                }
            });
        }
Exemplo n.º 5
0
        public void TrackEventTest()
        {
            IWorkContext context  = WorkContext.Empty;
            var          listener = new TrackEventEtwListener("EtwEventTests.TrackEventTest");

            using (var eventListener = new EventSourceListener())
            {
                eventListener.EnableEvents(listener, EventLevel.LogAlways);

                using (EventRouter router = new EventRouter(context).Register("test", (x, _) => listener.Post(x)))
                {
                    TrackEventSource source = new TrackEventSource(router, "test");

                    source.Verbose(context, "first message");
                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    eventListener.EventDataItems.Count.Should().Be(1);
                    EventData eventData = eventListener.EventDataItems[0];

                    eventData.EventSourceName.Should().Be("test");
                    eventData.EventName.Should().Be("Verbose");
                    eventData.TelemetryLevel.Should().Be(TelemetryLevel.Verbose);
                    eventData.Cv.Should().Be(context.Cv.ToString());
                    eventData.Tag.Should().Be(context.Tag.ToString());
                }
            }
        }
Exemplo n.º 6
0
        public void TestRoutedEvents()
        {
            var routedEvent = new EventRouter <string>();

            var assertionCount = 0;

            var assertionIncrementCheck = new Action <Action>((a) =>
            {
                var origCount = assertionCount;
                a();
                Assert.AreEqual(origCount + 1, assertionCount);
            });

            routedEvent.RegisterOnce("Home/{Page}", (args) =>
            {
                Assert.AreEqual("thepage", args.RouteVariables["page"]);
                Assert.AreEqual(args.Data, "Foo");
                assertionCount++;
            });

            assertionIncrementCheck(() =>
            {
                routedEvent.Route("Home/ThePage", "Foo");
            });
            Console.WriteLine(assertionCount);
        }
Exemplo n.º 7
0
        public void LoadExtension(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return;
            }

            _fileName = fileName;

            Assembly assembly = LoadAssembly(fileName);

            if (!_loadedAssemblyList.ContainsKey(assembly.FullName))
            {
                _loadedAssemblyList.Add(assembly.FullName, assembly);
            }
            foreach (Type t in assembly.GetTypes())
            {
                if (t.GetInterface("IExtension") != null)
                {
                    IExtension extension = (IExtension)assembly.CreateInstance(t.FullName);
                    if (extension != null &&
                        ExtensionManager.GetInstance().GetExtensionByName(extension.GetExtensionName()) == null &&
                        !_extensionList.ContainsKey(extension.GetExtensionName()))
                    {
                        _extensionList.Add(extension.GetExtensionName(), extension);
                        EventRouter.GetInstance().FireEvent("Extension_Loaded", (object)extension, null);
                        Console.WriteLine(
                            $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/ExtensionManager]:{extension.GetExtensionName()} has been loaded");
                    }
                }
            }
        }
Exemplo n.º 8
0
            public InstanceWithRoutes()
            {
                _sut             = new EventRouter();
                _registeredRoute = new CapturingRoute();

                _sut.RegisterRoute <EventWithRegisteredRoute>(_registeredRoute.Capture);
            }
Exemplo n.º 9
0
        //Initialize whenever agent is set to a new value
        bool Initialize(Component newAgent)
        {
            //purge cached reference whenever we init new agent
            _eventRouter = null;

            //"Transform" the agent to the agentType and set as current
            _currentAgent = newAgent.TransformToType(agentType);

            //error if it's null but an agentType is required
            if (_currentAgent == null && agentType != null)
            {
                return(Error("Failed to resolve Agent to requested type '" + agentType + "', or new Agent is NULL. Does the Agent has the requested Component?"));
            }

            //Use the field attributes
            if (InitializeFieldAttributes(_currentAgent) == false)
            {
                return(false);
            }

            //let user make further adjustments and inform us if there was an error
            var error = OnInit();

            if (error != null)
            {
                return(Error(error));
            }

            return(true);
        }
Exemplo n.º 10
0
            /// <summary>
            /// 创建事件代理对象
            /// </summary>
            /// <param name="argsType">事件数据类型</param>
            /// <returns>代理对象实例</returns>
            public IEventChannel GetEventChannel(Type argsType)
            {
                if (argsType == null)
                {
                    return(null);
                }
                var rval = EventChannels.GetOrAdd(
                    argsType,
                    t =>
                {
                    try
                    {
                        var t2 = typeof(EventChannel <>).MakeGenericType(t);
                        return(Activator.CreateInstance(t2, this) as IEventChannel);
                    }
                    catch (Exception ex)
                    {
                        EventRouter.RaiseErrorEvent(this, ex);
                    }
                    return(null);
                }
                    );



                return(rval);
            }
Exemplo n.º 11
0
        public void TrackEventLogFileWithManagementTest()
        {
            IWorkContext context    = WorkContext.Empty;
            string       tempFolder = Path.Combine(Path.GetTempPath(), "TelemetryTest");

            Directory.CreateDirectory(tempFolder);
            TrackEventMemoryListener listener;

            using (EventRouter router = new EventRouter(context))
            {
                listener = router.SetMemoryListener();
                TrackEventSource source = new TrackEventSource(router, "test");

                source.Verbose(context, "first message");
            }

            listener.Count.Should().Be(1);

            EventData eventData = listener.Dequeue();

            eventData.EventSourceName.Should().Be("test");
            eventData.EventName.Should().Be("Verbose");
            eventData.TelemetryLevel.Should().Be(TelemetryLevel.Verbose);
            eventData.Cv.Should().Be(context.Cv.ToString());
            eventData.Tag.Should().Be(context.Tag.ToString());
        }
        public ConfigurationManager()
        {
            this.pendingQueue = new List <IConfiguration>();

            this.resolvedDependencies = new Dictionary <DependencyName, object>();

            EventRouter.Subscribe <DependencyEvent, DependencyInfo>(this.DependencyResolvedHandler);
        }
Exemplo n.º 13
0
 void EnterEnd()
 {
     FinalScore = Score * ScoreMultiplier;
     BestScore  = Util.Max(FinalScore, BestScore);
     EventRouter.Publish(Events.ShowFinalScore, FinalScore);
     EventRouter.Publish(Events.UpdateBestScore, BestScore, FinalScore);
     Tween(this, new { Score = 0 }, 30);
 }
Exemplo n.º 14
0
 public void Initialize()
 {
     foreach (var extension in _extensionList)
     {
         extension.Value.Initialize();
         EventRouter.GetInstance().FireEvent("Extension_Initialize", null, extension.Value.GetExtensionName());
     }
 }
Exemplo n.º 15
0
 static ShoppingCart()
 {
     EventRouter = new EventRouterBuilder <ShoppingCart, IDomainEvent>
     {
         (ShoppingCart x, ShoppingCartCreated y) => x.Apply(y),
         (ShoppingCart x, ItemAddedToShoppingCart y) => x.Apply(y)
     }.Build();
 }
Exemplo n.º 16
0
        void EnterPlaying()
        {
            CurrentGap      = 180;
            Score           = 0;
            ScoreMultiplier = 1;

            Scene.Add(new Flippy(Session));
            EventRouter.Publish(Events.GameStarted);
            EventRouter.Publish(Events.UpdateBestScore, BestScore, FinalScore);
        }
Exemplo n.º 17
0
 /* INIT */
 void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
     else if (Instance != this)
     {
         Destroy(gameObject);
     }
 }
Exemplo n.º 18
0
 public void SetEnvironment(ExtensionManager extensionManager, EventRouter eventRouter, CronTab cronTab, BaseStorage storage, string rootPath)
 {
     ExtensionManager.GetInstance(extensionManager);
     EventRouter.GetInstance(eventRouter);
     //AppDomain.MonitoringIsEnabled = true;
     AppDomain.CurrentDomain.AssemblyResolve += _currentAppDomain_AssemblyResolve;
     _loadedAssemblyList = new Dictionary <string, Assembly>();
     _extensionList      = new Dictionary <string, IExtension>();
     _metaAssemblyList   = new Dictionary <string, Assembly>();
     IOManager.SetDefaultDataStorage(storage);
     IOManager.SetRootPath(rootPath);
     CronTab.GetInstance(cronTab);
 }
Exemplo n.º 19
0
        static void ExchangeTheSubscribedRouter(ListenToEventRouterDataBehavior bhv, EventRouter newRouter)
        {
            var targetEventRouter = newRouter ?? EventRouter.Instance;
            var query             = targetEventRouter.GetEventChannel <object>()
                                    .Where(x => string.IsNullOrEmpty(bhv.EventRoutingName) || bhv.EventRoutingName == x.EventName);


            var old = Interlocked.Exchange(
                ref bhv._oldSubscrption,
                query.Subscribe(e => bhv.LastDataReceived = e.EventData).MakeFinalizableDisposable());

            old?.Dispose();
        }
Exemplo n.º 20
0
        public override void Update()
        {
            base.Update();

            if (!Dead)
            {
                if (Session.Controller.A.Pressed)
                {
                    EventRouter.Publish(Events.FlippyFlipped);
                    Tween(Image, new { ScaleX = 1, ScaleY = 1 }, 45).From(new { ScaleX = 2f, ScaleY = 0.5f }).Ease(Ease.ElasticOut);
                    Tween(Image, new { Angle = 0 }, 30).From(new { Angle = Rand.Float(-10, 10) });
                    GravityDirection *= -1;
                    SpeedY           /= 4;
                }

                Scene.Add(new FlippyTrail(X, Y));
                Scene.Add(new FlippyTrail(X, Y + SpeedY * 0.005f));

                SpeedY += (int)(GravityDirection * GravityForce);
                SpeedY  = (int)Util.Clamp(SpeedY, -1000, 1000);

                Movement.MoveY(SpeedY);


                if (Overlap(X, Y, (int)Tags.Wall))
                {
                    Image.Color = Color.Red;
                    EventRouter.Publish(Events.FlippyDied);
                    Death();
                }
                if (Y < 50)
                {
                    EventRouter.Publish(Events.FlippyDied);
                    Death();
                }
                if (Y > Game.Instance.Height - 50)
                {
                    EventRouter.Publish(Events.FlippyDied);
                    Death();
                }
            }
            else
            {
                Image.Angle += 15;
            }
        }
Exemplo n.º 21
0
        public PageManager()
            : base()
        {
            this.mPageResourceGroup    = ResourceGroupManager.DefaultResourceGroupName;
            ArePagingOperationsEnabled = true;

            this.mEventRouter             = new EventRouter();
            this.mEventRouter.pManager    = this;
            this.mEventRouter.pWorlds     = this.mWorlds;
            this.mEventRouter.pCameraList = this.mCameraList;

            Root.Instance.FrameStarted += this.mEventRouter.FrameStarted;
            Root.Instance.FrameEnded   += this.mEventRouter.FrameEnded;

            CreateStandardStrategies();
            CreateStandardContentFactories();
        }
Exemplo n.º 22
0
        public void TrackEventLogFileTest()
        {
            IWorkContext context    = WorkContext.Empty;
            string       tempFolder = Path.Combine(Path.GetTempPath(), "TelemetryTest");

            Directory.CreateDirectory(tempFolder);
            string logFileName;

            using (var logWriter = new LogFileWriter(tempFolder).Open())
                using (EventRouter router = new EventRouter(context).Register("test", (x, _) => logWriter.Write(x)))
                {
                    logFileName = logWriter.LogFileName;

                    TrackEventSource source = new TrackEventSource(router, "test");

                    source.Verbose(context, "first message");
                }

            var readList = new List <EventData>();

            using (var reader = new LogFileReader(logFileName).Open())
            {
                while (true)
                {
                    IEnumerable <EventData> readItems = reader.Read(100);
                    readItems.Should().NotBeNull();
                    if (!readItems.Any())
                    {
                        break;
                    }

                    readList.AddRange(readItems);
                }
            }

            readList.Count.Should().Be(1);

            EventData eventData = readList[0];

            eventData.EventSourceName.Should().Be("test");
            eventData.EventName.Should().Be("Verbose");
            eventData.TelemetryLevel.Should().Be(TelemetryLevel.Verbose);
            eventData.Cv.Should().Be(context.Cv.ToString());
            eventData.Tag.Should().Be(context.Tag.ToString());
        }
Exemplo n.º 23
0
        public void TrackEventDrainFalseTest()
        {
            TrackEventSource source;

            IWorkContext context  = WorkContext.Empty;
            var          listener = new TrackEventMemoryListener();

            using (EventRouter router = new EventRouter(context, drainOnDispose: false).Register("test", (x, _) => listener.Post(x)))
            {
                source = new TrackEventSource(router, "test");

                listener.Count.Should().Be(0);

                source.Verbose(context, "first message");
            }

            listener.Count.Should().Be(0);
        }
Exemplo n.º 24
0
                public EventChannel(EventRouter router)
                {
                    var current   = this;
                    var argsType  = typeof(TEventData);
                    var basetypes = new List <Type>()
                    {
                        //argsType
                    };


                    for (; ;)
                    {
                        argsType = argsType.GetTypeInfo().BaseType;
                        if (argsType != null && argsType?.Name != "RuntimeClass")
                        {
                            basetypes.Add(argsType);
                        }
                        else
                        {
                            break;
                        }


                        if (router != null)
                        {
                            BaseClassTypeChannels = basetypes

                                                    .Select(x => router.GetEventChannel(x))
                                                    .Where(x => x != null)
                                                    .ToList();


                            ImplementedInterfaceTypeInstances = typeof(TEventData)
                                                                .GetTypeInfo()
                                                                .ImplementedInterfaces
                                                                .Where(x => x.Name[0] == 'I')
                                                                .Select(x =>
                                                                        router.GetEventChannel(x))
                                                                .Where(x => x != null)
                                                                .ToList();
                        }
                    }
                }
Exemplo n.º 25
0
        public void WakeUp(object sender, object eventArgs)
        {
            DateTime now = DateTime.Now;

            if (_isWakeUp)
            {
                return;
            }
            _isWakeUp = true;
            try
            {
                foreach (var taskConfig in _taskConfig)
                {
                    bool isAllComplete = taskConfig.ThreadPool.TrueForAll(item => !item.IsAlive);
                    if (isAllComplete)
                    {
                        taskConfig.ThreadPool.Clear();
                    }
                    if (taskConfig.NextDateTime.HasValue && taskConfig.NextDateTime <= DateTime.Now)
                    {
                        string executionId = Common.MD5(Clock.GetTimeStamp(true) + taskConfig.TargetType.Name);
                        if (taskConfig.ThreadPool.Count > 0 && !taskConfig.TargetType.IsAsync)
                        {
                            continue;
                        }
                        taskConfig.LastRunTime = now;
                        TaskThread thread = taskConfig.TargetType.Run(executionId);
                        taskConfig.ThreadPool.Add(thread);
                        taskConfig.GoNext();
                    }
                }
            }
            catch (Exception ex)
            {
                EventRouter.GetInstance().FireEvent("Error_Occurred", "CronTab",
                                                    "Fatal error:" + ex.GetBaseException().Message + "\n\t" + ex.GetBaseException().StackTrace);
            }
            finally
            {
                _isWakeUp = false;
            }
        }
Exemplo n.º 26
0
        public TaskThread Run(string executionId)
        {
            TaskThread taskThread = new TaskThread(new Thread((o) =>
            {
                try
                {
                    Method.Invoke(executionId);
                }
                catch (Exception ex)
                {
                    EventRouter.GetInstance().FireEvent("Warn_Occurred", this,
                                                        $"Execute task {Method} failed: {(ex.InnerException == null ? ex.Message : ex.InnerException.Message)}\nStack trace:\n{ex.StackTrace}");
                }
            }), MaximumExecuteTime, executionId)
            {
                CreateTime = DateTime.Now
            };

            return(taskThread);
        }
Exemplo n.º 27
0
        public Wall(float x, float y) : base(x, y)
        {
            Graphic = Image;
            SetHitbox(40, 480, (int)Tags.Wall);
            X     = 700;
            Layer = 10;

            Image.OutlineColor     = new Color("364298");
            Image.OutlineThickness = 4;

            if (Y < 0)
            {
                Tween(this, new { Y = Y }, 40).From(new { Y = Y - 480 }).Ease(Ease.ElasticOut);
            }
            else
            {
                Tween(this, new { Y = Y }, 40).From(new { Y = Y + 480 }).Ease(Ease.ElasticOut);
            }

            EventRouter.Subscribe(Events.FlippyDied, HandleDeath);
        }
Exemplo n.º 28
0
        public HudTitleInfo()
        {
            TextTitle.X   = Game.Instance.HalfWidth;
            TextDetails.X = Game.Instance.HalfWidth;
            TextWebzone.X = Game.Instance.HalfWidth;

            TextTitle.DefaultShadowX      = 3;
            TextTitle.DefaultShadowY      = 3;
            TextTitle.DefaultSineAmpY     = 10;
            TextTitle.DefaultSineRateY    = 10;
            TextTitle.DefaultOffsetAmount = 5;

            TextDetails.DefaultShadowX   = 1;
            TextDetails.DefaultShadowY   = 1;
            TextDetails.DefaultSineAmpX  = 1;
            TextDetails.DefaultSineAmpY  = 2;
            TextDetails.DefaultSineRateX = 5;
            TextDetails.DefaultSineRateY = 5;

            TextWebzone.DefaultCharColor = new Color("749ace");

            TextTitle.Refresh();
            TextDetails.Refresh();
            TextWebzone.Refresh();

            TextTitle.Y   = 200;
            TextDetails.Y = 300;
            TextWebzone.Y = 460;

            TextTitle.CenterOrigin();
            TextDetails.CenterOrigin();
            TextWebzone.CenterOrigin();

            AddGraphics(TextTitle, TextDetails, TextWebzone);

            EventRouter.Subscribe(Events.GameStarted, (EventRouter.Event e) =>
            {
                Tween(this, new { Y = 480 }, 30).Ease(Ease.BackIn);
            });
        }
Exemplo n.º 29
0
        public void TrackEventTest()
        {
            IWorkContext context  = WorkContext.Empty;
            var          listener = new TrackEventMemoryListener();

            using (EventRouter router = new EventRouter(context).Register("test", (x, _) => listener.Post(x)))
            {
                TrackEventSource source = new TrackEventSource(router, "test");

                listener.Count.Should().Be(0);

                source.Verbose(context, "first message");
                Thread.Sleep(TimeSpan.FromSeconds(1));
                listener.Count.Should().Be(1);

                EventData eventData = listener.Dequeue();
                eventData.EventSourceName.Should().Be("test");
                eventData.EventName.Should().Be("Verbose");
                eventData.TelemetryLevel.Should().Be(TelemetryLevel.Verbose);
                eventData.Cv.Should().Be(context.Cv.ToString());
                eventData.Tag.Should().Be(context.Tag.ToString());
            }
        }
Exemplo n.º 30
0
 private Order(List <IOrderEvent> evts)
 {
     evts.ForEach(e => EventRouter[e.GetType()](this, e));
 }
Exemplo n.º 31
0
		public PageManager()
			: base()
		{
			this.mPageResourceGroup = ResourceGroupManager.DefaultResourceGroupName;
			ArePagingOperationsEnabled = true;

			this.mEventRouter = new EventRouter();
			this.mEventRouter.pManager = this;
			this.mEventRouter.pWorlds = this.mWorlds;
			this.mEventRouter.pCameraList = this.mCameraList;

			Root.Instance.FrameStarted += this.mEventRouter.FrameStarted;
			Root.Instance.FrameEnded += this.mEventRouter.FrameEnded;

			CreateStandardStrategies();
			CreateStandardContentFactories();
		}
Exemplo n.º 32
0
 /// <summary>
 /// Initializes new instance of IEventRouter implementation
 /// </summary>
 /// <returns></returns>
 protected virtual IEventRouter InitEventRouter()
 {
     IEventRouter router = new EventRouter();
     router.PolymorphicInvokationEnabled = true;
     return router;
 }
Exemplo n.º 33
0
 void OnMapClicked(EventRouter.Event evt)
 {
     PaintTile(evt.GetData<int>(0), evt.GetData<int>(1));
 }
Exemplo n.º 34
0
 void HandleGlobalVolumeChange(EventRouter.Event e)
 {
     // Update volume (Volume setter does this, so set Volume to Volume)
     Volume = Volume;
 }
Exemplo n.º 35
0
        /// <summary>
        /// The PageManager is the entry point through which you load all PagedWorld instances, 
		/// and the place where PageStrategy instances and factory classes are
		/// registered to customise the paging behaviour.
        /// </summary>
        public PageManager()
        {
            mQueue = new PageRequestQueue(this);
            mPageResourceGroup = ResourceGroupManager.DefaultResourceGroupName;

            mEventRouter = new EventRouter();
            mEventRouter.pManager = this;
            mEventRouter.pWorlds = mWorlds;

            Root.Instance.FrameStarted += mEventRouter.FrameStarted;
            Root.Instance.FrameEnded += mEventRouter.FrameEnded;

            CreateStandardStrategies();
            CreateStandardContentFactories();
        }