Exemplo n.º 1
0
        /// <summary>
        /// Loads the component and any resources or dependencies it might have.
        /// Called during initialization of the component
        /// </summary>
        /// <returns>Returns an awaitable Task</returns>
        protected override Task Load()
        {
            if (this.weatherStates.Count == 0)
            {
                return(Task.FromResult(0));
            }

            this.CurrentWeather = this.weatherStates.AnyOrDefaultFromWeight(state => state.OccurrenceProbability);
            if (this.CurrentWeather == null)
            {
                throw new InvalidZoneException(this, "The zone was not able to initialize with the weather states provided to it.");
            }

            this.weatherClock = new EngineTimer <IWeatherState>(this.CurrentWeather);

            // Start the weather timer, converting the minutes specified
            // with WeatherUpdateFrequency to in-game minutes using the GameTimeRatio.
            this.weatherClock.Start(
                0,
                TimeSpan.FromMinutes(this.WeatherUpdateFrequency * this.Owner.Owner.GameTimeAdjustmentFactor).TotalMilliseconds,
                0,
                this.SetupWeather);

            return(Task.FromResult(0));
        }
        public async Task Delete_game_will_delete_adapter()
        {
            // Arrange
            var configuration = Mock.Of <IGameConfiguration>(mock => mock.GetAdapters() == new IAdapter[1] {
                new AdapterFixture()
            });
            var game = new MudGame();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            await game.Configure(configuration);

            IAdapter[] adapters = game.Configuration.GetAdapters();

            // Act
            game.BeginStart(async(runningGame) => await game.Delete());
            var timer = new EngineTimer <AdapterFixture>((AdapterFixture)adapters[0]);

            timer.Start(TimeSpan.FromSeconds(20).TotalMilliseconds, 0, 1, (fixture, runningTimer) =>
            {
                runningTimer.Stop();
            });

            while (!((AdapterFixture)adapters[0]).IsDeleted)
            {
                await Task.Delay(1);

                if (!timer.IsRunning)
                {
                    break;
                }
            }

            // Assert
            Assert.IsTrue(((AdapterFixture)adapters[0]).IsDeleted);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Starts the state clock at the specified interval, firing the callback provided.
 /// </summary>
 /// <param name="interval">The interval.</param>
 /// <param name="callback">The callback.</param>
 private void StartStateClock(double interval, Action <TimeOfDay> callback)
 {
     // If the minute interval is less than 1 second,
     // then we increment by the hour to reduce excess update calls.
     this.timeOfDayClock = new EngineTimer <TimeOfDay>(this.CurrentTime);
     this.timeOfDayClock.Start(interval, interval, 0, (state, clock) =>
     {
         callback(state);
         this.OnTimeUpdated();
     });
 }
Exemplo n.º 4
0
        /// <summary>
        /// Setups the weather up.
        /// </summary>
        private void SetupWeather(IWeatherState state, EngineTimer <IWeatherState> timer)
        {
            // Set the current weather based on the probability of it changing.
            IWeatherState nextWeatherState = this.weatherStates.AnyOrDefaultFromWeight(weather => weather.OccurrenceProbability);

            if (nextWeatherState != this.CurrentWeather)
            {
                this.CurrentWeather = nextWeatherState;
                this.OnWeatherChanged(null, this.CurrentWeather);
            }
        }
Exemplo n.º 5
0
        public void Ctor_sets_state_property()
        {
            // Arrange
            var fixture = new ComponentFixture();

            // Act
            var engineTimer = new EngineTimer <ComponentFixture>(fixture);

            // Assert
            Assert.IsNotNull(engineTimer.StateData, "State was not assigned from the constructor.");
            Assert.AreEqual(fixture, engineTimer.StateData, "An incorrect State object was assigned to the timer.");
        }
Exemplo n.º 6
0
        public void Start_sets_is_running()
        {
            // Arrange
            var fixture     = new ComponentFixture();
            var engineTimer = new EngineTimer <ComponentFixture>(fixture);

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => { });

            // Assert
            Assert.IsTrue(engineTimer.IsRunning, "Engine Timer was not started.");
        }
Exemplo n.º 7
0
        public void Start_sets_is_running()
        {
            // Arrange
            var fixture = new ComponentFixture();
            var engineTimer = new EngineTimer<ComponentFixture>(fixture);

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => { });

            // Assert
            Assert.IsTrue(engineTimer.IsRunning, "Engine Timer was not started.");
        }
Exemplo n.º 8
0
        public void Ctor_sets_state_property()
        {
            // Arrange
            var fixture = new ComponentFixture();

            // Act
            var engineTimer = new EngineTimer<ComponentFixture>(fixture);

            // Assert
            Assert.IsNotNull(engineTimer.StateData, "State was not assigned from the constructor.");
            Assert.AreEqual(fixture, engineTimer.StateData, "An incorrect State object was assigned to the timer.");
        }
Exemplo n.º 9
0
        public void finalize()
        {
            sprite.Dispose();

            TextureManager.Instance.Dispose();
            ModelManager.Instance.Dispose();
            EffectManager.Instance.Dispose();
            TerrainMeshManager.Instance.Dispose();

            FileSystem.Instance.Dispose();

            EngineTimer.Dispose();
        }
Exemplo n.º 10
0
        public async Task Stop_disables_the_timer()
        {
            // Arrange
            var fixture     = new ComponentFixture();
            var engineTimer = new EngineTimer <ComponentFixture>(fixture);

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => timer.Stop());
            await Task.Delay(20);

            // Assert
            Assert.IsFalse(engineTimer.IsRunning, "Engine Timer was not started.");
        }
Exemplo n.º 11
0
        public async Task Stop_disables_the_timer()
        {
            // Arrange
            var fixture = new ComponentFixture();
            var engineTimer = new EngineTimer<ComponentFixture>(fixture);

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => timer.Stop());
            await Task.Delay(20);

            // Assert
            Assert.IsFalse(engineTimer.IsRunning, "Engine Timer was not started.");
        }
Exemplo n.º 12
0
        public void Callback_invoked_when_running()
        {
            // Arrange
            var  fixture         = new ComponentFixture();
            var  engineTimer     = new EngineTimer <ComponentFixture>(fixture);
            bool callbackInvoked = false;

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => { callbackInvoked = true; });
            Task.Delay(20);

            // Assert
            Assert.IsTrue(callbackInvoked, "Engine Timer did not invoke the callback as expected.");
        }
Exemplo n.º 13
0
        public async Task Timer_stops_when_number_of_fires_is_hit()
        {
            // Arrange
            var fixture       = new ComponentFixture();
            var engineTimer   = new EngineTimer <ComponentFixture>(fixture);
            int callbackCount = 0;

            // Act
            engineTimer.Start(0, 1, 2, (component, timer) => { callbackCount += 1; });
            await Task.Delay(TimeSpan.FromSeconds(2));

            // Assert
            Assert.IsFalse(engineTimer.IsRunning, "Timer was not stopped.");
            Assert.AreEqual(2, callbackCount, "Engine Timer did not invoke the callback as expected.");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sets up the weather condition in the zone by evaluating the available weather states
        /// and changing the state if needed.
        /// </summary>
        /// <param name="state">The current weather state.</param>
        /// <param name="timer">The zone timer that is responsible for updating the weather state.</param>
        void SetupWeather(IWeatherState state, EngineTimer <IWeatherState> timer)
        {
            IWeatherState nextState = this.weatherStates.AnyOrDefaultFromWeight(weather => weather.OccurrenceProbability);

            if (nextState == null)
            {
                return;
            }

            var initialState = this.CurrentWeather;

            this.CurrentWeather = nextState;

            this.OnWeatherChanged(initialState, nextState);
            timer.SetState(nextState);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes the zone with the supplied realm.
        /// </summary>
        /// <param name="realm">The realm.</param>
        public virtual void Initialize(DefaultRealm realm)
        {
            this.realm = realm;

            if (this.weatherStates.Count > 0)
            {
                // Set up our weather clock and start performing weather changes.
                var weatherClock = new EngineTimer <IWeatherState>(this.CurrentWeather);

                // Convert the minutes specified with WeatherUpdateFrequency to in-game minutes using the GameTimeRatio.
                weatherClock.Start(
                    0,
                    TimeSpan.FromMinutes(this.WeatherUpdateFrequency * this.realm.World.GameTimeAdjustmentFactor).TotalMilliseconds,
                    0,
                    this.SetupWeather);
            }
        }
        /// <summary>
        /// Reviews the client connection states and cleans up orphaned player connections.
        /// </summary>
        /// <param name="adapter">The server adapter.</param>
        /// <param name="timer">The timer running to initiate the review.</param>
        private void ReviewClientConnectionStates(IAdapter adapter, EngineTimer <IAdapter> timer)
        {
            var connectedClients = this.playerConnections.ToArray();

            foreach (KeyValuePair <IPlayer, IConnection> pair in connectedClients)
            {
                IPlayer     player     = pair.Key;
                IConnection connection = pair.Value;
                if (connection.IsConnectionValid())
                {
                    continue;
                }

                this.PublishMessage(new InfoMessage("Player connection timed out."));
                this.Disconnect(player);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <returns>Returns an awaitable Task</returns>
        public Task Initialize()
        {
            // Set up our auto-save if the frequency is set for it.
            if (this.AutoSaveFrequency < 1)
            {
                return(Task.FromResult(false));
            }

            this.autosaveTimer = new EngineTimer <T>(this.ItemToSave);
            double autosaveInterval = TimeSpan.FromMinutes(this.AutoSaveFrequency).TotalMilliseconds;

            this.autosaveTimer.StartAsync(
                autosaveInterval,
                autosaveInterval,
                0,
                (game, timer) => this.saveDelegate());

            return(Task.FromResult(true));
        }
Exemplo n.º 18
0
        public Ship(
            IParticleEngine particleEngine,
            IRandomizer randomizer,
            ShipState?state = null)
        {
            _particleEngine = particleEngine ?? throw new ArgumentNullException(nameof(particleEngine));
            _randomizer     = randomizer ?? throw new ArgumentNullException(nameof(randomizer));
            // Size = Vector2.Zero;
            //AngularVelocity = 1f;

            EngineTimer.EveryNumOfSeconds = 0.5f;
            EngineTimer.Restart();

            ExplosionTimer.EveryNumOfSeconds = 0.3f;
            ExplosionTimer.Restart();
            if (state != null)
            {
                foreach (var spriteState in state.Balls)
                {
                    shipBullets.Add(new Ball(_randomizer, new GameTimer())
                    {
                        State = spriteState
                    });
                }
            }
            else
            {
                state = new ShipState();
                state.SpriteState.Size            = Vector2.Zero;
                state.SpriteState.AngularVelocity = 1f;
                for (int i = 0; i < 4; i++)
                {
                    var ball = new Ball(_randomizer, new GameTimer());
                    shipBullets.Add(ball);
                    state.Balls.Add(ball.State);
                }
            }
            State       = state;
            SpriteState = state.SpriteState;
        }
        /// <summary>
        /// Initializes the component.
        /// </summary>
        /// <returns>
        /// Returns an awaitable Task
        /// </returns>
        public override Task Initialize()
        {
            if (this.Configuration == null)
            {
                throw new InvalidAdapterStateException(this, $"The {this.Name} adapter requires a valid {typeof(IServerConfiguration).Name} to be provided to it. Please provide one via the {nameof(this.Configure)}({typeof(IServerConfiguration).Name}) method.");
            }
            else if (this.Status != ServerStatus.Stopped)
            {
                throw new InvalidAdapterStateException(this, $"The {this.Name} adapter has already been initialized.");
            }
            else if (this.Configuration.Port > 0)
            {
                this.RunningPort = this.Configuration.Port;
            }

            this.playerConnections  = new Dictionary <IPlayer, IConnection>();
            this.playerSockets      = new Dictionary <IPlayer, Socket>();
            this.Status             = ServerStatus.Stopped;
            this.clientTimeoutTimer = new EngineTimer <IAdapter>(this);

            return(Task.FromResult(0));
        }
Exemplo n.º 20
0
        public async Task Timer_stops_when_number_of_fires_is_hit()
        {
            // Arrange
            var fixture = new ComponentFixture();
            var engineTimer = new EngineTimer<ComponentFixture>(fixture);
            int callbackCount = 0;

            // Act
            engineTimer.Start(0, 1, 2, (component, timer) => { callbackCount += 1; });
            await Task.Delay(TimeSpan.FromSeconds(2));

            // Assert
            Assert.IsFalse(engineTimer.IsRunning, "Timer was not stopped.");
            Assert.AreEqual(2, callbackCount, "Engine Timer did not invoke the callback as expected.");
        }
Exemplo n.º 21
0
        /// <summary>
        /// Sets up the weather condition in the zone by evaluating the available weather states 
        /// and changing the state if needed.
        /// </summary>
        /// <param name="state">The current weather state.</param>
        /// <param name="timer">The zone timer that is responsible for updating the weather state.</param>
        void SetupWeather(IWeatherState state, EngineTimer<IWeatherState> timer)
        {
            IWeatherState nextState = this.weatherStates.AnyOrDefaultFromWeight(weather => weather.OccurrenceProbability);
            if (nextState == null)
            {
                return;
            }

            var initialState = this.CurrentWeather;
            this.CurrentWeather = nextState;

            this.OnWeatherChanged(initialState, nextState);
            timer.SetState(nextState);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Loads the component and any resources or dependencies it might have.
        /// Called during initialization of the component
        /// </summary>
        /// <returns>Returns an awaitable Task</returns>
        protected override Task Load()
        {
            if (this.weatherStates.Count == 0)
            {
                return Task.FromResult(0);
            }

            this.CurrentWeather = this.weatherStates.AnyOrDefaultFromWeight(state => state.OccurrenceProbability);
            if (this.CurrentWeather == null)
            {
                throw new InvalidZoneException(this, "The zone was not able to initialize with the weather states provided to it.");
            }

            this.weatherClock = new EngineTimer<IWeatherState>(this.CurrentWeather);

            // Start the weather timer, converting the minutes specified 
            // with WeatherUpdateFrequency to in-game minutes using the GameTimeRatio.
            this.weatherClock.Start(
                0,
                TimeSpan.FromMinutes(this.WeatherUpdateFrequency * this.Owner.Owner.GameTimeAdjustmentFactor).TotalMilliseconds,
                0,
                this.SetupWeather);

            return Task.FromResult(0);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Setups the weather up.
 /// </summary>
 private void SetupWeather(IWeatherState state, EngineTimer<IWeatherState> timer)
 {
     // Set the current weather based on the probability of it changing.
     IWeatherState nextWeatherState = this.weatherStates.AnyOrDefaultFromWeight(weather => weather.OccurrenceProbability);
     if (nextWeatherState != this.CurrentWeather)
     {
         this.CurrentWeather = nextWeatherState;
         this.OnWeatherChanged(null, this.CurrentWeather);
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Initializes the zone with the supplied realm.
        /// </summary>
        /// <param name="realm">The realm.</param>
        public virtual void Initialize(DefaultRealm realm)
        {
            this.realm = realm;

            if (this.weatherStates.Count > 0)
            {
                // Set up our weather clock and start performing weather changes.
                var weatherClock = new EngineTimer<IWeatherState>(this.CurrentWeather);

                // Convert the minutes specified with WeatherUpdateFrequency to in-game minutes using the GameTimeRatio.
                weatherClock.Start(
                    0,
                    TimeSpan.FromMinutes(this.WeatherUpdateFrequency * this.realm.World.GameTimeAdjustmentFactor).TotalMilliseconds,
                    0,
                    this.SetupWeather);
            }
        }
Exemplo n.º 25
0
        public void Callback_invoked_when_running()
        {
            // Arrange
            var fixture = new ComponentFixture();
            var engineTimer = new EngineTimer<ComponentFixture>(fixture);
            bool callbackInvoked = false;

            // Act
            engineTimer.Start(0, 1, 0, (component, timer) => { callbackInvoked = true; });
            Task.Delay(20);

            // Assert
            Assert.IsTrue(callbackInvoked, "Engine Timer did not invoke the callback as expected.");
        }
Exemplo n.º 26
0
        public async Task Delete_game_will_delete_adapter()
        {
            // Arrange
            var configuration = Mock.Of<IGameConfiguration>(mock => mock.GetAdapters() == new IAdapter[1] { new AdapterFixture() });
            var game = new MudGame();
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            await game.Configure(configuration);

            IAdapter[] adapters = game.Configuration.GetAdapters();

            // Act
            game.BeginStart(async (runningGame) => await game.Delete());
            var timer = new EngineTimer<AdapterFixture>((AdapterFixture)adapters[0]);
            timer.Start(TimeSpan.FromSeconds(20).TotalMilliseconds, 0, 1, (fixture, runningTimer) =>
            {
                runningTimer.Stop();
            });

            while (!((AdapterFixture)adapters[0]).IsDeleted)
            {
                await Task.Delay(1);
                if (!timer.IsRunning)
                {
                    break;
                }
            }

            // Assert
            Assert.IsTrue(((AdapterFixture)adapters[0]).IsDeleted);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Starts the state clock at the specified interval, firing the callback provided.
 /// </summary>
 /// <param name="interval">The interval.</param>
 /// <param name="callback">The callback.</param>
 private void StartStateClock(double interval, Action<TimeOfDay> callback)
 {
     // If the minute interval is less than 1 second,
     // then we increment by the hour to reduce excess update calls.
     this.timeOfDayClock = new EngineTimer<TimeOfDay>(this.CurrentTime);
     this.timeOfDayClock.Start(interval, interval, 0, (state, clock) =>
         {
             callback(state);
             this.OnTimeUpdated();
         });
 }