A task to be executed by the Scheduler. Stores timing information and state.
Ejemplo n.º 1
0
 ChatTimer( TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy )
 {
     if( startedBy == null ) throw new ArgumentNullException( "startedBy" );
     StartedBy = startedBy;
     Message = message;
     StartTime = DateTime.UtcNow;
     EndTime = StartTime.Add( duration );
     Duration = duration;
     int oneSecondRepeats = (int)duration.TotalSeconds + 1;
     if( duration > Hour ) {
         announceIntervalIndex = AnnounceIntervals.Length - 1;
         lastHourAnnounced = (int)duration.TotalHours;
     } else {
         for( int i = 0; i < AnnounceIntervals.Length; i++ ) {
             if( duration <= AnnounceIntervals[i] ) {
                 announceIntervalIndex = i - 1;
                 break;
             }
         }
     }
     task = Scheduler.NewTask( TimerCallback, this );
     Id = Interlocked.Increment( ref timerCounter );
     AddTimerToList( this );
     IsRunning = true;
     task.RunRepeating( TimeSpan.Zero,
                        TimeSpan.FromSeconds( 1 ),
                        oneSecondRepeats );
 }
Ejemplo n.º 2
0
        static void Beat( SchedulerTask scheduledTask ) {
            if( Server.IsShuttingDown ) return;

            if( ConfigKey.HeartbeatEnabled.Enabled() ) {
                SendMinecraftNetBeat();
                if( ConfigKey.IsPublic.Enabled() && ConfigKey.HeartbeatToWoMDirect.Enabled() ) {
                    SendWoMDirectBeat();
                }

            } else {
                // If heartbeats are disabled, the server data is written
                // to a text file instead (heartbeatdata.txt)
                string[] data = new[] {
                    Salt,
                    Server.InternalIP.ToString(),
                    Server.Port.ToStringInvariant(),
                    Server.CountPlayers( false ).ToStringInvariant(),
                    ConfigKey.MaxPlayers.GetString(),
                    ConfigKey.ServerName.GetString(),
                    ConfigKey.IsPublic.GetString(),
                    ConfigKey.WoMDirectDescription.GetString(),
                    ConfigKey.WoMDirectFlags.GetString(),
                    ConfigKey.HeartbeatToWoMDirect.Enabled().ToString()
                };
                const string tempFile = Paths.HeartbeatDataFileName + ".tmp";
                File.WriteAllLines( tempFile, data, Encoding.ASCII );
                Paths.MoveOrReplaceFile( tempFile, Paths.HeartbeatDataFileName );
            }
        }
Ejemplo n.º 3
0
 public ZombieGame( World world )
 {
     _world = world;
     startTime = DateTime.Now;
     _humanCount = _world.Players.Length;
     _task = new SchedulerTask( Interval, false ).RunForever( TimeSpan.FromSeconds( 1 ) );
     _world.gameMode = GameMode.ZombieSurvival;
     Player.Moved += OnPlayerMoved;
     Player.JoinedWorld += OnChangedWorld;
 }
Ejemplo n.º 4
0
 public static TeamDeathMatch GetInstance(World world)
 {
     if (instance == null)
     {
         TDMworld_ = world;
         instance = new TeamDeathMatch();
         startTime = DateTime.UtcNow;
         task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
     }
     return instance;
 }
Ejemplo n.º 5
0
 public ExplodingBug( Player p )
 {
     player = p;
     world = player.World;
     guild = GuildManager.PlayersGuild( player.Info );
     end = player.Position.ToBlockCoords();
     block = new Vector3I( end.X, end.Y, end.Z - 1 );
     Started = true;
     task = Scheduler.NewBackgroundTask( t => StartAI() ).RunForever( TimeSpan.FromMilliseconds( 230 ) );
     endTask = Scheduler.NewTask( t => Stop() ).RunOnce( TimeSpan.FromSeconds( 25 ) );
     player.PublicAuxStateObjects.Add( "bug", this );
 }
Ejemplo n.º 6
0
 public void Interval( SchedulerTask task )
 {
     //check to stop Interval
     if ( _world.gameMode != GameMode.ZombieSurvival || _world == null ) {
         _world = null;
         task.Stop();
         return;
     }
     if ( !_started ) {
         if ( startTime != null && ( DateTime.Now - startTime ).TotalMinutes > 1 ) {
             /*if (_world.Players.Length < 3){
                 _world.Players.Message("&WThe game failed to start: 2 or more players need to be in the world");
                 Stop(null);
                 return;
             }*/
             ShufflePlayerPositions();
             _started = true;
             RandomPick();
             lastChecked = DateTime.Now;
             return;
         }
     }
     //calculate humans
     _humanCount = _world.Players.Where( p => p.iName != _zomb ).Count();
     //check if zombies have won already
     if ( _started ) {
         if ( _humanCount == 1 && _world.Players.Count() == 1 ) {
             _world.Players.Message( "&WThe Zombies have failed to infect everyone... &9HUMANS WIN!" );
             Stop( null );
             return;
         }
         if ( _humanCount == 0 ) {
             _world.Players.Message( "&WThe Humans have failed to survive... &9ZOMBIES WIN!" );
             Stop( null );
             return;
         }
     }
     //check if 5mins is up and all zombies have failed
     if ( _started && startTime != null && ( DateTime.Now - startTime ).TotalMinutes > 6 ) {
         _world.Players.Message( "&WThe Zombies have failed to infect everyone... &9HUMANS WIN!" );
         Stop( null );
         return;
     }
     //if no one has won, notify players of their status every 31s
     if ( lastChecked != null && ( DateTime.Now - lastChecked ).TotalSeconds > 30 ) {
         _world.Players.Message( "&WThere are {0} humans", _humanCount.ToString() );
         foreach ( Player p in _world.Players ) {
             if ( p.iName == _zomb ) p.Message( "&8You are " + _zomb );
             else p.Message( "&8You are a Human" );
         }
         lastChecked = DateTime.Now;
     }
 }
Ejemplo n.º 7
0
 public void StartPerk()
 {
     if ( !Started ) {
         Started = true;
         if ( TimesToRepeat == -1 ) {
             task = Scheduler.NewTask( t => PerformAction() ).RunOnce( TimeSpan.FromMilliseconds( Delay ) );
         } else if ( TimesToRepeat == 0 ) {
             task = Scheduler.NewTask( t => PerformAction() ).RunForever( TimeSpan.FromMilliseconds( Delay ) );
         } else {
             task = Scheduler.NewTask( t => PerformAction() ).RunRepeating( TimeSpan.FromMilliseconds( Delay ), TimeSpan.FromMilliseconds( Delay ), TimesToRepeat );
         }
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Starts the game
        /// </summary>
        /// <param name="player">Player starting the game</param>
        public void Start( Player player )
        {
            if ( instance != null ) {
                player.Message( "Cannot start GuildGame: A game is already in progress" );
                return;
            }
            task = Scheduler.NewTask( t => Stop( Player.Console ) ).RunOnce( TimeSpan.FromMinutes( 5 ) );

            foreach ( Player p in Server.Players ) {
                if ( GuildManager.PlayersGuild( p.Info ) != null ) {
                    //they can play the game, so add them
                    p.PublicAuxStateObjects.Add( "GameEnabled", true );
                }
            }
        }
Ejemplo n.º 9
0
 public static ZombieGame GetInstance(World world)
 {
     if (instance == null)
     {
         _world = world;
         instance = new ZombieGame();
         startTime = DateTime.Now;
         _humanCount = _world.Players.Length;
         _world.Players.Message(_humanCount.ToString());
         Player.Moved += OnPlayerMoved;
         _task = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
         //_world.positions = new Player[_world.Map.Width,
                // _world.Map.Length, _world.Map.Height];
         _world.gameMode = GameMode.ZombieSurvival;
     }
     return instance;
 }
Ejemplo n.º 10
0
 public Turret( Player p )
 {
     player = p;
     world = p.World;
     guild = GuildManager.PlayersGuild( p.Info );
     end = player.Position.ToBlockCoords();
     Vector3I checkPos = new Vector3I( end.X, end.Y, end.Z - 2 );
     Block b = world.Map.GetBlock( checkPos );
     if ( Physics.BlockThrough( b ) ) {
         player.Message( "&WYou can only place a turret on the ground, not in the air" );
         return;
     }
     blocks = new Vector3I[] { new Vector3I( end ),
         new Vector3I( end.X, end.Y, end.Z - 1 ),
         new Vector3I( end.X, end.Y, end.Z + 1 ) };
     start = blocks[0];
     BuildTurret();
     task = Scheduler.NewBackgroundTask( t => StartAI() ).RunForever( TimeSpan.FromMilliseconds( 250 ) );
     AddTurretToList();
     lastTimeShot = DateTime.UtcNow;
 }
Ejemplo n.º 11
0
        static void Beat(SchedulerTask scheduledTask)
        {
            if (Server.IsShuttingDown)
            {
                return;
            }

            if (ConfigKey.HeartbeatEnabled.Enabled())
            {
                if (ClassiCube())
                {
                    SendClassiCubeBeat();
                }
                else
                {
                    SendMinecraftNetBeat();
                }
                SendLegendCraftNetBeat();
                HbSave();
            }
            else
            {
                // If heartbeats are disabled, the server data is written
                // to a text file instead (heartbeatdata.txt)
                string[] data = new[] {
                    Salt,
                    Server.InternalIP.ToString(),
                    Server.Port.ToString(),
                    Server.CountPlayers(false).ToString(),
                    ConfigKey.MaxPlayers.GetString(),
                    ConfigKey.ServerName.GetString(),
                    ConfigKey.IsPublic.GetString(),
                };
                const string tempFile = Paths.HeartbeatDataFileName + ".tmp";
                File.WriteAllLines(tempFile, data, Encoding.ASCII);
                Paths.MoveOrReplace(tempFile, Paths.HeartbeatDataFileName);
            }
        }
Ejemplo n.º 12
0
        static void ExecuteBackgroundTask(SchedulerTask task)
        {
            task.IsExecuting = true;
#if DEBUG_SCHEDULER
            FireEvent(TaskExecuting, task);
#endif

#if DEBUG
            task.Callback(task);
#else
            try {
                task.Callback(task);
            } catch (Exception ex) {
                Logger.LogAndReportCrash("Exception thrown by ScheduledTask callback", "fCraft", ex, false);
            } finally {
                task.IsExecuting = false;
            }
#endif

#if DEBUG_SCHEDULER
            FireEvent(TaskExecuted, task);
#endif
        }
Ejemplo n.º 13
0
        static void TimerCallback([NotNull] SchedulerTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            ChatTimer timer = (ChatTimer)task.UserState;

            if (task.MaxRepeats == 1)
            {
                if (String.IsNullOrEmpty(timer.Message))
                {
                    Server.Players.Message("&2[&7CountDown Finished&2]");
                    IRC.SendChannelMessage("\u212C&S[&7CountDown Finished&S]");
                }
                else
                {
                    Server.Players.Message("&2[&7Timer Finished&2] &7" + timer.Message);
                    IRC.SendChannelMessage("\u212C&S[&7Timer Finished&S]\u211C " + timer.Message);
                }
                //Timer Ends Here.
                timer.Stop(false);
            }
            else if (timer.announceIntervalIndex >= 0)
            {
                if (timer.lastHourAnnounced != (int)timer.TimeLeft.TotalHours)
                {
                    timer.lastHourAnnounced = (int)timer.TimeLeft.TotalHours;
                    timer.Announce(TimeSpan.FromHours(Math.Ceiling(timer.TimeLeft.TotalHours)));
                }
                if (timer.TimeLeft <= AnnounceIntervals[timer.announceIntervalIndex])
                {
                    timer.Announce(AnnounceIntervals[timer.announceIntervalIndex]);
                    timer.announceIntervalIndex--;
                }
            }
        }
Ejemplo n.º 14
0
 public static void drownCheck(SchedulerTask task)
 {
     try {
         foreach (Player p in Server.Players.Where(p => !p.Immortal))
         {
             if (p.World != null)   //ignore console
             {
                 if (p.World.waterPhysics)
                 {
                     Position pos = new Position(
                         ( short )(p.Position.X / 32),
                         ( short )(p.Position.Y / 32),
                         ( short )((p.Position.Z + 1) / 32)
                         );
                     if (p.WorldMap.GetBlock(pos.X, pos.Y, pos.Z) == Block.Water)
                     {
                         if (p.DrownTime == null || (DateTime.UtcNow - p.DrownTime).TotalSeconds > 33)
                         {
                             p.DrownTime = DateTime.UtcNow;
                         }
                         if ((DateTime.UtcNow - p.DrownTime).TotalSeconds > 30)
                         {
                             p.TeleportTo(p.WorldMap.Spawn);
                             p.World.Players.Message("{0}&S drowned and died", p.ClassyName);
                         }
                     }
                     else
                     {
                         p.DrownTime = DateTime.UtcNow;
                     }
                 }
             }
         }
     } catch (Exception ex) {
         Logger.Log(LogType.SeriousError, "" + ex);
     }
 }
Ejemplo n.º 15
0
 ChatTimer( TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy ) {
     if( startedBy == null ) throw new ArgumentNullException( "startedBy" );
     StartedBy = startedBy;
     Message = message;
     StartTime = DateTime.UtcNow;
     EndTime = StartTime.Add( duration );
     Duration = duration;
     int oneSecondRepeats = (int)duration.TotalSeconds + 1;
     if( duration > Hour ) {
         announceIntervalIndex = AnnounceIntervals.Length - 1;
         lastHourAnnounced = (int)duration.TotalHours;
     } else {
         for( int i = 0; i < AnnounceIntervals.Length; i++ ) {
             if( duration <= AnnounceIntervals[i] ) {
                 announceIntervalIndex = i - 1;
                 break;
             }
         }
     }
     task = Scheduler.NewTask( TimerCallback, this );
     ID = Interlocked.Increment( ref timerCounter );
     AddTimerToList( this );
     IsRunning = true;
     task.RunRepeating( TimeSpan.Zero,
                        TimeSpan.FromSeconds( 1 ),
                        oneSecondRepeats );
     try
     {
         if (!(Directory.Exists("./Timers"))) Directory.CreateDirectory("./Timers");
         string[] output = { "StartDate: " + StartTime.ToString(), "EndDate: " + EndTime.ToString(), "CreatedBy: " + StartedBy, "Message: " + Message };
         File.WriteAllLines("./Timers/" + EndTime.Year.ToString() + "_" + EndTime.Month.ToString() + "_" + EndTime.Day.ToString() + "_" + EndTime.Hour.ToString() + "_" + EndTime.Minute.ToString() + "_" + EndTime.Second.ToString() + ".txt", output);
     }
     catch (Exception ex)
     {
         Player.Console.Message("Timer Writer Has Crashed: {0}", ex);
     }
 }
Ejemplo n.º 16
0
        ChatTimer(TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy)
        {
            if (startedBy == null)
            {
                throw new ArgumentNullException("startedBy");
            }
            StartedBy = startedBy;
            Message   = message;
            StartTime = DateTime.UtcNow;
            EndTime   = StartTime.Add(duration);
            Duration  = duration;
            int oneSecondRepeats = (int)duration.TotalSeconds + 1;

            if (duration > Hour)
            {
                announceIntervalIndex = AnnounceIntervals.Length - 1;
                lastHourAnnounced     = (int)duration.TotalHours;
            }
            else
            {
                for (int i = 0; i < AnnounceIntervals.Length; i++)
                {
                    if (duration <= AnnounceIntervals[i])
                    {
                        announceIntervalIndex = i - 1;
                        break;
                    }
                }
            }
            task = Scheduler.NewTask(TimerCallback, this);
            ID   = Interlocked.Increment(ref timerCounter);
            AddTimerToList(this);
            IsRunning = true;
            task.RunRepeating(TimeSpan.Zero,
                              TimeSpan.FromSeconds(1),
                              oneSecondRepeats);
        }
Ejemplo n.º 17
0
        /// <summary> Schedules a given task for execution. </summary>
        /// <param name="task"> Task to schedule. </param>
        internal static void AddTask( [NotNull] SchedulerTask task ) {
            if ( task == null )
                throw new ArgumentNullException( "task" );
            lock ( TaskListLock ) {
                if ( Server.IsShuttingDown )
                    return;
                task.IsStopped = false;
#if DEBUG_SCHEDULER
                FireEvent( TaskAdded, task );
                if( Tasks.Add( task ) ) {
                    UpdateCache();
                    Logger.Log( LogType.Debug,
                                "Scheduler.AddTask: Added {0}", task );
                }else{
                    Logger.Log( LogType.Debug,
                                "Scheduler.AddTask: Added duplicate {0}", task );
                }
#else
                if ( Tasks.Add( task ) ) {
                    UpdateCache();
                }
#endif
            }
        }
Ejemplo n.º 18
0
        void SaveTask( SchedulerTask task ) {
            if( Map == null ) return;
            lock( SyncRoot ) {
                // ReSharper disable ConditionIsAlwaysTrueOrFalse
                // ReSharper disable HeuristicUnreachableCode
                if( Map == null ) return;
                // ReSharper restore HeuristicUnreachableCode
                // ReSharper restore ConditionIsAlwaysTrueOrFalse

                if( BackupInterval != TimeSpan.Zero &&
                    DateTime.UtcNow.Subtract( lastBackup ) > BackupInterval &&
                    (Map.HasChangedSinceBackup || !ConfigKey.BackupOnlyWhenChanged.Enabled()) ) {

                    string backupFileName = String.Format( TimedBackupFormat, Name, DateTime.Now ); // localized
                    Map.SaveBackup( MapFileName,
                                    Path.Combine( Paths.BackupPath, backupFileName ) );
                    lastBackup = DateTime.UtcNow;
                }

                if( Map.HasChangedSinceSave ) {
                    SaveMap();
                }
            }
        }
Ejemplo n.º 19
0
        static void Beat(SchedulerTask scheduledTask)
        {
            if (Server.IsShuttingDown)
            {
                return;
            }

            if (ConfigKey.HeartbeatEnabled.Enabled())
            {
                SendMinecraftNetBeat();
                if (ConfigKey.IsPublic.Enabled() && ConfigKey.HeartbeatToWoMDirect.Enabled())
                {
                    SendWoMDirectBeat();
                }
            }
            else
            {
                // If heartbeats are disabled, the server data is written
                // to a text file instead (heartbeatdata.txt)
                string[] data = new[] {
                    Salt,
                    Server.InternalIP.ToString(),
                    Server.Port.ToStringInvariant(),
                    Server.CountPlayers(false).ToStringInvariant(),
                    ConfigKey.MaxPlayers.GetString(),
                    ConfigKey.ServerName.GetString(),
                    ConfigKey.IsPublic.GetString(),
                    ConfigKey.WoMDirectDescription.GetString(),
                    ConfigKey.WoMDirectFlags.GetString(),
                    ConfigKey.HeartbeatToWoMDirect.Enabled().ToString()
                };
                const string tempFile = Paths.HeartbeatDataFileName + ".tmp";
                File.WriteAllLines(tempFile, data, Encoding.ASCII);
                Paths.MoveOrReplaceFile(tempFile, Paths.HeartbeatDataFileName);
            }
        }
Ejemplo n.º 20
0
 public void Interval(SchedulerTask task)
 {
     //check to stop Interval
     if (_world == null)
     {
         task.Stop();
         return;
     }
     if (_world.gameMode != GameMode.PropHunt)
     {
         _world = null;
         task.Stop();
         return;
     }
     if ((DateTime.Now - LastChecked).TotalSeconds > 29.9 && TimeLeft < TimeLimit)
     {
         _world.Players.Message("&WThere are currently {0} block(s) and  {1} seeker(s) left on {2}.",
                                _world.Players.Count() - _world.Players.Count(player => player.IsPropHuntSeeker),
                                _world.Players.Count(player => player.IsPropHuntSeeker), _world.ClassyName);
         _world.Players.Message("&WThere are {0} seconds left.", TimeLeft);
         LastChecked = DateTime.Now;
     }
     CheckScore();
 }
Ejemplo n.º 21
0
        void StartTasks() {
            lock( taskLock ) {
                updateTask = Scheduler.NewTask( UpdateTask );
                updateTask.RunForever( this,
                                       TimeSpan.FromMilliseconds( ConfigKey.TickInterval.GetInt() ),
                                       TimeSpan.Zero );

                if( ConfigKey.SaveInterval.GetInt() > 0 ) {
                    saveTask = Scheduler.NewBackgroundTask( SaveTask );
                    saveTask.IsCritical = true;
                    saveTask.AdjustForExecutionTime = true;
                    saveTask.RunForever( this,
                                         TimeSpan.FromSeconds( ConfigKey.SaveInterval.GetInt() ),
                                         TimeSpan.FromSeconds( ConfigKey.SaveInterval.GetInt() ) );
                }
            }
        }
Ejemplo n.º 22
0
 static void FireEvent( EventHandler<SchedulerTaskEventArgs> eventToFire, SchedulerTask task ) {
     var h = eventToFire;
     if( h != null ) h( null, new SchedulerTaskEventArgs( task ) );
 }
Ejemplo n.º 23
0
 public SchedulerTaskEventArgs(SchedulerTask task)
 {
     Task = task;
 }
Ejemplo n.º 24
0
 static void MonitorProcessorUsage( SchedulerTask task ) {
     TimeSpan newCPUTime = Process.GetCurrentProcess().TotalProcessorTime - cpuUsageStartingOffset;
     CPUUsageLastMinute = ( newCPUTime - oldCPUTime ).TotalSeconds /
                          ( Environment.ProcessorCount * DateTime.UtcNow.Subtract( lastMonitorTime ).TotalSeconds );
     lastMonitorTime = DateTime.UtcNow;
     CPUUsageTotal = newCPUTime.TotalSeconds /
                     ( Environment.ProcessorCount * DateTime.UtcNow.Subtract( StartTime ).TotalSeconds );
     oldCPUTime = newCPUTime;
     IsMonitoringCPUUsage = true;
 }
Ejemplo n.º 25
0
        static void DoGC( SchedulerTask task ) {
            if( !gcRequested ) return;
            gcRequested = false;

            Process proc = Process.GetCurrentProcess();
            proc.Refresh();
            long usageBefore = proc.PrivateMemorySize64 / ( 1024 * 1024 );

            GC.Collect( GC.MaxGeneration, GCCollectionMode.Forced );

            proc.Refresh();
            long usageAfter = proc.PrivateMemorySize64 / ( 1024 * 1024 );

            Logger.Log( LogType.Debug,
                        "Server.DoGC: Collected on schedule ({0}->{1} MB).",
                        usageBefore, usageAfter );
        }
Ejemplo n.º 26
0
 static void CheckConnections( SchedulerTask param ) {
     TcpListener listenerCache = listener;
     if( listenerCache != null && listenerCache.Pending() ) {
         try {
             Player.StartSession( listenerCache.AcceptTcpClient() );
         } catch( Exception ex ) {
             Logger.Log( LogType.Error,
                         "Server.CheckConnections: Could not accept incoming connection: {0}", ex );
         }
     }
 }
Ejemplo n.º 27
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.CaptureTheFlag)
            {
                task.Stop();
                world_ = null;
                return;
            }

            //remove announcements after 5 seconds
            if (announced != DateTime.MaxValue && (DateTime.Now - announced).TotalSeconds >= 5)
            {
                foreach (Player p in world_.Players)
                {
                    if (p.ClassiCube && Heartbeat.ClassiCube())
                    {
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcements, simply send a color code and call it a day
                    }
                }
                announced = DateTime.MaxValue;
            }

            //remove dodge after 1m
            foreach (Player p in world_.Players)
            {
                if (p.Info.canDodge)
                {
                    if (p.Info.dodgeTime != DateTime.MaxValue && (DateTime.Now - p.Info.dodgeTime).TotalSeconds >= 60)
                    {
                        p.Info.canDodge  = false;
                        p.Info.dodgeTime = DateTime.MaxValue;

                        world_.Players.Message(p.Name + " is no longer able to dodge.");
                    }
                }
            }

            //remove strengthen after 1m
            foreach (Player p in world_.Players)
            {
                if (p.Info.strengthened)
                {
                    if (p.Info.strengthTime != DateTime.MaxValue && (DateTime.Now - p.Info.strengthTime).TotalSeconds >= 60)
                    {
                        p.Info.strengthened = false;
                        p.Info.strengthTime = DateTime.MaxValue;

                        world_.Players.Message(p.Name + " is no longer dealing 2x damage.");
                    }
                }
            }

            //remove Blades of Fury after 1m
            if ((BlueBOFdebuff != DateTime.MaxValue && (DateTime.Now - BlueBOFdebuff).TotalSeconds >= 60))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.CTFBlueTeam)
                    {
                        p.Info.stabDisarmed = false;
                    }
                    else
                    {
                        p.Info.stabAnywhere = false;
                    }
                }
                BlueBOFdebuff = DateTime.MaxValue;

                world_.Players.Message("Blades of Fury has ended.");
            }

            if ((RedBOFdebuff != DateTime.MaxValue && (DateTime.Now - RedBOFdebuff).TotalSeconds >= 60))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.CTFRedTeam)
                    {
                        p.Info.stabDisarmed = false;
                    }
                    else
                    {
                        p.Info.stabAnywhere = false;
                    }
                }
                RedBOFdebuff = DateTime.MaxValue;

                world_.Players.Message("Blades of Fury has ended.");
            }

            //remove disarm after 30s
            if ((RedDisarmed != DateTime.MaxValue && (DateTime.Now - RedDisarmed).TotalSeconds >= 30))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.CTFRedTeam)
                    {
                        p.GunMode          = true;
                        p.Info.gunDisarmed = false;
                    }
                }
                RedDisarmed = DateTime.MaxValue;

                world_.Players.Message("The Disarm Spell has ended.");
            }

            if ((BlueDisarmed != DateTime.MaxValue && (DateTime.Now - BlueDisarmed).TotalSeconds >= 30))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.CTFBlueTeam)
                    {
                        p.GunMode          = true;
                        p.Info.gunDisarmed = false;
                    }
                }
                BlueDisarmed = DateTime.MaxValue;

                world_.Players.Message("The Disarm Spell has ended.");
            }

            if (!started)
            {
                //create a player moving event
                Player.Moving += PlayerMoving;

                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    world_.Players.Message("&WCTF&s requires at least 2 people to play.");
                    return;
                }

                //once timedelay is up, we start
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    if (!world_.gunPhysics)
                    {
                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
                    }
                    foreach (Player p in world_.Players)
                    {
                        if (p.ClassiCube && Heartbeat.ClassiCube())
                        {
                            //loop through each block ID
                            for (int i = 1; i < 65; i++)
                            {
                                //allow player to break glass block in order to shoot gun, disallow all other blocks except flags
                                if (i.Equals(20))
                                {
                                    p.Send(PacketWriter.MakeSetBlockPermissions((byte)20, false, true));
                                }
                                else if (i.Equals(21))
                                {
                                    p.Send(PacketWriter.MakeSetBlockPermissions((byte)21, false, true));
                                }
                                else if (i.Equals(29))
                                {
                                    p.Send(PacketWriter.MakeSetBlockPermissions((byte)29, false, true));
                                }
                                else
                                {
                                    p.Send(PacketWriter.MakeSetBlockPermissions((byte)i, false, false));
                                }
                            }
                        }

                        assignTeams(p);

                        if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
                        {
                            p.Info.IsHidden = false;
                            Player.RaisePlayerHideChangedEvent(p);
                        }

                        if (p.Info.CTFRedTeam)
                        {
                            p.TeleportTo(world_.redCTFSpawn.ToPlayerCoords());
                        }

                        if (p.Info.CTFBlueTeam)
                        {
                            p.TeleportTo(world_.blueCTFSpawn.ToPlayerCoords());
                        }

                        p.GunMode = true;
                        GunGlassTimer timer = new GunGlassTimer(p);
                        timer.Start();

                        //send an announcement (Will be sent as a normal message to non classicube players)
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));

                        if (p.ClassiCube && Heartbeat.ClassiCube())
                        {
                            //set player health
                            p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));

                            //set game score
                            p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: 0,&1 Blue&f: 0"));
                        }
                    }

                    //check that the flags haven't been misplaced during startup
                    if (world_.Map.GetBlock(world_.redFlag) != Block.Red)
                    {
                        world_.Map.QueueUpdate(new BlockUpdate(null, world_.redFlag, Block.Red));
                    }

                    if (world_.Map.GetBlock(world_.blueFlag) != Block.Blue)
                    {
                        world_.Map.QueueUpdate(new BlockUpdate(null, world_.blueFlag, Block.Blue));
                    }

                    started     = true;         //the game has officially started
                    isOn        = true;
                    lastChecked = DateTime.Now; //used for intervals
                    announced   = DateTime.Now;
                    return;
                }
            }

            //update blue team and red team counts
            redTeamCount =
                (
                    from red in world_.Players
                    where red.Info.CTFRedTeam
                    select red
                ).Count();

            blueTeamCount =
                (
                    from blue in world_.Players
                    where blue.Info.CTFBlueTeam
                    select blue
                ).Count();



            //Announce flag holder
            if (String.IsNullOrEmpty(redFlagHolder))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.hasRedFlag && redFlagHolder == null)
                    {
                        world_.Players.Message(p.Name + " has stolen the Red flag!");
                        redFlagHolder = p.Name;
                    }
                }
            }

            //update flagholder
            else
            {
                redFlagHolder = null;
                foreach (Player p in world_.Players)
                {
                    if (p.Info.hasRedFlag)
                    {
                        redFlagHolder = p.Name;
                    }
                }
            }

            if (String.IsNullOrEmpty(blueFlagHolder))
            {
                foreach (Player p in world_.Players)
                {
                    if (p.Info.hasBlueFlag && blueFlagHolder == null)
                    {
                        world_.Players.Message(p.Name + " has stolen the Blue flag!");
                        blueFlagHolder = p.Name;
                    }
                }
            }

            //update flagholder
            else
            {
                blueFlagHolder = null;
                foreach (Player p in world_.Players)
                {
                    if (p.Info.hasBlueFlag)
                    {
                        blueFlagHolder = p.Name;
                    }
                }
            }

            //Check victory conditions
            if (blueScore == 5)
            {
                world_.Players.Message("&fThe blue team has won {0} to {1}!", blueScore, redScore);
                Stop(null);
                return;
            }

            if (redScore == 5)
            {
                world_.Players.Message("&fThe red team has won {1} to {0}!", blueScore, redScore);
                Stop(null);
                return;
            }

            //if time is up
            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= (totalTime))
            {
                if (redScore > blueScore)
                {
                    world_.Players.Message("&fThe &cRed&f Team won {0} to {1}!", redScore, blueScore);
                    Stop(null);
                    return;
                }
                if (redScore < blueScore)
                {
                    world_.Players.Message("&fThe &1Blue&f Team won {0} to {1}!", blueScore, redScore);
                    Stop(null);
                    return;
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams tied {0} to {0}!", blueScore);
                    Stop(null);
                    return;
                }
                if (world_.Players.Count() <= 1)
                {
                    Stop(null);
                    return;
                }
            }

            //Check for forfeits
            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10)
            {
                if (blueTeamCount < 1 || redTeamCount < 1)
                {
                    if (blueTeamCount == 0)
                    {
                        if (world_.Players.Count() >= 1)
                        {
                            world_.Players.Message("&1Blue Team &fhas forfeited the game. &cRed Team &fwins!");
                        }
                        Stop(null);
                        return;
                    }
                    if (redTeamCount == 0)
                    {
                        if (world_.Players.Count() >= 1)
                        {
                            world_.Players.Message("&cRed Team &fhas forfeited the game. &1Blue Team &fwins!");
                        }
                        Stop(null);
                        return;
                    }
                    //lol, everyone left
                    else
                    {
                        Stop(null);
                        return;
                    }
                }
            }

            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));
            //Keep the players updated about the score
            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.8 && timeLeft <= timeLimit)
            {
                if (redScore > blueScore)
                {
                    world_.Players.Message("&fThe &cRed Team&f is winning {0} to {1}.", redScore, blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                if (redScore < blueScore)
                {
                    world_.Players.Message("&fThe &1Blue Team&f is winning {0} to {1}.", blueScore, redScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams are tied at {0}!", blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                lastChecked = DateTime.Now;
            }
            if (timeLeft == 10)
            {
                world_.Players.Message("&WOnly 10 seconds left!");
            }
        }
Ejemplo n.º 28
0
 public void Start()
 {
     started = true;
     task    = Scheduler.NewTask(StartFeed);
     task.RunForever(TimeSpan.FromMilliseconds(600));
 }
Ejemplo n.º 29
0
        static void CheckPaidStatusCallback(SchedulerTask task)
        {
            PlayerInfo info = (PlayerInfo)task.UserState;

            info.AccountType = Player.CheckPaidStatus(info.Name);
        }
Ejemplo n.º 30
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.TeamDeathMatch)
            {
                task.Stop();
                world_ = null;
                return;
            }

            //remove announcement after 5 seconds
            if ((DateTime.Now - announced).TotalSeconds >= 5)
            {
                foreach (Player p in world_.Players)
                {
                    if (p.usesCPE)
                    {
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcement, simply send a color code and call it a day
                    }
                }
            }

            if (!started)
            {
                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    world_.Players.Message("&WTeam DeathMatch&s requires at least 2 people to play.");
                    return;
                }
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        if (!manualTeams)
                        {
                            assignTeams(p); //assigns teams (who knew?)
                        }
                        if (p.Info.isOnRedTeam)
                        {
                            p.TeleportTo(TeamDeathMatch.redSpawn);
                        }                                                                  //teleport players to the team spawn
                        if (p.Info.isOnBlueTeam)
                        {
                            p.TeleportTo(TeamDeathMatch.blueSpawn);
                        }

                        if (!p.GunMode)
                        {
                            p.GunMode = true; //turns on gunMode automatically if not already on
                            GunGlassTimer timer = new GunGlassTimer(p);
                            timer.Start();
                        }

                        if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
                        {
                            p.Info.IsHidden = false;
                            Player.RaisePlayerHideChangedEvent(p);
                        }

                        //send an announcement
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));

                        if (p.usesCPE)
                        {
                            //set player's health
                            p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));

                            //set game score
                            p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: 0,&1 Blue&f: 0"));
                        }
                    }
                    started = true;   //the game has officially started
                    isOn    = true;
                    if (!world_.gunPhysics)
                    {
                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
                    }
                    lastChecked = DateTime.Now;                        //used for intervals
                    announced   = DateTime.Now;                        //set when the announcement was launched
                    return;
                }
            }

            //check if one of the teams have won
            if (redScore >= scoreLimit || blueScore >= scoreLimit)
            {
                Stop(null);
                return;
            }
            if (blueScore == scoreLimit && redScore == scoreLimit) //if they somehow manage to tie which I am pretty sure is impossible
            {
                world_.Players.Message("The teams tied at {0}!", redScore);
                Stop(null);
                return;
            }

            //check if time is up
            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= (totalTime))
            {
                if (redScore != blueScore)
                {
                    Stop(null);
                    return;
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams tied {0} to {1}!", blueScore, redScore);
                    Stop(null);
                    return;
                }
                if (world_.Players.Count() <= 1)
                {
                    Stop(null);
                    return;
                }
            }

            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10) //check if players left the world, forfeits if no players of that team left
            {
                int redCount  = world_.Players.Where(p => p.Info.isOnRedTeam).ToArray().Count();
                int blueCount = world_.Players.Where(p => p.Info.isOnBlueTeam).ToArray().Count();
                if (blueCount < 1 || redCount < 1)
                {
                    if (blueTeamCount == 0)
                    {
                        if (world_.Players.Count() >= 1)
                        {
                            world_.Players.Message("&1Blue Team &fhas forfeited the game. &cRed Team &fwins!");
                        }
                        Stop(null);
                        return;
                    }
                    if (redTeamCount == 0)
                    {
                        if (world_.Players.Count() >= 1)
                        {
                            world_.Players.Message("&cRed Team &fhas forfeited the game. &1Blue Team &fwins!");
                        }
                        Stop(null);
                        return;
                    }
                    else
                    {
                        Stop(null);
                        return;
                    }
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));
            //Keep the players updated about the score
            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.8 && timeLeft <= timeLimit)
            {
                if (redScore > blueScore)
                {
                    world_.Players.Message("&fThe &cRed Team&f is winning {0} to {1}.", redScore, blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                if (redScore < blueScore)
                {
                    world_.Players.Message("&fThe &1Blue Team&f is winning {0} to {1}.", blueScore, redScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams are tied at {0}!", blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                lastChecked = DateTime.Now;
            }
            if (timeLeft == 10)
            {
                world_.Players.Message("&WOnly 10 seconds left!");
            }
        }
Ejemplo n.º 31
0
 public ZombieSurvival(World world)
 {
     startTime = DateTime.UtcNow;
     _world    = world;
     task_     = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
 }
Ejemplo n.º 32
0
        public void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (_world.gameMode != GameMode.ZombieSurvival || _world == null)
            {
                _world = null;
                task.Stop();
                return;
            }
            if (!isOn)
            {
                if (_world.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    /*if (!ConfigKey.IsNormal.Enabled())
                     * {
                     *  return;
                     * }
                     * else
                     * {
                     *  _world.Players.Message("&WZombie Survival&s requires at least 4 people to play.");
                     *  return;
                     * }*/
                }
                if (startTime != null && (DateTime.UtcNow - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in _world.Players)
                    {
                        int x  = rand.Next(2, _world.Map.Width);
                        int y  = rand.Next(2, _world.Map.Length);
                        int z1 = 0;
                        for (int z = _world.Map.Height - 1; z > 0; z--)
                        {
                            if (_world.Map.GetBlock(x, y, z) != Block.Air)
                            {
                                z1 = z + 3;
                                break;
                            }
                        }
                        p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords());
                        //teleport players to a random position
                        beginGame(p);
                        chooseInfected();
                    }
                    isOn        = true;
                    lastChecked = DateTime.UtcNow; //used for intervals
                    return;
                }
            }
            if (isOn && (DateTime.UtcNow - lastChecked).TotalSeconds > 10)
            //check if players left the world, forfeits if no players of that team left
            {
                if (_world.Players.Count(player => player.IsInfected) == _world.Players.Count())
                {
                    ZombiesWin();
                    return;
                }
                if (_world.Players.Count(player => player.IsInfected) == 0 && _world.Players.Count() > 0)
                {
                    HumansWin();
                    return;
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));

            if (lastChecked != null && (DateTime.UtcNow - lastChecked).TotalSeconds > 29.9 && timeLeft <= timeLimit)
            {
                _world.Players.Message("There are currently {0} human(s) and {1} zombie(s) left on {2}",
                                       _world.Players.Count() - _world.Players.Count(player => player.IsInfected),
                                       _world.Players.Count(player => player.IsInfected), _world.ClassyName);
            }
        }
Ejemplo n.º 33
0
        static void Beat(SchedulerTask scheduledTask)
        {
            if (Server.IsShuttingDown)
            {
                return;
            }

            data = new HeartbeatData {
                IsPublic        = ConfigKey.IsPublic.GetBool(),
                MaxPlayers      = ConfigKey.MaxPlayers.GetInt(),
                PlayerCount     = Server.CountPlayers(false),
                ServerIP        = Server.IP,
                Port            = Server.Port,
                ProtocolVersion = Config.ProtocolVersion,
                Salt            = Server.Salt,
                ServerName      = ConfigKey.ServerName.GetString()
            };

            // This needs to be wrapped in try/catch because and exception in an event handler
            // would permanently stop heartbeat sending.
            try {
                if (RaiseHeartbeatSendingEvent(data))
                {
                    RescheduleHeartbeat();
                    return;
                }
            } catch (Exception ex) {
                Logger.LogAndReportCrash("Heartbeat.Sending handler failed", "fCraft", ex, false);
            }

            if (ConfigKey.HeartbeatEnabled.GetBool())
            {
                UriBuilder    ub = new UriBuilder(Uri);
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("public={0}&max={1}&users={2}&port={3}&version={4}&salt={5}&name={6}",
                                data.IsPublic,
                                data.MaxPlayers,
                                data.PlayerCount,
                                data.Port,
                                data.ProtocolVersion,
                                Uri.EscapeDataString(data.Salt),
                                Uri.EscapeDataString(data.ServerName));

                foreach (var pair in data.CustomData)
                {
                    sb.AppendFormat("&{0}={1}",
                                    Uri.EscapeDataString(pair.Key),
                                    Uri.EscapeDataString(pair.Value));
                }
                ub.Query = sb.ToString();

                request = (HttpWebRequest)WebRequest.Create(ub.Uri);
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
                request.Method      = "GET";
                request.Timeout     = Timeout;
                request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);

                request.BeginGetResponse(ResponseCallback, null);
            }
            else
            {
                // If heartbeats are disabled, the data is written to a text file (heartbeatdata.txt)
                const string tempFile = Paths.HeartbeatDataFileName + ".tmp";

                File.WriteAllLines(tempFile,
                                   new[] {
                    Server.Salt,
                    Server.IP.ToString(),
                    Server.Port.ToString(),
                    Server.CountPlayers(false).ToString(),
                    ConfigKey.MaxPlayers.GetString(),
                    ConfigKey.ServerName.GetString(),
                    ConfigKey.IsPublic.GetString()
                },
                                   Encoding.ASCII);

                Paths.MoveOrReplace(tempFile, Paths.HeartbeatDataFileName);
                RescheduleHeartbeat();
            }
        }
Ejemplo n.º 34
0
        void SaveTask( SchedulerTask task ) {
            if( !IsLoaded ) return;
            lock( SyncRoot ) {
                if( Map == null ) return;

                lock( BackupLock ) {
                    if( BackupsEnabled &&
                        DateTime.UtcNow.Subtract( lastBackup ) > BackupInterval &&
                        ( HasChangedSinceBackup || !ConfigKey.BackupOnlyWhenChanged.Enabled() ) ) {

                        string backupFileName = String.Format( TimedBackupFormat, Name, DateTime.Now ); // localized
                        SaveBackup( Path.Combine( Paths.BackupPath, backupFileName ) );
                        lastBackup = DateTime.UtcNow;
                    }
                }

                if( Map.HasChangedSinceSave ) {
                    SaveMap();
                }

                if( BlockDB.IsEnabledGlobally && BlockDB.IsEnabled ) {
                    BlockDB.Flush( true );
                }
            }
        }
Ejemplo n.º 35
0
 internal static void StartSaveTask()
 {
     saveTask = Scheduler.NewBackgroundTask(SaveTask)
                .RunForever(SaveInterval, SaveInterval + TimeSpan.FromSeconds(15));
 }
Ejemplo n.º 36
0
 static void PruneDBTask( SchedulerTask task )
 {
     int removedCount = PlayerDB.RemoveInactivePlayers();
     Player player = (Player)task.UserState;
     player.Message( "PruneDB: Removed {0} inactive players!", removedCount );
 }
Ejemplo n.º 37
0
        static void MainLoop()
        {
            while (!Server.IsShuttingDown)
            {
                DateTime ticksNow = DateTime.UtcNow;

                SchedulerTask[] taskListCache = taskCache;

                for (int i = 0; i < taskListCache.Length && !Server.IsShuttingDown; i++)
                {
                    SchedulerTask task = taskListCache[i];
                    if (task.IsStopped || task.NextTime > ticksNow)
                    {
                        continue;
                    }
                    if (task.IsRecurring && task.AdjustForExecutionTime)
                    {
                        task.NextTime += task.Interval;
                    }

                    if (task.IsBackground)
                    {
                        lock ( BackgroundTaskQueueLock ) {
                            BackgroundTasks.Enqueue(task);
                        }
                    }
                    else
                    {
                        task.IsExecuting = true;
#if DEBUG_SCHEDULER
                        FireEvent(TaskExecuting, task);
#endif

#if DEBUG
                        task.Callback(task);
                        task.IsExecuting = false;
#else
                        try {
                            task.Callback(task);
                        } catch (Exception ex) {
                            Logger.LogAndReportCrash("Exception thrown by ScheduledTask callback", "fCraft", ex, false);
                        } finally {
                            task.IsExecuting = false;
                        }
#endif

#if DEBUG_SCHEDULER
                        FireEvent(TaskExecuted, task);
#endif
                    }

                    if (!task.IsRecurring || task.MaxRepeats == 1)
                    {
                        task.Stop();
                        continue;
                    }
                    task.MaxRepeats--;

                    ticksNow = DateTime.UtcNow;
                    if (!task.AdjustForExecutionTime)
                    {
                        task.NextTime = ticksNow.Add(task.Interval);
                    }
                }

                Thread.Sleep(10);
            }
        }
Ejemplo n.º 38
0
 private void Server_Initialized( object sender, EventArgs e )
 {
     task = Scheduler.NewTask( t => Events.SaveGuilds() ).RunForever( TimeSpan.FromMinutes( 1 ), TimeSpan.FromMinutes( 1 ) );
     Logger.Log( LogType.ConsoleOutput, "Loading " + GuildConfig.NumberOfGuilds + " guilds" );
     GuildConfig.LoadAllGuilds();
     Logger.Log( LogType.ConsoleOutput, "Finished loading guilds" );
     Logger.Log( LogType.ConsoleOutput, "Starting guild perks" );
     Events.Init();
     CommandManager.RegisterCustomCommand( CdGuild );
     CommandManager.RegisterCustomCommand( CdGuildChat );
     CommandManager.RegisterCustomCommand( CdHiScores );
 }
Ejemplo n.º 39
0
        static void CheckIdles( SchedulerTask task ) {
            Player[] tempPlayerList = Players;
            for( int i = 0; i < tempPlayerList.Length; i++ ) {
                Player player = tempPlayerList[i];
                if( player.Info.Rank.IdleKickTimer <= 0 ) continue;

                if( player.IdleTime.TotalMinutes >= player.Info.Rank.IdleKickTimer ) {
                    Message( "{0}&S was kicked for being idle for {1} min",
                             player.ClassyName,
                             player.Info.Rank.IdleKickTimer );
                    string kickReason = "Idle for " + player.Info.Rank.IdleKickTimer + " minutes";
                    player.Kick( Player.Console, kickReason, LeaveReason.IdleKick, false, true, false );
                    player.ResetIdleTimer(); // to prevent kick from firing more than once
                }
            }
        }
Ejemplo n.º 40
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.FFA) //bug checking
            {
                task.Stop();
                world_ = null;
                return;
            }

            //remove announcement after 5 seconds
            if ((DateTime.UtcNow - announced).TotalSeconds >= 5)
            {
                foreach (Player p in world_.Players)
                {
                    if (p.SupportsMessageTypes)
                    {
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcement, simply send a color code and call it a day
                    }
                }
            }

            if (!started)                       //first time running the interval
            {
                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    world_.Players.Message("&WFFA&s requires at least 2 people to play.");
                    task.Stop();
                    return;
                }
                if (startTime != null && (DateTime.UtcNow - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        int x  = rand.Next(2, world_.Map.Width);
                        int y  = rand.Next(2, world_.Map.Length);
                        int z1 = 0;
                        for (int z = world_.Map.Height - 1; z > 0; z--)
                        {
                            if (world_.Map.GetBlock(x, y, z) != Block.Air)
                            {
                                z1 = z + 3;
                                break;
                            }
                        }
                        p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords()); //teleport players to a random position
                        InitializePlayer(p);
                        if (!p.GunMode)
                        {
                            p.GunMode = true; //turns on gunMode automatically if not already on
                            GunGlassTimer timer = new GunGlassTimer(p);
                            timer.Start();
                        }

                        if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
                        {
                            p.Info.IsHidden = false;
                            Player.RaisePlayerHideChangedEvent(p);
                        }

                        //send an announcement
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));

                        //set player health
                        p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));

                        //set leader
                        p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&eCurrent Leader&f: None"));
                    }
                    started = true;   //the game has officially started
                    if (!world_.gunPhysics)
                    {
                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
                    }
                    lastChecked = DateTime.UtcNow;                     //used for intervals
                    announced   = DateTime.UtcNow;                     //set when the announcement was launched
                    return;
                }
            }

            //check if one of the players has won
            foreach (Player p in world_.Players)
            {
                if (started && startTime != null && (DateTime.UtcNow - startTime).TotalSeconds >= timeDelay && p.Info.gameKillsFFA >= scoreLimit)
                {
                    Stop(p);
                    return;
                }
            }

            //check if time is up
            if (started && startTime != null && (DateTime.UtcNow - startTime).TotalSeconds >= (totalTime))
            {
                Player winner = GetScoreList()[0];
                if (world_.Players.Count() < 2)
                {
                    Stop(winner);
                    return;
                }
                Stop(winner);
                return;
            }

            if (started && (DateTime.UtcNow - lastChecked).TotalSeconds > 10) //check if players left the world, forfeits if no players of that team left
            {
                if (world_.Players.Count() < 2)
                {
                    Player[] players = world_.Players;
                    Stop(players[0]);
                    return;
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.UtcNow - startTime).ToSeconds()));
            //Keep the players updated about the score
            if (lastChecked != null && (DateTime.UtcNow - lastChecked).TotalSeconds > 29.9 && timeLeft <= timeLimit)
            {
                Player leader      = GetScoreList()[0]; //leader is the top of the score list
                Player secondPlace = GetScoreList()[1]; //second place is - well, second place XD
                if (isOn() && leader.Info.gameKillsFFA != secondPlace.Info.gameKillsFFA)
                {
                    world_.Players.Message("{0}&f is winning &c{1} &fto &c{2}", leader.ClassyName, leader.Info.gameKillsFFA, secondPlace.Info.gameKillsFFA);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                if (leader.Info.gameKillsFFA == secondPlace.Info.gameKillsFFA)
                {
                    world_.Players.Message("{1}&f and {2}&f are tied at &c{0}!", leader.Info.gameKillsFFA, leader.ClassyName, secondPlace.ClassyName);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                }
                lastChecked = DateTime.UtcNow;
            }
            if (timeLeft < 10.1)
            {
                world_.Players.Message("&WOnly 10 seconds left!");
            }
        }
Ejemplo n.º 41
0
 // shows announcements
 static void ShowRandomAnnouncement( SchedulerTask task ) {
     if( !File.Exists( Paths.AnnouncementsFileName ) ) return;
     string[] lines = File.ReadAllLines( Paths.AnnouncementsFileName );
     if( lines.Length == 0 ) return;
     string line = lines[new Random().Next( 0, lines.Length )].Trim();
     if( line.Length == 0 ) return;
     foreach( Player player in Players.Where( player => player.World != null ) ) {
         string announcementLine = Chat.ReplaceTextKeywords( player, line );
         announcementLine = Chat.ReplaceEmoteKeywords( announcementLine );
         announcementLine = Chat.ReplaceUnicodeWithEmotes( announcementLine );
         player.Message( "&R" + announcementLine );
     }
 }
Ejemplo n.º 42
0
 static void FlushAll( SchedulerTask task )
 {
     lock( WorldManager.SyncRoot ) {
         foreach( World w in WorldManager.Worlds.Where( w => w.BlockDB.IsEnabled ) ) {
             w.BlockDB.Flush();
         }
     }
 }
Ejemplo n.º 43
0
 public SchedulerTaskEventArgs([NotNull] SchedulerTask task)
 {
     Task = task;
 }
Ejemplo n.º 44
0
        static void doorTimer_Elapsed(SchedulerTask task)
        {
            DoorInfo info = (DoorInfo)task.UserState;
            int counter = 0;
            for (int x = info.Zone.Bounds.XMin; x <= info.Zone.Bounds.XMax; x++) {
                for (int y = info.Zone.Bounds.YMin; y <= info.Zone.Bounds.YMax; y++) {
                    for (int z = info.Zone.Bounds.ZMin; z <= info.Zone.Bounds.ZMax; z++) {
                        info.WorldMap.QueueUpdate(new BlockUpdate(null, new Vector3I(x, y, z), info.Buffer[counter]));
                        counter++;
                    }
                }
            }

            lock (openDoorsLock) { openDoors.Remove(info.Zone); }
        }
Ejemplo n.º 45
0
 static void FireEvent( EventHandler<SchedulerTaskEventArgs> eventToFire, SchedulerTask task ) {
     var h = eventToFire;
     if( h != null ) h( null, new SchedulerTaskEventArgs( task ) );
 }
Ejemplo n.º 46
0
 public static void Stop(Player player)
 {
     if (player != null){
         _world.Players.Message("{0}&S stopped the game of Infection on world {1}",
             player.ClassyName, _world.ClassyName);
     }
     RevertNames();
     _world.gameMode = GameMode.NULL;
     _humanCount = 0;
     _task = null;
     instance = null;
     _started = false;
 }
Ejemplo n.º 47
0
 void StopTasks() {
     lock( taskLock ) {
         if( updateTask != null ) {
             updateTask.Stop();
             updateTask = null;
         }
         if( saveTask != null ) {
             saveTask.Stop();
             saveTask = null;
         }
     }
 }
Ejemplo n.º 48
0
 /// <summary> Starts the heartbeats. </summary>
 public static void Start()
 {
     task = Scheduler.NewBackgroundTask(Beat).RunManual();
 }
Ejemplo n.º 49
0
 void UpdateTask( SchedulerTask task ) {
     Map tempMap = Map;
     if( tempMap != null ) {
         tempMap.ProcessUpdates();
     }
 }
Ejemplo n.º 50
0
 public static void Interval(SchedulerTask task)
 {
     //check to stop Interval
     if (_world.gameMode != GameMode.ZombieSurvival || _world == null)
     {
         _world = null;
         task.Stop();
         return;
     }
     if (!_started)
     {
         if (startTime != null && (DateTime.Now - startTime).TotalMinutes > 1)
         {
             /*if (_world.Players.Length < 3){
                 _world.Players.Message("&WThe game failed to start: 2 or more players need to be in the world");
                 Stop(null);
                 return;
             }*/
             foreach (Player p in _world.Players)
             {
                 int x = rand.Next(2, _world.Map.Width);
                 int y = rand.Next(2, _world.Map.Length);
                 int z1 = 0;
                 for (int z = _world.Map.Height - 1; z > 0; z--)
                 {
                     if (_world.Map.GetBlock(x, y, z) != Block.Air)
                     {
                         z1 = z + 3;
                         break;
                     }
                 }
                 p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords());
             }
             _started = true;
             RandomPick();
             lastChecked = DateTime.Now;
             return;
         }
     }
     //calculate humans
     _humanCount = _world.Players.Where(p => p.iName != _zomb).Count();
     //check if zombies have won already
     if (_humanCount == 0)
     {
         _world.Players.Message("&WThe Humans have failed to survive... &9ZOMBIES WIN!");
         Stop(null);
         return;
     }
     //check if 5mins is up and all zombies have failed
     if (_started && startTime != null && (DateTime.Now - startTime).TotalMinutes > 6)
     {
         _world.Players.Message("&WThe Zombies have failed to infect everyone... &9HUMANS WIN!");
         Stop(null);
         return;
     }
     //if no one has won, notify players of their status every 31s
     if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 30)
     {
         _world.Players.Message("&WThere are {0} humans", _humanCount.ToString());
         foreach (Player p in _world.Players)
         {
             if (p.iName == _zomb) p.Message("&8You are " + _zomb);
             else p.Message("&8You are a Human");
         }
         lastChecked = DateTime.Now;
     }
 }
Ejemplo n.º 51
0
        // Looks up the changes in BlockDB and prints a confirmation prompt. Runs on a background thread.
        static void UndoPlayerLookup( SchedulerTask task ) {
            BlockDBUndoArgs args = (BlockDBUndoArgs)task.UserState;
            bool allPlayers = ( args.Targets.Length == 0 );
            string cmdName = ( args.Not ? "UndoPlayerNot" : "UndoPlayer" );

            // prepare to look up
            string targetList;
            if( allPlayers ) {
                targetList = "EVERYONE";
            } else if( args.Not ) {
                targetList = "EVERYONE except " + args.Targets.JoinToClassyString();
            } else {
                targetList = args.Targets.JoinToClassyString();
            }
            BlockDBEntry[] changes;

            if( args.CountLimit > 0 ) {
                // count-limited lookup
                if( args.Targets.Length == 0 ) {
                    changes = args.World.BlockDB.Lookup( args.CountLimit );
                } else {
                    changes = args.World.BlockDB.Lookup( args.CountLimit, args.Targets, args.Not );
                }
                if( changes.Length > 0 ) {
                    Logger.Log( LogType.UserActivity,
                                "{0}: Asked {1} to confirm undo on world {2}",
                                cmdName, args.Player.Name, args.World.Name );
                    args.Player.Confirm( BlockDBUndoConfirmCallback, args,
                                         "Undo last {0} changes made by {1}&S?",
                                         changes.Length, targetList );
                }

            } else {
                // time-limited lookup
                if( args.Targets.Length == 0 ) {
                    changes = args.World.BlockDB.Lookup( Int32.MaxValue, args.AgeLimit );
                } else {
                    changes = args.World.BlockDB.Lookup( Int32.MaxValue, args.Targets, args.Not, args.AgeLimit );
                }
                if( changes.Length > 0 ) {
                    Logger.Log( LogType.UserActivity,
                                "{0}: Asked {1} to confirm undo on world {2}",
                                cmdName, args.Player.Name, args.World.Name );
                    args.Player.Confirm( BlockDBUndoConfirmCallback, args,
                                         "Undo changes ({0}) made by {1}&S in the last {2}?",
                                         changes.Length, targetList, args.AgeLimit.ToMiniString() );
                }
            }

            // stop if there's nothing to undo
            if( changes.Length == 0 ) {
                args.Player.Message( "{0}: Found nothing to undo.", cmdName );
            } else {
                args.Entries = changes;
            }
        }
Ejemplo n.º 52
0
 /// <summary>
 /// Repeating task, checks things
 /// </summary>
 /// <param name="task">Task in question</param>
 public void Interval(SchedulerTask task)
 {
     //check to stop Interval
     if (_world.gameMode != GameMode.ZombieSurvival || _world == null)
     {
         _world = null;
         task.Stop();
         return;
     }
     if (!_started)
     {
         if (startTime != null && (DateTime.UtcNow - startTime).TotalMinutes > 1)
         {
             /*if (_world.Players.Length < 3){
              *  _world.Players.Message("&WThe game failed to start: 2 or more players need to be in the world");
              *  Stop(null);
              *  return;
              * }*/
             ShufflePlayerPositions();
             _started = true;
             RandomPick();
             lastChecked = DateTime.UtcNow;
             return;
         }
     }
     //calculate humans
     _humanCount = _world.Players.Where(p => p.iName != _zomb).Count();
     //check if zombies have won already
     if (_started)
     {
         if (_humanCount == 1 && _world.Players.Count() == 1)
         {
             _world.Players.Message("&WThe Zombies have failed to infect everyone... &9HUMANS WIN!");
             Stop(null);
             return;
         }
         if (_humanCount == 0)
         {
             _world.Players.Message("&WThe Humans have failed to survive... &9ZOMBIES WIN!");
             Stop(null);
             return;
         }
     }
     //check if 5mins is up and all zombies have failed
     if (_started && startTime != null && (DateTime.UtcNow - startTime).TotalMinutes >= 5)
     {
         _world.Players.Message("&WThe Zombies have failed to infect everyone... &9HUMANS WIN!");
         Stop(null);
         return;
     }
     //if no one has won, notify players of their status every ~30s
     if (lastChecked != null && (DateTime.UtcNow - lastChecked).TotalSeconds >= 30)
     {
         _world.Players.Message("&WThere are {0} humans", _humanCount.ToString());
         foreach (Player p in _world.Players)
         {
             if (p.iName == _zomb)
             {
                 p.Message("&8You are " + _zomb);
             }
             else
             {
                 p.Message("&8You are a Human");
             }
         }
         lastChecked = DateTime.UtcNow;
     }
 }
Ejemplo n.º 53
0
 static void SaveTask(SchedulerTask task)
 {
     Save();
 }
Ejemplo n.º 54
0
 void UpdateTask( SchedulerTask task ) {
     Map tempMap = Map;
     if( tempMap != null ) {
         tempMap.ProcessUpdates();
     }
 }
Ejemplo n.º 55
0
 public SchedulerTaskEventArgs( SchedulerTask task )
 {
     Task = task;
 }
Ejemplo n.º 56
0
        static void TimeCheck(SchedulerTask task)
        {
            foreach (World world in WorldManager.Worlds)
            {
                if (world.RealisticEnv)
                {
                    int sky;
                    int clouds;
                    int fog;
                    DateTime now = DateTime.Now;
                    var SunriseStart = new TimeSpan(6, 30, 0);
                    var SunriseEnd = new TimeSpan(7, 29, 59);
                    var MorningStart = new TimeSpan(7, 30, 0);
                    var MorningEnd = new TimeSpan(11, 59, 59);
                    var NormalStart = new TimeSpan(12, 0, 0);
                    var NormalEnd = new TimeSpan(16, 59, 59);
                    var EveningStart = new TimeSpan(17, 0, 0);
                    var EveningEnd = new TimeSpan(18, 59, 59);
                    var SunsetStart = new TimeSpan(19, 0, 0);
                    var SunsetEnd = new TimeSpan(19, 29, 59);
                    var NightaStart = new TimeSpan(19, 30, 0);
                    var NightaEnd = new TimeSpan(1, 0, 1);
                    var NightbStart = new TimeSpan(1, 0, 2);
                    var NightbEnd = new TimeSpan(6, 29, 59);

                    if (now.TimeOfDay > SunriseStart && now.TimeOfDay < SunriseEnd) //sunrise
                    {
                        sky = ParseHexColor("ffff33");
                        clouds = ParseHexColor("ff0033");
                        fog = ParseHexColor("ff3333");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Water;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > MorningStart && now.TimeOfDay < MorningEnd) //end of sunrise
                    {
                        sky = -1;
                        clouds = ParseHexColor("ff0033");
                        fog = ParseHexColor("fffff0");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Water;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > NormalStart && now.TimeOfDay < NormalEnd)//env normal
                    {
                        sky = -1;
                        clouds = -1;
                        fog = -1;
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Water;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > EveningStart && now.TimeOfDay < EveningEnd) //evening
                    {
                        sky = ParseHexColor("99cccc");
                        clouds = -1;
                        fog = ParseHexColor("99ccff");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Water;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > SunsetStart && now.TimeOfDay < SunsetEnd) //sunset
                    {
                        sky = ParseHexColor("9999cc");
                        clouds = ParseHexColor("000033");
                        fog = ParseHexColor("cc9966");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Water;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > NightaStart && now.TimeOfDay < NightaEnd) //end of sunset
                    {
                        sky = ParseHexColor("003366");
                        clouds = ParseHexColor("000033");
                        fog = ParseHexColor("000033");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Black;
                        WorldManager.SaveWorldList();
                        return;
                    }

                    if (now.TimeOfDay > NightbStart && now.TimeOfDay < NightbEnd) //black
                    {
                        sky = ParseHexColor("000000");
                        clouds = ParseHexColor("000033");
                        fog = ParseHexColor("000033");
                        world.SkyColor = sky;
                        world.CloudColor = clouds;
                        world.FogColor = fog;
                        world.EdgeBlock = Block.Obsidian;
                        WorldManager.SaveWorldList();
                    }
                }
            }
        }