Exemplo n.º 1
0
        private void _checkForWinner()
        {
            _checkTimerCancel = null;

            if (!_cfg.GetCVar(CCVars.GameLobbyEnableWin))
            {
                return;
            }

            IPlayerSession winner = null;

            foreach (var playerSession in _playerManager.GetAllPlayers())
            {
                var playerEntity = playerSession.AttachedEntity;
                if (playerEntity == null ||
                    !playerEntity.TryGetComponent(out IMobStateComponent state))
                {
                    continue;
                }

                if (!state.IsAlive())
                {
                    continue;
                }

                if (winner != null)
                {
                    // Found a second person alive, nothing decided yet!
                    return;
                }

                winner = playerSession;
            }

            _chatManager.DispatchServerAnnouncement(winner == null
                ? Loc.GetString("Everybody is dead, it's a stalemate!")
                : Loc.GetString("{0} wins the death match!", winner));

            var restartDelay = 10;

            _chatManager.DispatchServerAnnouncement(Loc.GetString("Restarting in {0} seconds.", restartDelay));

            Timer.Spawn(TimeSpan.FromSeconds(restartDelay), () => _gameTicker.RestartRound());
        }
        private void EnableOverlay(double duration)
        {
            // If the timer gets reset
            if (_overlay != null)
            {
                _overlay.Duration  = _duration;
                _overlay.StartTime = _startTime;
                _cancelToken.Cancel();
            }
            else
            {
                var overlayManager = IoCManager.Resolve <IOverlayManager>();
                _overlay = new FlashOverlay(_duration);
                overlayManager.AddOverlay(_overlay);
            }

            _cancelToken = new CancellationTokenSource();
            Timer.Spawn((int)duration * 1000, DisableOverlay, _cancelToken.Token);
        }
Exemplo n.º 3
0
        public bool InteractHand(InteractHandEventArgs eventArgs)
        {
            if (!_canHelp || !KnockedDown)
            {
                return(false);
            }

            _canHelp = false;
            Timer.Spawn(((int)_helpInterval * 1000), () => _canHelp = true);

            EntitySystem.Get <AudioSystem>()
            .PlayFromEntity("/Audio/effects/thudswoosh.ogg", Owner, AudioHelpers.WithVariation(0.25f));

            _knockdownTimer -= _helpKnockdownRemove;

            SetStatusEffect();

            return(true);
        }
        private void _checkForWinner()
        {
            _checkTimerCancel = null;

            IPlayerSession winner = null;

            foreach (var playerSession in _playerManager.GetAllPlayers())
            {
                if (playerSession.AttachedEntity == null ||
                    !playerSession.AttachedEntity.TryGetComponent(out IDamageableComponent damageable))
                {
                    continue;
                }

                if (damageable.CurrentDamageState != DamageState.Alive)
                {
                    continue;
                }

                if (winner != null)
                {
                    // Found a second person alive, nothing decided yet!
                    return;
                }

                winner = playerSession;
            }

            if (winner == null)
            {
                _chatManager.DispatchServerAnnouncement("Everybody is dead, it's a stalemate!");
            }
            else
            {
                // We have a winner!
                _chatManager.DispatchServerAnnouncement($"{winner} wins the death match!");
            }

            _chatManager.DispatchServerAnnouncement($"Restarting in 10 seconds.");

            Timer.Spawn(TimeSpan.FromSeconds(10), () => _gameTicker.RestartRound());
        }
        public CommunicationsConsoleMenu(CommunicationsConsoleBoundUserInterface owner)
        {
            IoCManager.InjectDependencies(this);

            Title = Loc.GetString("Communications Console");
            Owner = owner;

            _countdownLabel = new RichTextLabel()
            {
                CustomMinimumSize = new Vector2(0, 200)
            };
            _emergencyShuttleButton            = new Button();
            _emergencyShuttleButton.OnPressed += (e) => Owner.EmergencyShuttleButtonPressed();

            var vbox = new VBoxContainer()
            {
                SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand
            };

            vbox.AddChild(_countdownLabel);
            vbox.AddChild(_emergencyShuttleButton);

            var hbox = new HBoxContainer()
            {
                SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.FillExpand
            };

            hbox.AddChild(new Control()
            {
                CustomMinimumSize = new Vector2(100, 0), SizeFlagsHorizontal = SizeFlags.FillExpand
            });
            hbox.AddChild(vbox);
            hbox.AddChild(new Control()
            {
                CustomMinimumSize = new Vector2(100, 0), SizeFlagsHorizontal = SizeFlags.FillExpand
            });

            Contents.AddChild(hbox);

            UpdateCountdown();
            Timer.SpawnRepeating(1000, UpdateCountdown, _timerCancelTokenSource.Token);
        }
Exemplo n.º 6
0
        public void TestCancellation()
        {
            var timerManager = IoCManager.Resolve <ITimerManager>();
            var taskManager  = IoCManager.Resolve <ITaskManager>();

            var cts = new CancellationTokenSource();
            var ran = false;

            Timer.Spawn(1000, () => ran = true, cts.Token);

            timerManager.UpdateTimers(new FrameEventArgs(.5f));

            Assert.That(ran, Is.False);

            cts.Cancel();

            timerManager.UpdateTimers(new FrameEventArgs(.6f));

            Assert.That(ran, Is.False);
        }
Exemplo n.º 7
0
        public void TestAsyncDelay()
        {
            var timerManager = IoCManager.Resolve <ITimerManager>();
            var ran          = false;

            async void Run()
            {
                await Timer.Delay(TimeSpan.FromMilliseconds(500));

                ran = true;
            }

            Run();
            Assert.That(ran, Is.False);

            // Set timers ahead 250 ms
            timerManager.UpdateTimers(new FrameEventArgs(.25f));
            Assert.That(ran, Is.False);

            // Another 300ms should do it.
            timerManager.UpdateTimers(new FrameEventArgs(.30f));
            Assert.That(ran, Is.True);
        }
Exemplo n.º 8
0
        private void EndRound(Victory victory)
        {
            string text;

            switch (victory)
            {
            case Victory.Innocents:
                text = "The innocents have won!";
                break;

            case Victory.Traitors:
                text = "The traitors have won!";
                break;

            default:
                text = "Nobody wins!";
                break;
            }

            _gameTicker.EndRound(text);
            _chatManager.DispatchServerAnnouncement($"Restarting in 10 seconds.");
            _checkTimerCancel.Cancel();
            Timer.Spawn(TimeSpan.FromSeconds(10), () => _gameTicker.RestartRound());
        }
Exemplo n.º 9
0
        public override void Added()
        {
            _entityManager.EventBus.SubscribeEvent <MobDamageStateChangedMessage>(EventSource.Local, this, _onMobDamageStateChanged);

            Timer.SpawnRepeating(DeadCheckDelay, _checkWinConditions, _checkTimerCancel.Token);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Will try and get around obstacles if stuck
        /// </summary>
        protected void AntiStuck(float frameTime)
        {
            // TODO: More work because these are sketchy af
            // TODO: Check if a wall was spawned in front of us and then immediately dump route if it was

            // First check if we're still in a stuck state from last frame
            if (IsStuck && !_tryingAntiStuck)
            {
                switch (_antiStuckMethod)
                {
                case AntiStuckMethod.None:
                    break;

                case AntiStuckMethod.Jiggle:
                    var randomRange = IoCManager.Resolve <IRobustRandom>().Next(0, 359);
                    var angle       = Angle.FromDegrees(randomRange);
                    Owner.TryGetComponent(out AiControllerComponent mover);
                    mover.VelocityDir = angle.ToVec().Normalized;

                    break;

                case AntiStuckMethod.PhaseThrough:
                    if (Owner.TryGetComponent(out CollidableComponent collidableComponent))
                    {
                        // TODO Fix this because they are yeeting themselves when they charge
                        // TODO: If something updates this this will f**k it
                        collidableComponent.CanCollide = false;

                        Timer.Spawn(100, () =>
                        {
                            if (!collidableComponent.CanCollide)
                            {
                                collidableComponent.CanCollide = true;
                            }
                        });
                    }
                    break;

                case AntiStuckMethod.Teleport:
                    Owner.Transform.DetachParent();
                    Owner.Transform.GridPosition = NextGrid;
                    break;

                case AntiStuckMethod.ReRoute:
                    GetRoute();
                    break;

                case AntiStuckMethod.Angle:
                    var random = IoCManager.Resolve <IRobustRandom>();
                    _addedAngle = new Angle(random.Next(-60, 60));
                    IsStuck     = false;
                    Timer.Spawn(100, () =>
                    {
                        _addedAngle = Angle.Zero;
                    });
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }

            _stuckTimerRemaining -= frameTime;

            // Stuck check cooldown
            if (_stuckTimerRemaining > 0.0f)
            {
                return;
            }

            _tryingAntiStuck     = false;
            _stuckTimerRemaining = 0.5f;

            // Are we actually stuck
            if ((_ourLastPosition.Position - Owner.Transform.GridPosition.Position).Length < TileTolerance)
            {
                _antiStuckAttempts++;

                // Maybe it's just 1 tile that's borked so try next 1?
                if (_antiStuckAttempts >= 2 && _antiStuckAttempts < 5 && Route.Count > 1)
                {
                    var nextTile = Route.Dequeue();
                    NextGrid = _mapManager.GetGrid(nextTile.GridIndex).GridTileToLocal(nextTile.GridIndices);
                    return;
                }

                if (_antiStuckAttempts >= 5 || Route.Count == 0)
                {
                    Logger.DebugS("ai", $"{Owner} is stuck at {Owner.Transform.GridPosition}, trying new route");
                    _antiStuckAttempts = 0;
                    IsStuck            = false;
                    _ourLastPosition   = Owner.Transform.GridPosition;
                    GetRoute();
                    return;
                }
                Stuck?.Invoke();
                IsStuck = true;
                return;
            }

            IsStuck = false;

            _ourLastPosition = Owner.Transform.GridPosition;
        }
Exemplo n.º 11
0
        public void Update(float delta)
        {
            if (Stunned)
            {
                StunnedTimer -= delta;

                if (StunnedTimer <= 0)
                {
                    StunnedTimer = 0f;
                    Dirty();
                }
            }

            if (KnockedDown)
            {
                KnockdownTimer -= delta;

                if (KnockdownTimer <= 0f)
                {
                    StandingStateHelper.Standing(Owner);

                    KnockdownTimer = 0f;
                    Dirty();
                }
            }

            if (SlowedDown)
            {
                SlowdownTimer -= delta;

                if (SlowdownTimer <= 0f)
                {
                    SlowdownTimer = 0f;

                    if (Owner.TryGetComponent(out MovementSpeedModifierComponent movement))
                    {
                        movement.RefreshMovementSpeedModifiers();
                    }

                    Dirty();
                }
            }

            if (!StunStart.HasValue || !StunEnd.HasValue ||
                !Owner.TryGetComponent(out ServerStatusEffectsComponent status))
            {
                return;
            }

            var start = StunStart.Value;
            var end   = StunEnd.Value;

            var length   = (end - start).TotalSeconds;
            var progress = (_gameTiming.CurTime - start).TotalSeconds;

            if (progress >= length)
            {
                Timer.Spawn(250, () => status.RemoveStatusEffect(StatusEffect.Stun), StatusRemoveCancellation.Token);
                LastStun = null;
            }
        }
 private void SetupTimer()
 {
     TokenSource?.Cancel();
     TokenSource = new CancellationTokenSource();
     Timer.SpawnRepeating(TimeSpan.FromSeconds(IntervalSeconds), OnTimerFired, TokenSource.Token);
 }
Exemplo n.º 13
0
 public static void AddTimer(this IEntity entity, Timer timer, CancellationToken cancellationToken = default)
 {
     entity
     .EnsureComponent <TimerComponent>()
     .AddTimer(timer, cancellationToken);
 }