Esempio n. 1
0
        private static void BotHandler(Player player, CommandReader cmd) {
            string option = cmd.Next();
            if (string.IsNullOrEmpty(option)) {
                CdEntity.PrintUsage(player);
                return;
            }

            if (option.ToLower() == "list") {
                player.Message("_Entities on {0}_", ConfigKey.ServerName.GetString());
                foreach (Bot botCheck in World.Bots) {
                    player.Message(botCheck.Name + " on " + botCheck.World.Name);
                }
                return;
            }
            if (option.ToLower() == "removeall") {
                if (cmd.IsConfirmed) {
                    foreach (Bot b in World.Bots) {
                        b.World.Players.Send(Packet.MakeRemoveEntity(b.ID));
                        if (File.Exists("./Entities/" + b.Name.ToLower() + ".txt")) {
                            File.Delete("./Entities/" + b.Name.ToLower() + ".txt");
                        }
                    }
                    World.Bots.Clear();
                    player.Message("All entities removed.");
                } else {
                    player.Confirm(cmd, "This will remove all the entites everywhere, are you sure?");
                }
                return;
            }

            //finally away from the special cases
            string botName = cmd.Next();
            if (string.IsNullOrEmpty(botName)) {
                CdEntity.PrintUsage(player);
                return;
            }

            Bot bot = new Bot();
            if (option != "create" && option != "add") {
                bot = World.FindBot(botName.ToLower());
                if (bot == null) {
                    player.Message(
                        "Could not find {0}! Please make sure you spelled the entities name correctly. To view all the entities, type /ent list.",
                        botName);
                    return;
                }
            }
            Block blockmodel;

            switch (option.ToLower()) {
                case "create":
                case "add":
                    string requestedModel = "humanoid";
                    if (cmd.HasNext) {
                        requestedModel = cmd.Next().ToLower();
                    }
                    if (!validEntities.Contains(requestedModel)) {
                        if (Map.GetBlockByName(requestedModel, false, out blockmodel)) {
                            requestedModel = blockmodel.GetHashCode().ToString();
                        } else {
                            player.Message(
                                "That wasn't a valid entity model! Valid models are chicken, creeper, human, pig, sheep, skeleton, spider, zombie, or any block ID/Name.");
                            return;
                        }
                    }

                    //if a botname has already been chosen, ask player for a new name
                    var matchingNames = from b in World.Bots where b.Name.ToLower() == botName.ToLower() select b;

                    if (matchingNames.Count() > 0) {
                        player.Message("An entity with that name already exists! To view all entities, type /ent list.");
                        return;
                    }

                    string skinString1 = (cmd.Next() ?? botName);
                    if (skinString1 != null) {
                        if (skinString1.StartsWith("--")) {
                            skinString1 = string.Format("http://minecraft.net/skin/{0}.png", skinString1.Replace("--", ""));
                        }
                        if (skinString1.StartsWith("-+")) {
                            skinString1 = string.Format("http://skins.minecraft.net/MinecraftSkins/{0}.png", skinString1.Replace("-+", ""));
                        }
                        if (skinString1.StartsWith("++")) {
                            skinString1 = string.Format("http://i.imgur.com/{0}.png", skinString1.Replace("++", ""));
                        }
                    }
                    Bot botCreate = new Bot();
                    botCreate.setBot(botName, skinString1, requestedModel, player.World, player.Position, getNewID());
                    botCreate.createBot();
                    player.Message("Successfully created entity {0}&s with id:{1} and skin {2}.", botCreate.Name, botCreate.ID, skinString1 ?? bot.Name);
                    break;
                case "remove":
                    player.Message("{0} was removed from the server.", bot.Name);
                    bot.removeBot();
                    break;
                case "model":
                    if (cmd.HasNext) {
                        string model = cmd.Next().ToLower();
                        string skinString2 = cmd.Next();
                        if (skinString2 != null) {
                            if (skinString2.StartsWith("--")) {
                                skinString2 = string.Format("http://minecraft.net/skin/{0}.png", skinString2.Replace("--", ""));
                            }
                            if (skinString2.StartsWith("-+")) {
                                skinString2 = string.Format("http://skins.minecraft.net/MinecraftSkins/{0}.png", skinString2.Replace("-+", ""));
                            }
                            if (skinString2.StartsWith("++")) {
                                skinString2 = string.Format("http://i.imgur.com/{0}.png", skinString2.Replace("++", ""));
                            }
                        }
                        if (string.IsNullOrEmpty(model)) {
                            player.Message(
                                "Usage is /Ent model <bot> <model>. Valid models are chicken, creeper, human, pig, sheep, skeleton, spider, zombie, or any block ID/Name.");
                            break;
                        }

                        if (model == "human") {
                            model = "humanoid";
                        }
                        if (!validEntities.Contains(model)) {
                            if (Map.GetBlockByName(model, false, out blockmodel)) {
                                model = blockmodel.GetHashCode().ToString();
                            } else {
                                player.Message(
                                    "That wasn't a valid entity model! Valid models are chicken, creeper, human, pig, sheep, skeleton, spider, zombie, or any block ID/Name.");
                                break;
                            }
                        }

                        player.Message("Changed entity model to {0} with skin {1}.", model, skinString2 ?? bot.SkinName);
                        bot.changeBotModel(model, skinString2 ?? bot.SkinName);
                    } else
                        player.Message(
                            "Usage is /Ent model <bot> <model>. Valid models are chicken, creeper, human, pig, sheep, skeleton, spider, zombie, or any block ID/Name.");
                    break;
                case "bring":
                    bot.teleportBot(player.Position);
                    break;
                case "tp":
                case "teleport":
                    World targetWorld = bot.World;
                    Bot target = bot;
                    if (targetWorld == player.World) {
                        if (player.World != null) {
                            player.LastWorld = player.World;
                            player.LastPosition = player.Position;
                        }
                        player.TeleportTo(target.Position);

                    } else {
                        if (targetWorld.Name.StartsWith("PW_") &&
                            !targetWorld.AccessSecurity.ExceptionList.Included.Contains(player.Info)) {
                            player.Message(
                                "You cannot join due to that Bot being in a personal world that you cannot access.");
                            break;
                        }
                        switch (targetWorld.AccessSecurity.CheckDetailed(player.Info)) {
                            case SecurityCheckResult.Allowed:
                            case SecurityCheckResult.WhiteListed:
                                if (player.Info.Rank.Name == "Banned") {
                                    player.Message("&CYou can not change worlds while banned.");
                                    player.Message("Cannot teleport to {0}&S.", target.Name,
                                        targetWorld.ClassyName, targetWorld.AccessSecurity.MinRank.ClassyName);
                                    break;
                                }
                                if (targetWorld.IsFull) {
                                    player.Message("Cannot teleport to {0}&S because world {1}&S is full.",
                                        target.Name, targetWorld.ClassyName);
                                    player.Message("Cannot teleport to {0}&S.", target.Name,
                                        targetWorld.ClassyName, targetWorld.AccessSecurity.MinRank.ClassyName);
                                    break;
                                }
                                player.StopSpectating();
                                player.JoinWorld(targetWorld, WorldChangeReason.Tp, target.Position);
                                break;
                            case SecurityCheckResult.BlackListed:
                                player.Message("Cannot teleport to {0}&S because you are blacklisted on world {1}",
                                    target.Name, targetWorld.ClassyName);
                                break;
                            case SecurityCheckResult.RankTooLow:
                                if (player.Info.Rank.Name == "Banned") {
                                    player.Message("&CYou can not change worlds while banned.");
                                    player.Message("Cannot teleport to {0}&S.", target.Name,
                                        targetWorld.ClassyName, targetWorld.AccessSecurity.MinRank.ClassyName);
                                    break;
                                }

                                if (targetWorld.IsFull) {
                                    if (targetWorld.IsFull) {
                                        player.Message("Cannot teleport to {0}&S because world {1}&S is full.",
                                            target.Name, targetWorld.ClassyName);
                                        player.Message("Cannot teleport to {0}&S.", target.Name,
                                            targetWorld.ClassyName, targetWorld.AccessSecurity.MinRank.ClassyName);
                                        break;
                                    }
                                    player.StopSpectating();
                                    player.JoinWorld(targetWorld, WorldChangeReason.Tp, target.Position);
                                    break;
                                }
                                player.Message("Cannot teleport to {0}&S because world {1}&S requires {2}+&S to join.",
                                    target.Name, targetWorld.ClassyName,
                                    targetWorld.AccessSecurity.MinRank.ClassyName);
                                break;
                        }
                    }
                    break;
                case "skin":
                    string skinString3 = cmd.Next();
                    if (skinString3 != null) {
                        if (skinString3.StartsWith("--")) {
                            skinString3 = string.Format("http://minecraft.net/skin/{0}.png", skinString3.Replace("--", ""));
                        }
                        if (skinString3.StartsWith("-+")) {
                            skinString3 = string.Format("http://skins.minecraft.net/MinecraftSkins/{0}.png", skinString3.Replace("-+", ""));
                        }
                        if (skinString3.StartsWith("++")) {
                            skinString3 = string.Format("http://i.imgur.com/{0}.png", skinString3.Replace("++", ""));
                        }
                    }
                    player.Message("Changed entity skin to {0}.", skinString3 ?? bot.Name);
                    bot.changeBotSkin(skinString3);
                    break;
                default:
                    CdEntity.PrintUsage(player);
                    break;
            }
        }
Esempio n. 2
0
        /// <summary> Starts the server:
        /// Creates Console pseudoplayer, loads the world list, starts listening for incoming connections,
        /// sets up scheduled tasks and starts the scheduler, starts the heartbeat, and connects to IRC.
        /// Raises Server.Starting and Server.Started events.
        /// May throw an exception on hard failure. </summary>
        /// <returns> True if server started normally, false on soft failure. </returns>
        /// <exception cref="System.InvalidOperationException"> Server is already running, or server/library have not been initailized. </exception>
        public static bool StartServer() {
            if( IsRunning ) {
                throw new InvalidOperationException( "Server is already running" );
            }
            if( !libraryInitialized || !serverInitialized ) {
                throw new InvalidOperationException(
                    "Server.InitLibrary and Server.InitServer must be called before Server.StartServer" );
            }

            StartTime = DateTime.UtcNow;
            cpuUsageStartingOffset = Process.GetCurrentProcess().TotalProcessorTime;
            Players = new Player[0];

            RaiseEvent( Starting );

            if( ConfigKey.BackupDataOnStartup.Enabled() ) {
                BackupData();
            }

            Player.Console = new Player( ConfigKey.ConsoleName.GetString() );
            Player.AutoRank = new Player( "(AutoRank)" );

            // Back up server data (PlayerDB, worlds, bans, config)
            if( ConfigKey.BlockDBEnabled.Enabled() ) {
                BlockDB.Init();
            }

            // Load the world list
            if( !WorldManager.LoadWorldList() ) return false;
            WorldManager.SaveWorldList();

            // Back up all worlds (if needed)
            if( ConfigKey.BackupOnStartup.Enabled() ) {
                foreach( World world in WorldManager.Worlds ) {
                    string backupFileName = String.Format( World.TimedBackupFormat,
                                                           world.Name, DateTime.Now ); // localized
                    world.SaveBackup( Path.Combine( Paths.BackupPath, backupFileName ) );
                }
            }

            // open the port
            Port = ConfigKey.Port.GetInt();
            InternalIP = IPAddress.Parse( ConfigKey.IP.GetString() );

            try {
                listener = new TcpListener( InternalIP, Port );
                listener.Start();

            } catch( Exception ex ) {
                // if the port is unavailable
                Logger.Log( LogType.Error,
                            "Could not start listening on port {0}, stopping. ({1})",
                            Port, ex.Message );
                if( !ConfigKey.IP.IsDefault() ) {
                    Logger.Log( LogType.Warning,
                                "Do not use the \"Designated IP\" setting unless you have multiple NICs or IPs." );
                }
                return false;
            }

            // Resolve internal and external IP addresses
            InternalIP = ( (IPEndPoint)listener.LocalEndpoint ).Address;
            ExternalIP = CheckExternalIP();

            if( ExternalIP == null ) {
                Logger.Log( LogType.SystemActivity,
                            "&3Server.Run: now accepting connections on port {0}", Port );
            } else {
                Logger.Log( LogType.SystemActivity,
                            "&3Server.Run: now accepting connections at {0}:{1}",
                            ExternalIP, Port );
            }

            // list loaded worlds
            WorldManager.UpdateWorldList();
            Logger.Log( LogType.SystemActivity,
                        "&3All available worlds: {0}",
                        WorldManager.Worlds.JoinToString( ", ", w => w.ClassyName ) );

            Logger.Log( LogType.SystemActivity,
                        "&3Main world: {0}&3; default rank: {1}",
                        WorldManager.MainWorld.ClassyName, RankManager.DefaultRank.ClassyName );

            // Check for incoming connections (every 250ms)
            checkConnectionsTask = Scheduler.NewTask( CheckConnections ).RunForever( CheckConnectionsInterval );

            // Check for idles (every 1s)
            checkIdlesTask = Scheduler.NewTask( CheckIdles ).RunForever( CheckIdlesInterval );// Check for idles (every 30s)

            // Monitor CPU usage (every 30s)
            try {
                MonitorProcessorUsage( null );
                Scheduler.NewTask( MonitorProcessorUsage ).RunForever( MonitorProcessorUsageInterval,
                                                                       MonitorProcessorUsageInterval );
            } catch( Exception ex ) {
                Logger.Log( LogType.Error,
                            "Server.StartServer: Could not start monitoring CPU use: {0}", ex );
            }

            // PlayerDB saving (every 90s)
            PlayerDB.StartSaveTask();

            // Announcements
            if( ConfigKey.AnnouncementInterval.GetInt() > 0 ) {
                TimeSpan announcementInterval = TimeSpan.FromMinutes( ConfigKey.AnnouncementInterval.GetInt() );
                Scheduler.NewTask( ShowRandomAnnouncement ).RunForever( announcementInterval );
                Scheduler.NewTask( RemoveRandomAnnouncement ).RunForever( announcementInterval, new TimeSpan(0, 0, 5));
            }

            #region LoadTimers
            try
            {
                //Load Timers.
                if (Directory.Exists("./Timers"))
                {
                    string[] TimersFileList = Directory.GetFiles("./Timers");
                    foreach (string filename in TimersFileList)
                    {
                        if (Path.GetExtension("./Timers/" + filename) == ".txt")
                        {
                            string[] TimerData = File.ReadAllLines(filename);
                            DateTime StartDate = DateTime.UtcNow;
                            DateTime EndDate = StartDate;
                            PlayerInfo CreatedBy = Player.Console.Info;
                            string TimerMessage = null;
                            foreach (string line in TimerData)
                            {
                                if (line.Contains("StartDate: "))
                                {
                                    string date = line.Remove(0, "StartDate: ".Length);
                                    if (DateTime.TryParse(date, out StartDate))
                                    {
                                        StartDate = DateTime.Parse(date);
                                    }
                                }
                                else if (line.Contains("EndDate: "))
                                {
                                    string date = line.Remove(0, "EndDate: ".Length);
                                    if (DateTime.TryParse(date, out EndDate))
                                    {
                                        EndDate = DateTime.Parse(date);
                                    }
                                }
                                else if (line.Contains("CreatedBy: "))
                                {
                                    string creator = line.Remove(0, "CreatedBy: ".Length);
                                    if (PlayerDB.FindPlayerInfoExact(creator) != null)
                                    {
                                        CreatedBy = PlayerDB.FindPlayerInfoExact(creator);
                                    }
                                }
                                else if (line.Contains("Message: "))
                                {
                                    TimerMessage = line.Remove(0, "Creator: ".Length);
                                }
                            }
                            if (StartDate == null || EndDate == null || CreatedBy == null || TimerMessage == null)
                            {
                                Player.Console.Message("Error starting a Timer: {0}, {1}, {2}, {3}", StartDate.ToString(), EndDate.ToString(), CreatedBy.Name, TimerMessage);
                                continue;
                            }
                            if (DateTime.Compare(EndDate, DateTime.UtcNow) <= 0)
                            {
                                Player.Console.Message("Timer Expired: {0}, {1}, {2}, {3} Time Now: {4}", StartDate.ToString(), EndDate.ToString(), CreatedBy.Name, TimerMessage, DateTime.UtcNow.ToString());
                                if (Directory.Exists("./Timers"))
                                {
                                    Player.Console.Message(filename);
                                    if (File.Exists(filename))
                                    {
                                        File.Delete(filename);
                                    }
                                }
                                continue;
                            }
                            if ((StartDate != EndDate) && (CreatedBy != null) && (TimerMessage != null))
                            {
                                ChatTimer.Start((EndDate - DateTime.UtcNow), TimerMessage, CreatedBy.Name);
                                continue;
                            }
                        }
                    }
                    if (TimersFileList.Length > 0) Player.Console.Message("All Timers Loaded. ({0})", TimersFileList.Length);
                    else Player.Console.Message("No Timers Were Loaded.");
                }
            }
            catch (Exception ex)
            {
                Player.Console.Message("Timer Loader Has Crashed: {0}", ex);
            }
            #endregion

            #region LoadReports

            try {
                if (Directory.Exists("./Reports")) {
                    string[] ReportFileList = Directory.GetFiles("./Reports");
                    int created = 0;
                    foreach (string filename in ReportFileList) {
                        Report rCreate = new Report();
                        if (Path.GetExtension("./Reports/" + filename) == ".txt") {
                            string[] reportData = File.ReadAllLines(filename);
                            string idString = filename.Replace("./Reports\\", "").Replace(".txt", "").Split('-')[0];
                            string sender = reportData[0];
                            DateTime dateSent = DateTime.MinValue;
                            long dateSentBinary;
                            if (long.TryParse(reportData[1], out dateSentBinary)) {
                                dateSent = DateTime.FromBinary(dateSentBinary);
                            }
                            string message = reportData[2];
                            int id;
                            if (int.TryParse(idString, out id)) {
                                rCreate.addReport(id, sender, dateSent, message);
                                created++;
                            }

                        }

                    }
                    if (created > 0)
                        Player.Console.Message("All Reports Loaded. ({0})", created);
                    else
                        Player.Console.Message("No reports were loaded.");
                }
            } catch (Exception ex) {
                Player.Console.Message("Report Loader Has Crashed: {0}", ex);
            }

            #endregion

            #region LoadFilters

            try {
                if (Directory.Exists("./Filters")) {
                    string[] FilterFileList = Directory.GetFiles("./Filters");
                    int created = 0;
                    foreach (string filename in FilterFileList) {
                        Filter filterCreate = new Filter();
                        if (Path.GetExtension("./Filters/" + filename) == ".txt") {
                            string[] filterData = File.ReadAllLines(filename);
                            string idString = filename.Replace("./Filters\\", "").Replace(".txt", "");
                            string wordString = filterData[0];
                            string replacementString = filterData[1];
                            int id;
                            if (int.TryParse(idString, out id)) {
                                filterCreate.addFilter(id, wordString, replacementString);
                                created++;
                            }

                        }

                    }
                    if (created > 0)
                        Player.Console.Message("All Filters Loaded. ({0})", created);
                    else
                        Player.Console.Message("No filters were loaded.");
                }
            } catch (Exception ex) {
                Player.Console.Message("Filter Loader Has Crashed: {0}", ex);
            }

            #endregion

            #region LoadEntities

            try {
                if (Directory.Exists("./Entities")) {
                    string[] EntityFileList = Directory.GetFiles("./Entities");
                    foreach (string filename in EntityFileList) {
                        Bot botCreate = new Bot();
                        if (Path.GetExtension("./Entities/" + filename) == ".txt") {
                            string[] entityData = File.ReadAllLines(filename);
                            sbyte idString;
                            Position posString;
                            string nameString = entityData[0];
                            string skinString = entityData[1];
                            string modelString = entityData[2];
                            if (!CpeCommands.validEntities.Contains(modelString)) {
                                Block block;
                                if (Map.GetBlockByName(modelString, false, out block)) {
                                    modelString = block.GetHashCode().ToString();
                                } else {
                                    modelString = "humanoid";
                                }
                            }
                            if (!sbyte.TryParse(entityData[3], out idString)) { }
                            World worldString = WorldManager.FindWorldExact(entityData[4]) ??
                                                WorldManager.FindMainWorld(RankManager.LowestRank);
                            if (!short.TryParse(entityData[5], out posString.X)) {
                                posString.X = worldString.map.Spawn.X;
                            }
                            if (!short.TryParse(entityData[6], out posString.Y)) {
                                posString.Y = worldString.map.Spawn.Y;
                            }
                            if (!short.TryParse(entityData[7], out posString.Z)) {
                                posString.Z = worldString.map.Spawn.Z;
                            }
                            if (!byte.TryParse(entityData[8], out posString.L)) {
                                posString.L = worldString.map.Spawn.L;
                            }
                            if (!byte.TryParse(entityData[9], out posString.R)) {
                                posString.R = worldString.map.Spawn.R;
                            }

                            botCreate.setBot(nameString, skinString ?? nameString, modelString, worldString, posString, idString);
                        }

                    }
                    if (EntityFileList.Length > 0)
                        Player.Console.Message("All Entities Loaded. ({0})", EntityFileList.Length);
                    else
                        Player.Console.Message("No Entities Were Loaded.");
                }
            } catch (Exception ex) {
                Player.Console.Message("Entity Loader Has Crashed: {0}", ex);
            }

            #endregion

            #region ResourceDownloads

            if (!Directory.Exists("./Bot")) {
                Directory.CreateDirectory("./Bot");
            }
			if (!File.Exists("Bot/Funfacts.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/Funfacts.txt", "Bot/Funfacts.txt");
            }
			if (!File.Exists("Bot/Jokes.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/Jokes.txt", "Bot/Jokes.txt");
            }
			if (!File.Exists("Bot/Protips.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/Protips.txt", "Bot/Protips.txt");
            }
            if (!File.Exists("Bot/Adjectives.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/Adjectives.txt", "Bot/Adjectives.txt");
            }
			if (!File.Exists("Bot/Nouns.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/Nouns.txt", "Bot/Nouns.txt");
			}

			if (!File.Exists("./MOTDList.txt")) {
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/MOTDList.txt", "MOTDList.txt");
			}

			if (!Directory.Exists("./fonts")) {
				Directory.CreateDirectory("./fonts");
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/comicsans.ttf", "fonts/comicsans.ttf");
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/mcclassic.ttf", "fonts/mcclassic.ttf");
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/microsoft.ttf", "fonts/microsoft.ttf");
				(new WebClient()).DownloadFile("http://123dmwm.tk/ProCraft/resources/minecraft.ttf", "fonts/minecraft.ttf");
			}

            #endregion


            PortalHandler.GetInstance();
            PortalDB.Load();
            BlockDefinition.LoadGlobalDefinitions();

            // garbage collection (every 60s)
            gcTask = Scheduler.NewTask( DoGC ).RunForever( GCInterval, TimeSpan.FromSeconds( 45 ) );

            Heartbeat.Start();

            if( ConfigKey.IRCBotEnabled.Enabled() ) {
                IRC.Start();
            }

            if( ConfigKey.AutoRankEnabled.Enabled() ) {
                Scheduler.NewTask( AutoRankManager.TaskCallback ).RunForever( AutoRankManager.TickInterval );
            }

            if( ConfigKey.RestartInterval.GetInt() > 0 ) {
                TimeSpan restartIn = TimeSpan.FromSeconds( ConfigKey.RestartInterval.GetInt() );
                Shutdown( new ShutdownParams( ShutdownReason.RestartTimer, restartIn, true ), false );
                ChatTimer.Start( restartIn, "Automatic Server Restart", Player.Console.Name );
            }
           
            // start the main loop - server is now connectible
            Scheduler.Start();
            IsRunning = true;

            RaiseEvent( Started );
            return true;
        }
Esempio n. 3
0
        static void BotHandler(Player player, Command cmd)
        {
            if (!player.ClassiCube || !Heartbeat.ClassiCube())
            {
                player.Message("Bots can only be used on ClassiCube servers and clients!");
                return;
            }
            string option = cmd.Next(); //take in the option arg
            if (string.IsNullOrEmpty(option)) //empty? return, otherwise continue
            {
                CdBot.PrintUsage(player);
                return;
            }

            //certain options that take in specific params are in here, the rest are in the switch-case
            if (option.ToLower() == "list")
            {
                player.Message("_Bots on {0}_", ConfigKey.ServerName.GetString());
                foreach (Bot botCheck in Server.Bots)
                {
                    player.Message(botCheck.Name + " on " + botCheck.World.Name);
                }
                return;
            }
            else if (option.ToLower() == "removeall")
            {
                Server.Bots.ForEach(botToRemove =>
                {
                    botToRemove.removeBot();
                });
                player.Message("All bots removed from the server.");
                return;
            }
            else if (option.ToLower() == "move")
            {
                string targetBot = cmd.Next();
                if (string.IsNullOrEmpty(targetBot))
                {
                    CdBot.PrintUsage(player);
                    return;
                }
                string targetPlayer = cmd.Next();
                if (string.IsNullOrEmpty(targetPlayer))
                {
                    CdBot.PrintUsage(player);
                    return;
                }

                Bot targetB = player.World.FindBot(targetBot);
                Player targetP = player.World.FindPlayerExact(targetPlayer);

                if (targetP == null)
                {
                    player.Message("Could not find {0} on {1}! Please make sure you spelled their name correctly.", targetPlayer, player.World);
                    return;
                }
                if (targetB == null)
                {
                    player.Message("Could not find {0} on {1}! Please make sure you spelled their name correctly.", targetBot, player.World);
                    return;
                }

                player.Message("{0} is now moving!", targetB.Name);
                targetB.isMoving = true;
                targetB.NewPosition = targetP.Position;
                targetB.OldPosition = targetB.Position;
                targetB.timeCheck.Start();
                return;
            }
            else if (option.ToLower() == "follow")
            {
                string targetBot = cmd.Next();
                if (string.IsNullOrEmpty(targetBot))
                {
                    CdBot.PrintUsage(player);
                    return;
                }
                string targetPlayer = cmd.Next();
                if (string.IsNullOrEmpty(targetPlayer))
                {
                    CdBot.PrintUsage(player);
                    return;
                }

                Bot targetB = player.World.FindBot(targetBot);
                Player targetP = player.World.FindPlayerExact(targetPlayer);

                if (targetP == null)
                {
                    player.Message("Could not find {0} on {1}! Please make sure you spelled their name correctly.", targetPlayer, player.World);
                    return;
                }
                if (targetB == null)
                {
                    player.Message("Could not find {0} on {1}! Please make sure you spelled their name correctly.", targetBot, player.World);
                    return;
                }

                player.Message("{0} is now following {1}!", targetB.Name, targetP.Name);
                targetB.isMoving = true;
                targetB.followTarget = targetP;
                targetB.OldPosition = targetB.Position;
                targetB.timeCheck.Start();
                return;
            }

            //finally away from the special cases
            string botName = cmd.Next(); //take in bot name arg
            if (string.IsNullOrEmpty(botName)) //null check
            {
                CdBot.PrintUsage(player);
                return;
            }

            Bot bot = new Bot();
            if (option != "create")//since the bot wouldn't exist for "create", we must check the bot for all cases other than "create"
            {
                bot = Server.FindBot(botName.ToLower()); //Find the bot and assign to bot var

                if (bot == null) //If null, return and yell at user
                {
                    player.Message("Could not find {0}! Please make sure you spelled the bot's name correctly. To view all the bots, type /Bot list.", botName);
                    return;
                }
            }

            //now to the cases - additional args should be taken in at the individual cases
            switch (option.ToLower())
            {
                case "create":
                    string requestedModel = cmd.Next();
                    if (string.IsNullOrEmpty(requestedModel))
                    {
                        player.Message("Usage is /Bot create <bot name> <bot model>. Valid models are chicken, creeper, croc, human, pig, printer, sheep, skeleton, spider, or zombie.");
                        return;
                    }

                    if (!validEntities.Contains(requestedModel))
                    {
                        player.Message("That wasn't a valid bot model! Valid models are chicken, creeper, croc, human, pig, printer, sheep, skeleton, spider, or zombie.");
                        return;
                    }

                    //if a botname has already been chosen, ask player for a new name
                    var matchingNames = from b in Server.Bots
                                   where b.Name.ToLower() == botName.ToLower()
                                   select b;

                    if (matchingNames.Count() > 0)
                    {
                        player.Message("A bot with that name already exists! To view all bots, type /bot list.");
                        return;
                    }

                    player.Message("Successfully created a bot.");
                    Bot botCreate = new Bot();
                    botCreate.setBot(botName, player.World, player.Position, LegendCraft.getNewID());
                    botCreate.createBot();
                    botCreate.changeBotModel(requestedModel);
                    break;
                case "remove":
                    player.Message("{0} was removed from the server.", bot.Name);
                    bot.removeBot();
                    break;
                case "fly":

                    if (bot.isFlying)
                    {
                        player.Message("{0} can no longer fly.", bot.Name);
                        bot.isFlying = false;
                        break;
                    }

                    player.Message("{0} can now fly!", bot.Name);
                    bot.isFlying = true;
                    break;
                case "model":

                    if (bot.Skin != "steve")
                    {
                        player.Message("Bots cannot change model with a skin! Use '/bot clone' to reset a bot's skin.");
                        return;
                    }

                    string model = cmd.Next();
                    if (string.IsNullOrEmpty(model))
                    {
                        player.Message("Usage is /Bot model <bot> <model>. Valid models are chicken, creeper, croc, human, pig, printer, sheep, skeleton, spider, or zombie.");
                        break;
                    }

                    if(model == "human")//lazy parse
                    {
                        model = "humanoid";
                    }
                    if (!validEntities.Contains(model))
                    {
                        player.Message("Please use a valid model name! Valid models are chicken, creeper, croc, human, pig, printer, sheep, skeleton, spider, or zombie.");
                        break;
                    }

                    player.Message("Changed bot model to {0}.", model);
                    bot.changeBotModel(model);

                    break;
                case "clone":

                    if (bot.Model != "humanoid")
                    {
                        player.Message("A bot must be a human in order to have a skin. Use '/bot model <bot> <model>' to change a bot's model.");
                        return;
                    }

                    string playerToClone = cmd.Next();
                    if (string.IsNullOrEmpty(playerToClone))
                    {
                        player.Message("{0}'s skin was reset!", bot.Name);
                        bot.Clone("steve");
                        break;
                    }
                    PlayerInfo targetPlayer = PlayerDB.FindPlayerInfoExact(playerToClone);
                    if (targetPlayer == null)
                    {
                        player.Message("That player doesn't exists! Please use a valid playername for the skin of the bot.");
                        break;
                    }

                    player.Message("{0}'s skin was updated!", bot.Name);
                    bot.Clone(playerToClone);
                    break;
                case "explode":

                    Server.Message("{0} exploded!", bot.Name);
                    bot.explodeBot(player);
                    break;
                case "summon":

                    if (player.World != bot.World)
                    {
                        bot.tempRemoveBot(); //remove the entity
                        bot.World = player.World; //update variables
                        bot.Position = player.Position;
                        bot.updateBotPosition(); //replace the entity
                    }
                    else
                    {
                        bot.Position = player.Position;
                        bot.teleportBot(player.Position);
                    }

                    if (bot.Model != "human")
                    {
                        bot.changeBotModel(bot.Model); //replace the model, if the model is set
                    }
                    if (bot.Skin != "steve")
                    {
                        bot.Clone(bot.Skin); //replace the skin, if a skin is set
                    }
                    break;
                case "stop":

                    player.Message("{0} is no longer moving.", bot.Name);
                    bot.isMoving = false;
                    bot.timeCheck.Stop();
                    bot.timeCheck.Reset();
                    bot.followTarget = null;
                    break;
                default:
                    CdBot.PrintUsage(player);
                    break;
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Saves the entity data to be used when restarting the server
 /// </summary>
 /// <param name="bot">entity being saved</param>
 public static void SaveEntity(Bot bot) {
     try {
         String[] entityData = {
             bot.Name, bot.SkinName ?? bot.Name, bot.Model ?? "humanoid", bot.ID.ToString(CultureInfo.InvariantCulture),
             bot.World.Name, bot.Position.X.ToString(CultureInfo.InvariantCulture),
             bot.Position.Y.ToString(CultureInfo.InvariantCulture),
             bot.Position.Z.ToString(CultureInfo.InvariantCulture),
             bot.Position.L.ToString(CultureInfo.InvariantCulture),
             bot.Position.R.ToString(CultureInfo.InvariantCulture)
         };
         if (!Directory.Exists("./Entities")) {
             Directory.CreateDirectory("./Entities");
         }
         File.WriteAllLines("./Entities/" + bot.Name.ToLower() + ".txt", entityData);
     } catch (Exception ex) {
         Player.Console.Message("Entity Saver Has Crashed: {0}", ex);
     }
 }