NextInt() private method

private NextInt ( int &number ) : bool
number int
return bool
        void Roll(Player player, Command cmd)
        {
            Random rand = new Random();
            int    min = 1, max = 100, num, t1, t2;

            if (cmd.NextInt(out t1))
            {
                if (cmd.NextInt(out t2))
                {
                    if (t2 >= t1)
                    {
                        min = t1;
                        max = t2;
                    }
                }
                else if (t1 >= 1)
                {
                    max = t1;
                }
            }
            num = rand.Next(min, max + 1);
            string msg = Color.Silver + player.name + " rolled " + num + " (" + min + "..." + max + ")";

            world.log.LogConsole(msg);
            world.SendToAll(PacketWriter.MakeMessage(msg), null);
        }
 void TP(Player player, Command cmd)
 {
     if (player.Can(Permissions.Teleport))
     {
         string name = cmd.Next();
         if (name == null)
         {
             player.Send(PacketWriter.MakeTeleport(255, world.map.spawn));
         }
         else
         {
             Player target = world.FindPlayer(name);
             if (target != null)
             {
                 Position pos = target.pos;
                 pos.x += 1;
                 pos.y += 1;
                 pos.h += 1;
                 player.Send(PacketWriter.MakeTeleport(255, pos));
             }
             else if (cmd.Next() == null)
             {
                 world.NoPlayerMessage(player, name);
             }
             else
             {
                 cmd.Rewind();
                 int x, y, h;
                 if (cmd.NextInt(out x) && cmd.NextInt(out y) && cmd.NextInt(out h))
                 {
                     if (x < 0 || x > world.map.widthX ||
                         y < 0 || y > world.map.widthY ||
                         y < 0 || y > world.map.height)
                     {
                         player.Message("Specified coordinates are outside the map!");
                     }
                     else
                     {
                         player.pos.Set(x * 32 + 16, y * 32 + 16, h * 32 + 16, player.pos.r, player.pos.l);
                         player.Send(PacketWriter.MakeTeleport(255, player.pos));
                     }
                 }
                 else
                 {
                     player.Message("See " + Color.Help + "/help tp" + Color.Sys + " for information on using /tp");
                 }
             }
         }
     }
     else
     {
         world.NoAccessMessage(player);
     }
 }
Beispiel #3
0
        static void RollHandler(Player player, Command cmd)
        {
            if (player.Info.IsMuted)
            {
                player.MessageMuted();
                return;
            }

            if (player.DetectChatSpam())
            {
                return;
            }

            Random rand = new Random();
            int    n1;
            int    min, max;

            if (cmd.NextInt(out n1))
            {
                int n2;
                if (!cmd.NextInt(out n2))
                {
                    n2 = 1;
                }
                min = Math.Min(n1, n2);
                max = Math.Max(n1, n2);
            }
            else
            {
                min = 1;
                max = 100;
            }

            int num = rand.Next(min, max + 1);

            Server.Message(player,
                           "{0}{1} rolled {2} ({3}...{4})",
                           player.ClassyName, Color.Silver, num, min, max);
            player.Message("{0}You rolled {1} ({2}...{3})",
                           Color.Silver, num, min, max);
        }
Beispiel #4
0
        void GenerateHollow(Player player, Command cmd)
        {
            if (!player.Can(Permissions.SaveAndLoad))
            {
                world.NoAccessMessage(player);
                return;
            }
            int wx, wy, height;

            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                player.Message("Usage: " + Color.Help + "/genh widthX widthY height type filename");
                return;
            }
            string mode     = cmd.Next();
            string filename = cmd.Next();

            if (mode == null || filename == null)
            {
                player.Message("Usage: " + Color.Help + "/genh widthX widthY height type filename");
                return;
            }
            filename += ".fcm";

            int seed;

            if (!cmd.NextInt(out seed))
            {
                seed = new Random().Next();
            }
            Random rand = new Random(seed);

            player.Message("Seed: " + Convert.ToBase64String(BitConverter.GetBytes(seed)));

            Map map = new Map(world, wx, wy, height);

            map.spawn.Set(map.widthX / 2 * 32 + 16, map.widthY / 2 * 32 + 16, map.height * 32, 0, 0);

            DoGenerate(map, player, mode, filename, rand, true);
        }
Beispiel #5
0
        internal static void Roll(Player player, Command cmd)
        {
            if (player.Info.IsMuted)
            {
                player.MutedMessage();
                return;
            }

            Random rand = new Random();
            int    min = 1, max = 100, t1;

            if (cmd.NextInt(out t1))
            {
                int t2;
                if (cmd.NextInt(out t2))
                {
                    if (t2 < t1)
                    {
                        min = t2;
                        max = t1;
                    }
                    else
                    {
                        min = t1;
                        max = t2;
                    }
                }
                else if (t1 >= 1)
                {
                    max = t1;
                }
            }
            int num = rand.Next(min, max + 1);

            Server.SendToAll("{0}{1} rolled {2} ({3}...{4})",
                             player.GetClassyName(), Color.Silver, num, min, max);
        }
Beispiel #6
0
 void Roll( Player player, Command cmd ) {
     Random rand = new Random();
     int min = 1, max = 100, num, t1, t2;
     if( cmd.NextInt( out t1 ) ) {
         if( cmd.NextInt( out t2 ) ) {
             if( t2 >= t1 ) {
                 min = t1;
                 max = t2;
             }
         } else if( t1 >= 1 ){
             max = t1;
         }
     }
     num = rand.Next( min, max+1 );
     string msg = Color.Silver + player.name + " rolled " + num + " ("+min+"..."+max+")";
     world.log.LogConsole( msg );
     world.SendToAll( PacketWriter.MakeMessage( msg ), null );
 }
        static void RotateHandler( Player player, Command cmd )
        {
            CopyState originalInfo = player.GetCopyInformation();
            if( originalInfo == null ) {
                player.MessageNow( "Nothing to rotate! Copy something first." );
                return;
            }

            int degrees;
            if( !cmd.NextInt( out degrees ) || (degrees != 90 && degrees != -90 && degrees != 180 && degrees != 270) ) {
                CdRotate.PrintUsage( player );
                return;
            }

            string axisName = cmd.Next();
            Axis axis = Axis.Z;
            if( axisName != null ) {
                switch( axisName.ToLower() ) {
                    case "x":
                        axis = Axis.X;
                        break;
                    case "y":
                        axis = Axis.Y;
                        break;
                    case "z":
                    case "h":
                        axis = Axis.Z;
                        break;
                    default:
                        CdRotate.PrintUsage( player );
                        return;
                }
            }

            // allocate the new buffer
            Block[, ,] oldBuffer = originalInfo.Buffer;
            Block[, ,] newBuffer;

            if( degrees == 180 ) {
                newBuffer = new Block[oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 2 )];

            } else if( axis == Axis.X ) {
                newBuffer = new Block[oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 2 ), oldBuffer.GetLength( 1 )];

            } else if( axis == Axis.Y ) {
                newBuffer = new Block[oldBuffer.GetLength( 2 ), oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 0 )];

            } else { // axis == Axis.Z
                newBuffer = new Block[oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 2 )];
            }

            // clone to avoid messing up any paste-in-progress
            CopyState info = new CopyState( originalInfo, newBuffer );

            // construct the rotation matrix
            int[,] matrix = new[,]{
                {1,0,0},
                {0,1,0},
                {0,0,1}
            };

            int a, b;
            switch( axis ) {
                case Axis.X:
                    a = 1;
                    b = 2;
                    break;
                case Axis.Y:
                    a = 0;
                    b = 2;
                    break;
                default:
                    a = 0;
                    b = 1;
                    break;
            }

            switch( degrees ) {
                case 90:
                    matrix[a, a] = 0;
                    matrix[b, b] = 0;
                    matrix[a, b] = -1;
                    matrix[b, a] = 1;
                    break;
                case 180:
                    matrix[a, a] = -1;
                    matrix[b, b] = -1;
                    break;
                case -90:
                case 270:
                    matrix[a, a] = 0;
                    matrix[b, b] = 0;
                    matrix[a, b] = 1;
                    matrix[b, a] = -1;
                    break;
            }

            // apply the rotation matrix
            for( int x = oldBuffer.GetLength( 0 ) - 1; x >= 0; x-- ) {
                for( int y = oldBuffer.GetLength( 1 ) - 1; y >= 0; y-- ) {
                    for( int z = oldBuffer.GetLength( 2 ) - 1; z >= 0; z-- ) {
                        int nx = (matrix[0, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[0, 0] > 0 ? x : 0)) +
                                 (matrix[0, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[0, 1] > 0 ? y : 0)) +
                                 (matrix[0, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[0, 2] > 0 ? z : 0));
                        int ny = (matrix[1, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[1, 0] > 0 ? x : 0)) +
                                 (matrix[1, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[1, 1] > 0 ? y : 0)) +
                                 (matrix[1, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[1, 2] > 0 ? z : 0));
                        int nz = (matrix[2, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[2, 0] > 0 ? x : 0)) +
                                 (matrix[2, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[2, 1] > 0 ? y : 0)) +
                                 (matrix[2, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[2, 2] > 0 ? z : 0));
                        newBuffer[nx, ny, nz] = oldBuffer[x, y, z];
                    }
                }
            }

            player.Message( "Rotated copy (slot {0}) by {1} degrees around {2} axis.",
                            info.Slot + 1, degrees, axis );
            player.SetCopyInformation( info );
        }
 static void CopySlotHandler( Player player, Command cmd )
 {
     int slotNumber;
     if( cmd.NextInt( out slotNumber ) ) {
         if( cmd.HasNext ) {
             CdCopySlot.PrintUsage( player );
             return;
         }
         if( slotNumber < 1 || slotNumber > player.Info.Rank.CopySlots ) {
             player.Message( "CopySlot: Select a number between 1 and {0}", player.Info.Rank.CopySlots );
         } else {
             player.CopySlot = slotNumber - 1;
             CopyState info = player.GetCopyInformation();
             if( info == null ) {
                 player.Message( "Selected copy slot {0} (unused).", slotNumber );
             } else {
                 player.Message( "Selected copy slot {0}: {1} blocks from {2}, {3} old.",
                                 slotNumber, info.Buffer.Length,
                                 info.OriginWorld, DateTime.UtcNow.Subtract( info.CopyTime ).ToMiniString() );
             }
         }
     } else {
         CopyState[] slots = player.CopyInformation;
         player.Message( "Using {0} of {1} slots. Selected slot: {2}",
                         slots.Count( info => info != null ), player.Info.Rank.CopySlots, player.CopySlot + 1 );
         for( int i = 0; i < slots.Length; i++ ) {
             if( slots[i] != null ) {
                 player.Message( "  {0}: {1} blocks from {2}, {3} old",
                                 i + 1, slots[i].Buffer.Length,
                                 slots[i].OriginWorld, DateTime.UtcNow.Subtract( slots[i].CopyTime ).ToMiniString() );
             }
         }
     }
 }
Beispiel #9
0
        public static void RealmCreate(Player player, Command cmd, string themeName, string templateName)
        {
            MapGenTemplate template;
            MapGenTheme    theme;

            int wx, wy, height = 128;

            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                if (player.World != null)
                {
                    wx     = 128;
                    wy     = 128;
                    height = 128;
                }
                else
                {
                    player.Message("When used from console, /gen requires map dimensions.");

                    return;
                }
                cmd.Rewind();
                cmd.Next();
                cmd.Next();
            }

            if (!Map.IsValidDimension(wx))
            {
                player.Message("Cannot make map with width {0}: dimensions must be multiples of 16.", wx);
                return;
            }
            else if (!Map.IsValidDimension(wy))
            {
                player.Message("Cannot make map with length {0}: dimensions must be multiples of 16.", wy);
                return;
            }
            else if (!Map.IsValidDimension(height))
            {
                player.Message("Cannot make map with height {0}: dimensions must be multiples of 16.", height);
                return;
            }

            string fileName     = player.Name;
            string fullFileName = null;

            if (fileName == null)
            {
                if (player.World == null)
                {
                    player.Message("When used from console, /gen requires FileName.");

                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace this realm's map with a generated one?");
                    return;
                }
            }
            else
            {
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.IsValidPath(fullFileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            bool noTrees;

            if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
            {
                theme   = MapGenTheme.Forest;
                noTrees = true;
            }
            else
            {
                try
                {
                    theme   = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), themeName, true);
                    noTrees = (theme != MapGenTheme.Forest);
                }
                catch (Exception)
                {
                    player.MessageNow("Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                      themeName,
                                      String.Join(", ", Enum.GetNames(typeof(MapGenTheme))));
                    return;
                }
            }

            try
            {
                template = (MapGenTemplate)Enum.Parse(typeof(MapGenTemplate), templateName, true);
            }
            catch (Exception)
            {
                player.Message("Unrecognized template \"{0}\". Available templates are: {1}",
                               templateName,
                               String.Join(", ", Enum.GetNames(typeof(MapGenTemplate))));
                return;
            }

            if (!Enum.IsDefined(typeof(MapGenTheme), theme) || !Enum.IsDefined(typeof(MapGenTemplate), template))
            {
                return;
            }

            MapGeneratorArgs args = MapGenerator.MakeTemplate(template);

            args.MapWidth  = wx;
            args.MapLength = wy;
            args.MapHeight = height;
            args.MaxHeight = (int)(args.MaxHeight / 80d * height);
            args.MaxDepth  = (int)(args.MaxDepth / 80d * height);
            args.Theme     = theme;
            args.AddTrees  = !noTrees;

            Map map;

            try
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    player.MessageNow("Generating Grass {0}...", template);
                }
                else
                {
                    player.MessageNow("Generating {0} {1}...", theme, template);
                }
                if (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat)
                {
                    map = MapGenerator.GenerateFlatgrass(args.MapWidth, args.MapLength, args.MapHeight);
                }
                else
                {
                    MapGenerator generator = new MapGenerator(args);
                    map = generator.Generate();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "MapGenerator: Generation failed: {0}",
                           ex);
                player.MessageNow("&WAn error occured while generating the map.");
                return;
            }

            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.MessageNow("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                player.MessageNow("Generation done. Changing map...");
                player.World.ChangeMap(map);
            }
        }
Beispiel #10
0
        static void TimerHandler( Player player, Command cmd ) {
            string param = cmd.Next();

            // List timers
            if( param == null ) {
                ChatTimer[] list = ChatTimer.TimerList.OrderBy( timer => timer.TimeLeft ).ToArray();
                if( list.Length == 0 ) {
                    player.Message( "No timers running." );
                } else {
                    player.Message( "There are {0} timers running:", list.Length );
                    foreach( ChatTimer timer in list ) {
                        player.Message( "  #{0} \"{1}&S\" (started by {2}, {3} left)",
                                        timer.Id, timer.Message, timer.StartedBy, timer.TimeLeft.ToMiniString() );
                    }
                }
                return;
            }

            // Abort a timer
            if( param.Equals( "abort", StringComparison.OrdinalIgnoreCase ) ) {
                int timerId;
                if( cmd.NextInt( out timerId ) ) {
                    ChatTimer timer = ChatTimer.FindTimerById( timerId );
                    if( timer == null || !timer.IsRunning ) {
                        player.Message( "Given timer (#{0}) does not exist.", timerId );
                    } else {
                        timer.Stop();
                        string abortMsg = String.Format( "&Y(Timer) {0}&Y aborted a timer with {1} left: {2}",
                                                         player.ClassyName, timer.TimeLeft.ToMiniString(), timer.Message );
                        Chat.SendSay( player, abortMsg );
                    }
                } else {
                    CdTimer.PrintUsage( player );
                }
                return;
            }

            // Start a timer
            if( player.Info.IsMuted ) {
                player.MessageMuted();
                return;
            }
            if( player.DetectChatSpam() ) return;
            TimeSpan duration;
            if( !param.TryParseMiniTimespan( out duration ) ) {
                CdTimer.PrintUsage( player );
                return;
            }
            if( duration > DateTimeUtil.MaxTimeSpan ) {
                player.MessageMaxTimeSpan();
                return;
            }
            if( duration < ChatTimer.MinDuration ) {
                player.Message( "Timer: Must be at least 1 second." );
                return;
            }

            string sayMessage;
            string message = cmd.NextAll();
            if( String.IsNullOrEmpty( message ) ) {
                sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer",
                                            player.ClassyName,
                                            duration.ToMiniString() );
            } else {
                sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer: {2}",
                                            player.ClassyName,
                                            duration.ToMiniString(),
                                            message );
            }
            Chat.SendSay( player, sayMessage );
            ChatTimer.Start( duration, message, player.Name );
        }
Beispiel #11
0
        static void GenHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;
            string themeName = cmd.Next();
            string templateName;
            bool genOcean = false;
            bool genEmpty = false;
            bool noTrees = false;

            if (themeName == null)
            {
                CdGenerate.PrintUsage(player);
                return;
            }
            MapGenTheme theme = MapGenTheme.Forest;
            MapGenTemplate template = MapGenTemplate.Flat;

            // parse special template names (which do not need a theme)
            if (themeName.Equals("ocean"))
            {
                genOcean = true;

            }
            else if (themeName.Equals("empty"))
            {
                genEmpty = true;

            }
            else
            {
                templateName = cmd.Next();
                if (templateName == null)
                {
                    CdGenerate.PrintUsage(player);
                    return;
                }

                // parse theme
                bool swapThemeAndTemplate = false;
                if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
                {
                    theme = MapGenTheme.Forest;
                    noTrees = true;

                }
                else if (templateName.Equals("grass", StringComparison.OrdinalIgnoreCase))
                {
                    theme = MapGenTheme.Forest;
                    noTrees = true;
                    swapThemeAndTemplate = true;

                }
                else if (EnumUtil.TryParse(themeName, out theme, true))
                {
                    noTrees = (theme != MapGenTheme.Forest);

                }
                else if (EnumUtil.TryParse(templateName, out theme, true))
                {
                    noTrees = (theme != MapGenTheme.Forest);
                    swapThemeAndTemplate = true;

                }
                else
                {
                    player.Message("Gen: Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                    themeName,
                                    Enum.GetNames(typeof(MapGenTheme)).JoinToString());
                    return;
                }

                // parse template
                if (swapThemeAndTemplate)
                {
                    if (!EnumUtil.TryParse(themeName, out template, true))
                    {
                        player.Message("Unrecognized template \"{0}\". Available terrain types: Empty, Ocean, {1}",
                                        themeName,
                                        Enum.GetNames(typeof(MapGenTemplate)).JoinToString());
                        return;
                    }
                }
                else
                {
                    if (!EnumUtil.TryParse(templateName, out template, true))
                    {
                        player.Message("Unrecognized template \"{0}\". Available terrain types: Empty, Ocean, {1}",
                                        templateName,
                                        Enum.GetNames(typeof(MapGenTemplate)).JoinToString());
                        return;
                    }
                }
            }

            // parse map dimensions
            int mapWidth, mapLength, mapHeight;
            if (cmd.HasNext)
            {
                int offset = cmd.Offset;
                if (!(cmd.NextInt(out mapWidth) && cmd.NextInt(out mapLength) && cmd.NextInt(out mapHeight)))
                {
                    if (playerWorld != null)
                    {
                        Map oldMap = player.WorldMap;
                        // If map dimensions were not given, use current map's dimensions
                        mapWidth = oldMap.Width;
                        mapLength = oldMap.Length;
                        mapHeight = oldMap.Height;
                    }
                    else
                    {
                        player.Message("When used from console, /Gen requires map dimensions.");
                        CdGenerate.PrintUsage(player);
                        return;
                    }
                    cmd.Offset = offset;
                }
            }
            else if (playerWorld != null)
            {
                Map oldMap = player.WorldMap;
                // If map dimensions were not given, use current map's dimensions
                mapWidth = oldMap.Width;
                mapLength = oldMap.Length;
                mapHeight = oldMap.Height;
            }
            else
            {
                player.Message("When used from console, /Gen requires map dimensions.");
                CdGenerate.PrintUsage(player);
                return;
            }

            // Check map dimensions
            const string dimensionRecommendation = "Dimensions must be between 16 and 2047. " +
                                                   "Recommended values: 16, 32, 64, 128, 256, 512, and 1024.";
            if (!Map.IsValidDimension(mapWidth))
            {
                player.Message("Cannot make map with width {0}. {1}", mapWidth, dimensionRecommendation);
                return;
            }
            else if (!Map.IsValidDimension(mapLength))
            {
                player.Message("Cannot make map with length {0}. {1}", mapLength, dimensionRecommendation);
                return;
            }
            else if (!Map.IsValidDimension(mapHeight))
            {
                player.Message("Cannot make map with height {0}. {1}", mapHeight, dimensionRecommendation);
                return;
            }
            long volume = (long)mapWidth * (long)mapLength * (long)mapHeight;
            if (volume > Int32.MaxValue)
            {
                player.Message("Map volume may not exceed {0}", Int32.MaxValue);
                return;
            }

            if (!cmd.IsConfirmed && (!Map.IsRecommendedDimension(mapWidth) || !Map.IsRecommendedDimension(mapLength) || !Map.IsRecommendedDimension(mapHeight)))
            {
                player.Message("&WThe map will have non-standard dimensions. " +
                                "You may see glitched blocks or visual artifacts. " +
                                "The only recommended map dimensions are: 16, 32, 64, 128, 256, 512, and 1024.");
            }

            // figure out full template name
            bool genFlatgrass = (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat);
            string templateFullName;
            if (genEmpty)
            {
                templateFullName = "Empty";
            }
            else if (genOcean)
            {
                templateFullName = "Ocean";
            }
            else if (genFlatgrass)
            {
                templateFullName = "Flatgrass";
            }
            else
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    templateFullName = "Grass " + template;
                }
                else
                {
                    templateFullName = theme + " " + template;
                }
            }

            // check file/world name
            string fileName = cmd.Next();
            string fullFileName = null;
            if (fileName == null)
            {
                // replacing current world
                if (playerWorld == null)
                {
                    player.Message("When used from console, /Gen requires FileName.");
                    CdGenerate.PrintUsage(player);
                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace THIS MAP with a generated one ({0})?", templateFullName);
                    return;
                }

            }
            else
            {
                if (cmd.HasNext)
                {
                    CdGenerate.PrintUsage(player);
                    return;
                }
                // saving to file
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                if (!Paths.IsValidPath(fileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            // generate the map
            Map map;
            player.MessageNow("Generating {0}...", templateFullName);

            if (genEmpty)
            {
                map = MapGenerator.GenerateEmpty(mapWidth, mapLength, mapHeight);

            }
            else if (genOcean)
            {
                map = MapGenerator.GenerateOcean(mapWidth, mapLength, mapHeight);

            }
            else if (genFlatgrass)
            {
                map = MapGenerator.GenerateFlatgrass(mapWidth, mapLength, mapHeight);

            }
            else
            {
                MapGeneratorArgs args = MapGenerator.MakeTemplate(template);
                if (theme == MapGenTheme.Desert)
                {
                    args.AddWater = false;
                }
                float ratio = mapHeight / (float)args.MapHeight;
                args.MapWidth = mapWidth;
                args.MapLength = mapLength;
                args.MapHeight = mapHeight;
                args.MaxHeight = (int)Math.Round(args.MaxHeight * ratio);
                args.MaxDepth = (int)Math.Round(args.MaxDepth * ratio);
                args.SnowAltitude = (int)Math.Round(args.SnowAltitude * ratio);
                args.Theme = theme;
                args.AddTrees = !noTrees;

                MapGenerator generator = new MapGenerator(args);
                map = generator.Generate();
            }

            // save map to file, or load it into a world
            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.Message("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                if (playerWorld == null) PlayerOpException.ThrowNoWorld(player);
                player.MessageNow("Generation done. Changing map...");
                playerWorld.MapChangedBy = player.Name;
                playerWorld.ChangeMap(map);
            }
            Server.RequestGC();
        }
Beispiel #12
0
        static void WorldsHandler(Player player, Command cmd)
        {
            string param = cmd.Next();
            World[] worlds;

            string listName;
            string extraParam;
            int offset = 0;

            if (param == null || Int32.TryParse(param, out offset))
            {
                listName = "available worlds";
                extraParam = "";
                worlds = WorldManager.Worlds.Where(w => !w.IsRealm).Where(player.CanSee).ToArray();

            }
            else
            {
                switch (Char.ToLower(param[0]))
                {
                    case 'a':
                        listName = "worlds";
                        extraParam = "all ";
                        worlds = WorldManager.Worlds;
                        break;
                    case 'h':
                        listName = "hidden worlds";
                        extraParam = "hidden ";
                        worlds = WorldManager.Worlds.Where(w => !player.CanSee(w)).ToArray();
                        break;
                    case 'r':
                        listName = "Available Realms";
                        extraParam = "realms";
                        worlds = WorldManager.Worlds.Where(w => w.IsRealm).ToArray();
                        break;
                    case 'p':
                        listName = "populated worlds";
                        extraParam = "populated ";
                        worlds = WorldManager.Worlds.Where(w => w.Players.Any(player.CanSee)).ToArray();
                        break;
                    case '@':
                        if (param.Length == 1)
                        {
                            CdWorlds.PrintUsage(player);
                            return;
                        }
                        string rankName = param.Substring(1);
                        Rank rank = RankManager.FindRank(rankName);
                        if (rank == null)
                        {
                            player.MessageNoRank(rankName);
                            return;
                        }
                        listName = String.Format("worlds where {0}&S+ can build", rank.ClassyName);
                        extraParam = "@" + rank.Name + " ";
                        worlds = WorldManager.Worlds.Where(w => (w.BuildSecurity.MinRank <= rank) && player.CanSee(w))
                                                    .ToArray();
                        break;
                    default:
                        CdWorlds.PrintUsage(player);
                        return;
                }
                if (cmd.HasNext && !cmd.NextInt(out offset))
                {
                    CdWorlds.PrintUsage(player);
                    return;
                }
            }

            if (worlds.Length == 0)
            {
                player.Message("There are no {0}.", listName);

            }
            else if (worlds.Length <= WorldNamesPerPage || player.IsSuper)
            {
                player.MessagePrefixed("&S  ", "&SThere are {0} {1}: {2}",
                                        worlds.Length, listName, worlds.JoinToClassyString());

            }
            else
            {
                if (offset >= worlds.Length)
                {
                    offset = Math.Max(0, worlds.Length - WorldNamesPerPage);
                }
                World[] worldsPart = worlds.Skip(offset).Take(WorldNamesPerPage).ToArray();
                player.MessagePrefixed("&S   ", "&S{0}: {1}",
                                        listName.UppercaseFirst(), worldsPart.JoinToClassyString());

                if (offset + worldsPart.Length < worlds.Length)
                {
                    player.Message("Showing {0}-{1} (out of {2}). Next: &H/Worlds {3}{1}",
                                    offset + 1, offset + worldsPart.Length, worlds.Length, extraParam);
                }
                else
                {
                    player.Message("Showing worlds {0}-{1} (out of {2}).",
                                    offset + 1, offset + worldsPart.Length, worlds.Length);
                }
            }
        }
Beispiel #13
0
 static void Draw2DHandler( Player player, Command cmd )
 {
     string Shape = cmd.Next();
     if ( Shape == null ) {
         CdDraw2D.PrintUsage( player );
         return;
     }
     switch ( Shape.ToLower() ) {
         case "polygon":
         case "star":
         case "spiral":
             break;
         default:
             CdDraw2D.PrintUsage( player );
             return;
     }
     int radius = 0;
     int Points = 0;
     if ( !cmd.NextInt( out radius ) ) {
         radius = 20;
     }
     if ( !cmd.NextInt( out Points ) ) {
         Points = 5;
     }
     bool fill = true;
     if ( cmd.HasNext ) {
         if ( !bool.TryParse( cmd.Next(), out fill ) ) {
             fill = true;
         }
     }
     Draw2DData tag = new Draw2DData() { Shape = Shape, Points = Points, Radius = radius, Fill = fill };
     player.Message( "Draw2D({0}): Click 2 blocks or use &H/Mark&S to set direction.", Shape );
     player.SelectionStart( 2, Draw2DCallback, tag, Permission.DrawAdvanced );
 }
Beispiel #14
0
 static void SetFontHandler( Player player, Command cmd )
 {
     string Param = cmd.Next();
     if ( Param == null ) {
         CdSetFont.PrintUsage( player );
         return;
     }
     if ( Param.ToLower() == "reset" ) {
         player.font = new Font( "Times New Roman", 20, FontStyle.Regular );
         player.Message( "SetFont: Font reverted back to default ({0} size {1})",
             player.font.FontFamily.Name, player.font.Size );
         return;
     }
     if ( Param.ToLower() == "font" ) {
         string sectionName = cmd.NextAll();
         if ( !Directory.Exists( Paths.FontsPath ) ) {
             Directory.CreateDirectory( Paths.FontsPath );
             player.Message( "There are no fonts available for this server. Font is set to default: {0}", player.font.FontFamily.Name );
             return;
         }
         string fontFileName = null;
         string[] sectionFiles = Directory.GetFiles( Paths.FontsPath, "*.ttf", SearchOption.TopDirectoryOnly );
         if ( sectionName.Length < 1 ) {
             var sectionList = GetFontSectionList();
             player.Message( "{0} fonts Available: {1}", sectionList.Length, sectionList.JoinToString() ); //print the folder contents
             return;
         }
         for ( int i = 0; i < sectionFiles.Length; i++ ) {
             string sectionFullName = Path.GetFileNameWithoutExtension( sectionFiles[i] );
             if ( sectionFullName == null ) continue;
             if ( sectionFullName.StartsWith( sectionName, StringComparison.OrdinalIgnoreCase ) ) {
                 if ( sectionFullName.Equals( sectionName, StringComparison.OrdinalIgnoreCase ) ) {
                     fontFileName = sectionFiles[i];
                     break;
                 } else if ( fontFileName == null ) {
                     fontFileName = sectionFiles[i];
                 } else {
                     var matches = sectionFiles.Select( f => Path.GetFileNameWithoutExtension( f ) )
                                               .Where( sn => sn != null && sn.StartsWith( sectionName, StringComparison.OrdinalIgnoreCase ) );
                     player.Message( "Multiple font files matched \"{0}\": {1}",
                                     sectionName, matches.JoinToString() );
                     return;
                 }
             }
         }
         if ( fontFileName != null ) {
             string sectionFullName = Path.GetFileNameWithoutExtension( fontFileName );
             player.Message( "Your font has changed to \"{0}\":", sectionFullName );
             //change font here
             player.font = new System.Drawing.Font( player.LoadFontFamily( fontFileName ), player.font.Size );
             return;
         } else {
             var sectionList = GetFontSectionList();
             if ( sectionList == null ) {
                 player.Message( "No fonts have been found." );
             } else {
                 player.Message( "No fonts found for \"{0}\". Available fonts: {1}",
                                 sectionName, sectionList.JoinToString() );
             }
         }
     }
     if ( Param.ToLower() == "size" ) {
         int Size = -1;
         if ( cmd.NextInt( out Size ) ) {
             if ( Size > 48 || Size < 10 ) {
                 player.Message( "&WIncorrect font size ({0}): Size needs to be between 10 and 48", Size );
                 return;
             }
             player.Message( "SetFont: Size changed from {0} to {1} ({2})", player.font.Size, Size, player.font.FontFamily.Name );
             player.font = new System.Drawing.Font( player.font.FontFamily, Size );
         } else {
             player.Message( "&WInvalid size, use /SetFont Size FontSize. Example: /SetFont Size 14" );
             return;
         }
         return;
     } else {
         CdSetFont.PrintUsage( player );
         return;
     }
 }
Beispiel #15
0
        internal static void Generate( Player player, Command cmd )
        {
            if( !player.Can( Permissions.ManageWorlds ) ) {
                player.NoAccessMessage( Permissions.ManageWorlds );
                return;
            }
            int wx, wy, height;
            if( !(cmd.NextInt( out wx ) && cmd.NextInt( out wy ) && cmd.NextInt( out height )) ) {
                if( player.world != null ) {
                    wx = player.world.map.widthX;
                    wy = player.world.map.widthY;
                    height = player.world.map.height;
                } else {
                    player.Message( "Usage: " + Color.Help + "/gen widthX widthY height type filename" );
                    return;
                }
                cmd.Rewind();
            }
            string mode = cmd.Next();
            string filename = cmd.Next();
            if( mode == null || filename == null ) {
                player.Message( "Usage: " + Color.Help + "/gen widthX widthY height type filename" );
                return;
            }
            filename += ".fcm";

            int seed;
            if( !cmd.NextInt( out seed ) ) {
                seed = new Random().Next();
            }
            Random rand = new Random( seed );
            //player.Message( "Seed: " + Convert.ToBase64String( BitConverter.GetBytes( seed ) ) );

            Map map = new Map( player.world, wx, wy, height );
            map.spawn.Set( map.widthX / 2 * 32 + 16, map.widthY / 2 * 32 + 16, map.height * 32, 0, 0 );

            DoGenerate( map, player, mode, filename, rand, false );
        }
Beispiel #16
0
        internal static void ListHandler( Player player, Command cmd )
        {
            string Option = cmd.Next();
            if ( Option == null ) {
                CdList.PrintUsage( player );
                player.Message( "  Sections include: Staff, DisplayedNames, Idles, Portals, Rank, Top10, Emotes" );
                return;
            }
            switch ( Option.ToLower() ) {
                default:
                    CdList.PrintUsage( player );
                    player.Message( "  Sections include: Staff, DisplayedNames, Idles, Portals, Rank, Top10, Emotes" );
                    break;
                case "emotes":
                    string Usage = "Shows a list of all available emotes and their keywords. " +
                   "There are 31 emotes, spanning 3 pages. Use &h/List emotes 2&s and &h/List emotes 3&s to see pages 2 and 3.";
                    int page = 1;
                    if ( cmd.HasNext ) {
                        if ( !cmd.NextInt( out page ) ) {
                            player.Message( Usage );
                            return;
                        }
                    }
                    if ( page < 1 || page > 3 ) {
                        player.Message( Usage );
                        return;
                    }

                    var emoteChars = Chat.EmoteKeywords
                                         .Values
                                         .Distinct()
                                         .Skip( ( page - 1 ) * 11 )
                                         .Take( 11 );

                    player.Message( "List of emotes, page {0} of 3:", page );
                    foreach ( char ch in emoteChars ) {
                        char ch1 = ch;
                        string keywords = Chat.EmoteKeywords
                                              .Where( pair => pair.Value == ch1 )
                                              .Select( kvp => "{&F" + kvp.Key.UppercaseFirst() + "&7}" )
                                              .JoinToString( " " );
                        player.Message( "&F  {0} &7= {1}", ch, keywords );
                    }
                    if ( page < 3 )
                        player.Message( "Type /List Emotes {0} for the next page", page + 1 );

                    break;
                case "top10":
                    List<World> WorldNames = new List<World>( WorldManager.Worlds.Where( w => w.VisitCount > 0 )
                                         .OrderBy( c => c.VisitCount )
                                         .ToArray()
                                         .Reverse() );
                    string list = WorldNames.Take( 10 ).JoinToString( w => String.Format( "{0}&S: {1}", w.ClassyName, w.VisitCount ) );
                    if ( WorldNames.Count() < 1 ) {
                        player.Message( "&WNo results found" );
                        return;
                    }
                    player.Message( "&WShowing worlds with the most visits: " + list );
                    WorldNames.Clear();
                    break;
                case "idles":
                case "idle":
                    var Idles = Server.Players.Where( p => p.IdleTime.TotalMinutes > 5 ).ToArray();
                    var visiblePlayers = Idles.Where( player.CanSee );
                    if ( visiblePlayers.Count() > 0 )
                        player.Message( "Listing players idle for 5 mins or more: {0}",
                                        visiblePlayers.JoinToString( r => String.Format( "{0}&S (Idle {1}", r.ClassyName, r.IdleTime.ToMiniString() ) ) );
                    else player.Message( "No players have been idle for more than 5 minutes" );
                    break;
                case "portals":
                    if ( player.World == null ) {
                        player.Message( "/List portals cannot be used from Console" );
                        return;
                    }
                    if ( player.World.Map.Portals == null ||
                        player.World.Map.Portals.Count == 0 ) {
                        player.Message( "There are no portals in {0}&S.", player.World.ClassyName );
                    } else {
                        String[] portalNames = new String[player.World.Map.Portals.Count];
                        StringBuilder output = new StringBuilder( "There are " + player.World.Map.Portals.Count + " portals in " + player.World.ClassyName + "&S: " );

                        for ( int i = 0; i < player.World.Map.Portals.Count; i++ ) {
                            portalNames[i] = ( ( fCraft.Portals.Portal )player.World.Map.Portals[i] ).Name;
                        }
                        output.Append( portalNames.JoinToString( ", " ) );
                        player.Message( output.ToString() );
                    }
                    break;
                case "staff":
                    var StaffNames = PlayerDB.PlayerInfoList
                                         .Where( r => r.Rank.Can( Permission.ReadStaffChat ) &&
                                             r.Rank.Can( Permission.Ban ) &&
                                             r.Rank.Can( Permission.Promote ) )
                                             .OrderBy( p => p.Rank )
                                             .ToArray();
                    if ( StaffNames.Length < 1 ) {
                        player.Message( "&WNo results found" );
                        return;
                    }
                    if ( StaffNames.Length <= PlayersPerPage ) {
                        player.MessageManyMatches( "staff", StaffNames );
                    } else {
                        int offset;
                        if ( !cmd.NextInt( out offset ) ) offset = 0;
                        if ( offset >= StaffNames.Length )
                            offset = Math.Max( 0, StaffNames.Length - PlayersPerPage );
                        PlayerInfo[] StaffPart = StaffNames.Skip( offset ).Take( PlayersPerPage ).ToArray();
                        player.MessageManyMatches( "staff", StaffPart );
                        if ( offset + StaffPart.Length < StaffNames.Length )
                            player.Message( "Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + StaffPart.Length, StaffNames.Length,
                                            "staff", offset + StaffPart.Length );
                        else
                            player.Message( "Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + StaffPart.Length, StaffNames.Length );
                    }
                    break;

                case "rank":
                    string rankName = cmd.Next();
                    if ( rankName == null ) {
                        player.Message( "Usage: /List rank rankName" );
                        return;
                    }
                    Rank rank = RankManager.FindRank( rankName );
                    var RankNames = PlayerDB.PlayerInfoList
                                         .Where( r => r.Rank == rank )
                                             .ToArray();
                    if ( RankNames.Length < 1 ) {
                        player.Message( "&WNo results found" );
                        return;
                    }
                    if ( RankNames.Length <= PlayersPerPage ) {
                        player.MessageManyMatches( "players", RankNames );
                    } else {
                        int offset;
                        if ( !cmd.NextInt( out offset ) ) offset = 0;
                        if ( offset >= RankNames.Length )
                            offset = Math.Max( 0, RankNames.Length - PlayersPerPage );
                        PlayerInfo[] RankPart = RankNames.Skip( offset ).Take( PlayersPerPage ).ToArray();
                        player.MessageManyMatches( "rank list", RankPart );
                        if ( offset + RankPart.Length < RankNames.Length )
                            player.Message( "Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + RankPart.Length, RankNames.Length,
                                            "rank " + rank.ClassyName, offset + RankPart.Length );
                        else
                            player.Message( "Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + RankPart.Length, RankNames.Length );
                    }
                    break;
                case "displayednames":
                case "displayedname":
                case "dn":
                    var DisplayedNames = PlayerDB.PlayerInfoList
                                             .Where( r => r.DisplayedName != null ).OrderBy( p => p.Rank ).ToArray();
                    if ( DisplayedNames.Length < 1 ) {
                        player.Message( "&WNo results found" );
                        return;
                    }
                    if ( DisplayedNames.Length <= 15 ) {
                        player.MessageManyDisplayedNamesMatches( "DisplayedNames", DisplayedNames );
                    } else {
                        int offset;
                        if ( !cmd.NextInt( out offset ) ) offset = 0;
                        if ( offset >= DisplayedNames.Count() )
                            offset = Math.Max( 0, DisplayedNames.Length - 15 );
                        PlayerInfo[] DnPart = DisplayedNames.Skip( offset ).Take( 15 ).ToArray();
                        player.MessageManyDisplayedNamesMatches( "DisplayedNames", DnPart );
                        if ( offset + DisplayedNames.Length < DisplayedNames.Length )
                            player.Message( "Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + DnPart.Length, DisplayedNames.Length,
                                            "DisplayedNames", offset + DnPart.Length );
                        else
                            player.Message( "Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + DnPart.Length, DisplayedNames.Length );
                    }
                    break;
            }
        }
Beispiel #17
0
        internal static void Roll( Player player, Command cmd ) {
            if( player.Info.IsMuted ) {
                player.MutedMessage();
                return;
            }

            Random rand = new Random();
            int min = 1, max = 100, t1;
            if( cmd.NextInt( out t1 ) ) {
                int t2;
                if( cmd.NextInt( out t2 ) ) {
                    if( t2 < t1 ) {
                        min = t2;
                        max = t1;
                    } else {
                        min = t1;
                        max = t2;
                    }
                } else if( t1 >= 1 ) {
                    max = t1;
                }
            }
            int num = rand.Next( min, max + 1 );
            Server.SendToAll( "{0}{1} rolled {2} ({3}...{4})",
                              player.GetClassyName(), Color.Silver, num, min, max );
        }
Beispiel #18
0
        static void TreeHandler( Player player, Command cmd )
        {
            string shapeName = cmd.Next();
            int height;
            Forester.TreeShape shape;

            // that's one ugly if statement... does the job though.
            if( shapeName == null ||
                !cmd.NextInt( out height ) ||
                !EnumUtil.TryParse( shapeName, out shape, true ) ||
                shape == Forester.TreeShape.Stickly ||
                shape == Forester.TreeShape.Procedural ) {

                CdTree.PrintUsage( player );
                return;
            }

            if( height < 2 || height > 1024 ) {
                player.Message( "Tree height must be between 2 and 1024 blocks." );
                return;
            }

            Map map = player.World.Map;

            ForesterArgs args = new ForesterArgs {
                Height = height,
                Shape = shape,
                Map = map,
                Rand = new Random()
            };

            player.SelectionStart( 1, TreeCallback, args, CdTree.Permissions );
        }
Beispiel #19
0
        internal static void ListHandler(Player player, Command cmd)
        {
            string Option = cmd.Next();

            if (Option == null)
            {
                CdList.PrintUsage(player);
                return;
            }
            if (Option.ToLower() == "staff")
            {
                var StaffNames = PlayerDB.PlayerInfoList
                                     .Where(r => r.Rank.Can(Permission.ReadStaffChat) &&
                                         r.Rank.Can(Permission.Ban) &&
                                         r.Rank.Can(Permission.Promote))
                                         .ToArray();

                if (StaffNames.Length <= PlayersPerPage)
                {
                    player.MessageManyMatches("staff", StaffNames);
                }

                else
                {
                    int offset;

                    if (!cmd.NextInt(out offset)) offset = 0;

                    if (offset >= StaffNames.Length)
                        offset = Math.Max(0, StaffNames.Length - PlayersPerPage);

                    PlayerInfo[] StaffPart = StaffNames.Skip(offset).Take(PlayersPerPage).ToArray();
                    player.MessageManyMatches("staff", StaffPart);

                    if (offset + StaffPart.Length < StaffNames.Length)
                        player.Message("Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                        offset + 1, offset + StaffPart.Length, StaffNames.Length,
                                        "staff", offset + StaffPart.Length);
                    else
                        player.Message("Showing matches {0}-{1} (out of {2}).",
                                        offset + 1, offset + StaffPart.Length, StaffNames.Length);
                }
            }

            if (Option.ToLower() == "displayednames" || Option.ToLower() == "displayedname" || Option.ToLower() == "dn")
            {

                var DisplayedNames = PlayerDB.PlayerInfoList
                                         .Where(r => r.DisplayedName != null).ToArray();
                if (DisplayedNames.Count() > 0)
                    player.Message("Listing all DisplayedNames: {0}",
                                    DisplayedNames.JoinToString(r => String.Format("{0}&S({1})", r.ClassyName, r.Name)));
                else player.Message("No players with DisplayedNames were found in the Player Database");
            }
        }
Beispiel #20
0
        static void TimerHandler(Player player, Command cmd)
        {
            string param = cmd.Next();

            // List timers
            if (param == null)
            {
                ChatTimer[] list = ChatTimer.TimerList.OrderBy(timer => timer.TimeLeft).ToArray();
                if (list.Length == 0)
                {
                    player.Message("No timers running.");
                }
                else
                {
                    player.Message("There are {0} timers running:", list.Length);
                    foreach (ChatTimer timer in list)
                    {
                        player.Message("  #{0} \"{1}&S\" (started by {2}, {3} left)",
                                       timer.Id, timer.Message, timer.StartedBy, timer.TimeLeft.ToMiniString());
                    }
                }
                return;
            }

            // Abort a timer
            if (param.Equals("abort", StringComparison.OrdinalIgnoreCase))
            {
                int timerId;
                if (cmd.NextInt(out timerId))
                {
                    ChatTimer timer = ChatTimer.FindTimerById(timerId);
                    if (timer == null || !timer.IsRunning)
                    {
                        player.Message("Given timer (#{0}) does not exist.", timerId);
                    }
                    else
                    {
                        timer.Stop();
                        string abortMsg = String.Format("&Y(Timer) {0}&Y aborted a timer with {1} left: {2}",
                                                        player.ClassyName, timer.TimeLeft.ToMiniString(), timer.Message);
                        Chat.SendSay(player, abortMsg);
                    }
                }
                else
                {
                    CdTimer.PrintUsage(player);
                }
                return;
            }

            // Start a timer
            if (player.Info.IsMuted)
            {
                player.MessageMuted();
                return;
            }
            if (player.DetectChatSpam())
            {
                return;
            }
            TimeSpan duration;

            if (!param.TryParseMiniTimespan(out duration))
            {
                CdTimer.PrintUsage(player);
                return;
            }
            if (duration > DateTimeUtil.MaxTimeSpan)
            {
                player.MessageMaxTimeSpan();
                return;
            }
            if (duration < ChatTimer.MinDuration)
            {
                player.Message("Timer: Must be at least 1 second.");
                return;
            }

            string sayMessage;
            string message = cmd.NextAll();

            if (String.IsNullOrEmpty(message))
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer",
                                           player.ClassyName,
                                           duration.ToMiniString());
            }
            else
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer: {2}",
                                           player.ClassyName,
                                           duration.ToMiniString(),
                                           message);
            }
            Chat.SendSay(player, sayMessage);
            ChatTimer.Start(duration, message, player.Name);
        }
 private static void WhoIsHandler(Player player, Command cmd)
 {
     string Name = cmd.Next();
     if (string.IsNullOrEmpty(Name))
     {
         CdWhoIs.PrintUsage(player);
         return;
     }
     Name = Color.StripColors(Name.ToLower());
     PlayerInfo[] Names = PlayerDB.PlayerInfoList.Where(p => p.DisplayedName != null &&
         Color.StripColors(p.DisplayedName.ToLower()).Contains(Name))
                                  .ToArray();
     Array.Sort(Names, new PlayerInfoComparer(player));
     if (Names.Length < 1)
     {
         player.Message("&WNo results found with that DisplayedName");
         return;
     }
     if (Names.Length == 1)
     {
         player.Message("One player found with that DisplayedName: {0}", Names[0].Rank.Color + Names[0].Name);
         return;
     }
     if (Names.Length <= 15)
     {
         MessageManyMatches(player, Names);
     }
     else
     {
         int offset;
         if (!cmd.NextInt(out offset)) offset = 0;
         if (offset >= Names.Length)
             offset = Math.Max(0, Names.Length - 15);
         PlayerInfo[] Part = Names.Skip(offset).Take(15).ToArray();
         MessageManyMatches(player, Part);
         if (offset + Part.Length < Names.Length)
         {
             player.Message("Showing {0}-{1} (out of {2}). Next: &H/Whois {3} {4}",
                             offset + 1, offset + Part.Length, Names.Length,
                             Name, offset + Part.Length);
         }
         else
         {
             player.Message("Showing matches {0}-{1} (out of {2}).",
                             offset + 1, offset + Part.Length, Names.Length);
         }
     }
 }
        static void TPHandler( Player player, Command cmd )
        {
            string name = cmd.Next();
            if( name == null ) {
                CdTP.PrintUsage( player );
                return;
            }

            if( cmd.Next() != null ) {
                cmd.Rewind();
                int x, y, z;
                if( cmd.NextInt( out x ) && cmd.NextInt( out y ) && cmd.NextInt( out z ) ) {

                    if( x <= -1024 || x >= 1024 || y <= -1024 || y >= 1024 || z <= -1024 || z >= 1024 ) {
                        player.Message( "Coordinates are outside the valid range!" );

                    } else {
                        player.previousLocation = player.Position;
                        player.previousWorld = null;
                        player.TeleportTo( new Position {
                            X = (short)(x * 32 + 16),
                            Y = (short)(y * 32 + 16),
                            Z = (short)(z * 32 + 16),
                            R = player.Position.R,
                            L = player.Position.L
                        } );
                    }
                } else {
                    CdTP.PrintUsage( player );
                }

            } else {
                if( name == "-" ) {
                    if( player.LastUsedPlayerName != null ) {
                        name = player.LastUsedPlayerName;
                    } else {
                        player.Message( "Cannot repeat player name: you haven't used any names yet." );
                        return;
                    }
                }
                Player[] matches = Server.FindPlayers( player, name, true );
                if( matches.Length == 1 ) {
                    Player target = matches[0];
                    World targetWorld = target.World;
                    if( targetWorld == null ) PlayerOpException.ThrowNoWorld( target );

                    if( targetWorld == player.World ) {
                        player.previousLocation = player.Position;
                        player.previousWorld = null;
                        player.TeleportTo( target.Position );

                    } else {
                        switch( targetWorld.AccessSecurity.CheckDetailed( player.Info ) ) {
                            case SecurityCheckResult.Allowed:
                            case SecurityCheckResult.WhiteListed:
                                if( targetWorld.IsFull ) {
                                    player.Message( "Cannot teleport to {0}&S because world {1}&S is full.",
                                                    target.ClassyName,
                                                    targetWorld.ClassyName );
                                    return;
                                }
                                player.StopSpectating();
                                player.previousLocation = player.Position;
                                player.previousWorld = player.World;
                                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.ClassyName,
                                                targetWorld.ClassyName );
                                break;
                            case SecurityCheckResult.RankTooLow:
                                player.Message( "Cannot teleport to {0}&S because world {1}&S requires {2}+&S to join.",
                                                target.ClassyName,
                                                targetWorld.ClassyName,
                                                targetWorld.AccessSecurity.MinRank.ClassyName );
                                break;
                            // TODO: case PermissionType.RankTooHigh:
                        }
                    }

                } else if( matches.Length > 1 ) {
                    player.MessageManyMatches( "player", matches );

                } else {
                    // Try to guess if player typed "/TP" instead of "/Join"
                    World[] worlds = WorldManager.FindWorlds( player, name );

                    if( worlds.Length == 1 ) {
                        player.LastUsedWorldName = worlds[0].Name;
                        player.StopSpectating();
                        player.ParseMessage( "/Join " + worlds[0].Name, false, true );
                    } else {
                        player.MessageNoPlayer( name );
                    }
                }
            }
        }
        internal static void ListHandler(Player player, Command cmd)
        {
            string Option = cmd.Next();
            if (Option == null)
            {
                CdList.PrintUsage(player);
                player.Message("  Sections include: Staff, DisplayedNames, Idles, Portals, Rank, Top10");
                return;
            }
            switch (Option.ToLower())
            {
                default:
                    CdList.PrintUsage(player);
                    player.Message("  Sections include: Staff, DisplayedNames, Idles, Portals, Rank, Top10");
                    break;
                case "top10":
                    List<World> WorldNames = new List<World>(WorldManager.Worlds.Where(w => w.VisitCount > 0)
                                         .OrderBy(c => c.VisitCount)
                                         .ToArray()
                                         .Reverse());
                    string list = WorldNames.Take(10).JoinToString(w => String.Format("{0}&S: {1}", w.ClassyName, w.VisitCount));
                    if (WorldNames.Count() < 1){
                        player.Message("&WNo results found");
                        return;
                    }
                    player.Message("&WShowing worlds with the most visits: " + list);
                    WorldNames.Clear();
                    break;
                case "idles":
                case "idle":
                    var Idles = Server.Players.Where(p => p.IdleTime.TotalMinutes > 5).ToArray();
                    var visiblePlayers = Idles.Where(player.CanSee);
                    if (Idles.Count() > 0)
                        player.Message("Listing players idle for 5 mins or more: {0}",
                                        visiblePlayers.JoinToString(r => String.Format("{0}", r.ClassyName)));
                    else player.Message("No players have been idle for more than 5 minutes");
                    break;
                case "portals":
                    if (player.World == null){
                        player.Message("/List portals cannot be used from Console");
                        return;
                    }
                    if (player.World.Portals == null ||
                        player.World.Portals.Count == 0){
                        player.Message("There are no portals in {0}&S.", player.World.ClassyName);
                    }
                    else
                    {
                        String[] portalNames = new String[player.World.Portals.Count];
                        StringBuilder output = new StringBuilder("There are " + player.World.Portals.Count + " portals in " + player.World.ClassyName + "&S: ");

                        for (int i = 0; i < player.World.Portals.Count; i++)
                        {
                            portalNames[i] = ((fCraft.Portals.Portal)player.World.Portals[i]).Name;
                        }
                        output.Append(portalNames.JoinToString(", "));
                        player.Message(output.ToString());
                    }
                    break;
                case "staff":
                    var StaffNames = PlayerDB.PlayerInfoList
                                         .Where(r => r.Rank.Can(Permission.ReadStaffChat) &&
                                             r.Rank.Can(Permission.Ban) &&
                                             r.Rank.Can(Permission.Promote))
                                             .OrderBy(p => p.Rank)
                                             .ToArray();
                    if (StaffNames.Length < 1){
                        player.Message("&WNo results found");
                        return;
                    }
                    if (StaffNames.Length <= PlayersPerPage){
                        player.MessageManyMatches("staff", StaffNames);
                    }else{
                        int offset;
                        if (!cmd.NextInt(out offset)) offset = 0;
                        if (offset >= StaffNames.Length)
                            offset = Math.Max(0, StaffNames.Length - PlayersPerPage);
                        PlayerInfo[] StaffPart = StaffNames.Skip(offset).Take(PlayersPerPage).ToArray();
                        player.MessageManyMatches("staff", StaffPart);
                        if (offset + StaffPart.Length < StaffNames.Length)
                            player.Message("Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + StaffPart.Length, StaffNames.Length,
                                            "staff", offset + StaffPart.Length);
                        else
                            player.Message("Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + StaffPart.Length, StaffNames.Length);
                    }
                    break;

                case "rank":
                    string rankName = cmd.Next();
                    if (rankName == null)
                    {
                        player.Message("Usage: /List rank rankName");
                        return;
                    }
                    Rank rank = RankManager.FindRank(rankName);
                    var RankNames = PlayerDB.PlayerInfoList
                                         .Where(r => r.Rank == rank)
                                             .ToArray();
                    if (RankNames.Length < 1){
                        player.Message("&WNo results found");
                        return;
                    }
                    if (RankNames.Length <= PlayersPerPage)
                    {
                        player.MessageManyMatches("players", RankNames);
                    }
                    else
                    {
                        int offset;
                        if (!cmd.NextInt(out offset)) offset = 0;
                        if (offset >= RankNames.Length)
                            offset = Math.Max(0, RankNames.Length - PlayersPerPage);
                        PlayerInfo[] RankPart = RankNames.Skip(offset).Take(PlayersPerPage).ToArray();
                        player.MessageManyMatches("rank list", RankPart);
                        if (offset + RankPart.Length < RankNames.Length)
                            player.Message("Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + RankPart.Length, RankNames.Length,
                                            "rank " + rank.ClassyName, offset + RankPart.Length);
                        else
                            player.Message("Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + RankPart.Length, RankNames.Length);
                    }
                    break;
                case "displayednames":
                case "displayedname":
                case "dn":
                    var DisplayedNames = PlayerDB.PlayerInfoList
                                             .Where(r => r.DisplayedName != null).OrderBy(p => p.Rank).ToArray();
                    if (DisplayedNames.Length < 1){
                        player.Message("&WNo results found");
                        return;
                    }
                    if (DisplayedNames.Length <= 15)
                    {
                        player.MessageManyDisplayedNamesMatches("DisplayedNames", DisplayedNames);
                    }
                    else
                    {
                        int offset;
                        if (!cmd.NextInt(out offset)) offset = 0;
                        if (offset >= DisplayedNames.Count())
                            offset = Math.Max(0, DisplayedNames.Length - 15);
                        PlayerInfo[] DnPart = DisplayedNames.Skip(offset).Take(15).ToArray();
                        player.MessageManyDisplayedNamesMatches("DisplayedNames", DnPart);
                        if (offset + DisplayedNames.Length < DisplayedNames.Length)
                            player.Message("Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                            offset + 1, offset + DnPart.Length, DisplayedNames.Length,
                                            "DisplayedNames", offset + DnPart.Length);
                        else
                            player.Message("Showing matches {0}-{1} (out of {2}).",
                                            offset + 1, offset + DnPart.Length, DisplayedNames.Length);
                    }
                    break;
            }
        }
Beispiel #24
0
        static void WorldSearchHandler(Player player, Command cmd)
        {
            string worldName = cmd.Next();
            if (worldName == null)
            {
                CdWorldSearch.PrintUsage(player);
                return;
            }
            if (worldName.Length < 2)
            {
                CdWorldSearch.PrintUsage(player);
                return;
            }
            else
            {
                worldName = worldName.ToLower();
                var WorldNames = WorldManager.Worlds
                                         .Where(w => w.Name.ToLower().Contains(worldName)).ToArray();

                if (WorldNames.Length <= 30)
                {
                    player.MessageManyMatches("worlds", WorldNames);
                }
                else
                {
                    int offset;
                    if (!cmd.NextInt(out offset)) offset = 0;

                    if (offset >= WorldNames.Count())
                        offset = Math.Max(0, WorldNames.Length - 30);

                    World[] WorldPart = WorldNames.Skip(offset).Take(30).ToArray();
                    player.MessageManyMatches("worlds", WorldPart);

                    if (offset + WorldNames.Length < WorldNames.Length)
                        player.Message("Showing {0}-{1} (out of {2}). Next: &H/List {3} {4}",
                                        offset + 1, offset + WorldPart.Length, WorldNames.Length,
                                        "worldsearch", offset + WorldPart.Length);
                    else
                        player.Message("Showing matches {0}-{1} (out of {2}).",
                                        offset + 1, offset + WorldPart.Length, WorldNames.Length);
                    return;
                }
            }
        }
Beispiel #25
0
 internal static void Roll( Player player, Command cmd )
 {
     Random rand = new Random();
     int min = 1, max = 100, num, t1, t2;
     if( cmd.NextInt( out t1 ) ) {
         if( cmd.NextInt( out t2 ) ) {
             if( t2 >= t1 ) {
                 min = t1;
                 max = t2;
             }
         } else if( t1 >= 1 ) {
             max = t1;
         }
     }
     num = rand.Next( min, max + 1 );
     string msg = Color.Silver + player.nick + " rolled " + num + " (" + min + "..." + max + ")";
     Logger.LogConsole( msg );
     Server.SendToAll( msg );
 }
Beispiel #26
0
        public static void BlockInfoHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;
            if (playerWorld == null) PlayerOpException.ThrowNoWorld(player);

            // Make sure BlockDB is usable
            if (!BlockDB.IsEnabledGlobally)
            {
                player.Message("&WBlockDB is disabled on this server.");
                return;
            }
            if (!playerWorld.BlockDB.IsEnabled)
            {
                player.Message("&WBlockDB is disabled in this world.");
                return;
            }

            int x, y, z;
            if (cmd.NextInt(out x) && cmd.NextInt(out y) && cmd.NextInt(out z))
            {
                // If block coordinates are given, run the BlockDB query right away
                if (cmd.HasNext)
                {
                    CdBlockInfo.PrintUsage(player);
                    return;
                }
                Vector3I coords = new Vector3I(x, y, z);
                Map map = player.WorldMap;
                coords.X = Math.Min(map.Width - 1, Math.Max(0, coords.X));
                coords.Y = Math.Min(map.Length - 1, Math.Max(0, coords.Y));
                coords.Z = Math.Min(map.Height - 1, Math.Max(0, coords.Z));
                BlockInfoSelectionCallback(player, new[] { coords }, null);

            }
            else
            {
                // Otherwise, start a selection
                player.Message("BInfo: Click a block to look it up.");
                player.SelectionStart(1, BlockInfoSelectionCallback, null, CdBlockInfo.Permissions);
            }
        }
Beispiel #27
0
        internal static void InfoHandler( Player player, Command cmd ) {
            string name = cmd.Next();
            if( name == null ) {
                // no name given, print own info
                PrintPlayerInfo( player, player.Info );
                return;

            } else if( name.Equals( player.Name, StringComparison.OrdinalIgnoreCase ) ) {
                // own name given
                player.LastUsedPlayerName = player.Name;
                PrintPlayerInfo( player, player.Info );
                return;

            } else if( !player.Can( Permission.ViewOthersInfo ) ) {
                // someone else's name or IP given, permission required.
                player.MessageNoAccess( Permission.ViewOthersInfo );
                return;
            }

            // repeat last-typed name
            if( name == "-" ) {
                if( player.LastUsedPlayerName != null ) {
                    name = player.LastUsedPlayerName;
                } else {
                    player.Message( "Cannot repeat player name: you haven't used any names yet." );
                    return;
                }
            }

            PlayerInfo[] infos;
            IPAddress ip;

            if( name.Contains( "/" ) ) {
                // IP range matching (CIDR notation)
                string ipString = name.Substring( 0, name.IndexOf( '/' ) );
                string rangeString = name.Substring( name.IndexOf( '/' ) + 1 );
                byte range;
                if( Server.IsIP( ipString ) && IPAddress.TryParse( ipString, out ip ) &&
                    Byte.TryParse( rangeString, out range ) && range <= 32 ) {
                    player.Message( "Searching {0}-{1}", ip.RangeMin( range ), ip.RangeMax( range ) );
                    infos = PlayerDB.FindPlayersCidr( ip, range );
                } else {
                    player.Message( "Info: Invalid IP range format. Use CIDR notation." );
                    return;
                }

            } else if( Server.IsIP( name ) && IPAddress.TryParse( name, out ip ) ) {
                // find players by IP
                infos = PlayerDB.FindPlayers( ip );

            } else if( name.Contains( "*" ) || name.Contains( "?" ) ) {
                // find players by regex/wildcard
                string regexString = "^" + RegexNonNameChars.Replace( name, "" ).Replace( "*", ".*" ).Replace( "?", "." ) + "$";
                Regex regex = new Regex( regexString, RegexOptions.IgnoreCase | RegexOptions.Compiled );
                infos = PlayerDB.FindPlayers( regex );

            } else {
                // find players by partial matching
                PlayerInfo tempInfo;
                if( !PlayerDB.FindPlayerInfo( name, out tempInfo ) ) {
                    infos = PlayerDB.FindPlayers( name );
                } else if( tempInfo == null ) {
                    player.MessageNoPlayer( name );
                    return;
                } else {
                    infos = new[] { tempInfo };
                }
            }

            Array.Sort( infos, new PlayerInfoComparer( player ) );

            if( infos.Length == 1 ) {
                // only one match found; print it right away
                player.LastUsedPlayerName = infos[0].Name;
                PrintPlayerInfo( player, infos[0] );

            } else if( infos.Length > 1 ) {
                // multiple matches found
                if( infos.Length <= PlayersPerPage ) {
                    // all fit to one page
                    player.MessageManyMatches( "player", infos );

                } else {
                    // pagination
                    int offset;
                    if( !cmd.NextInt( out offset ) ) offset = 0;
                    if( offset >= infos.Length ) {
                        offset = Math.Max( 0, infos.Length - PlayersPerPage );
                    }
                    PlayerInfo[] infosPart = infos.Skip( offset ).Take( PlayersPerPage ).ToArray();
                    player.MessageManyMatches( "player", infosPart );
                    if( offset + infosPart.Length < infos.Length ) {
                        // normal page
                        player.Message( "Showing {0}-{1} (out of {2}). Next: &H/Info {3} {4}",
                                        offset + 1, offset + infosPart.Length, infos.Length,
                                        name, offset + infosPart.Length );
                    } else {
                        // last page
                        player.Message( "Showing matches {0}-{1} (out of {2}).",
                                        offset + 1, offset + infosPart.Length, infos.Length );
                    }
                }

            } else {
                // no matches found
                player.MessageNoPlayer( name );
            }
        }
Beispiel #28
0
        static void RollHandler( Player player, Command cmd ) {
            if( player.Info.IsMuted ) {
                player.MessageMuted();
                return;
            }

            if( player.DetectChatSpam() ) return;

            Random rand = new Random();
            int n1;
            int min, max;
            if( cmd.NextInt( out n1 ) ) {
                int n2;
                if( !cmd.NextInt( out n2 ) ) {
                    n2 = 1;
                }
                min = Math.Min( n1, n2 );
                max = Math.Max( n1, n2 );
            } else {
                min = 1;
                max = 100;
            }

            int num = rand.Next( min, max + 1 );
            Server.Message( player,
                            "{0}{1} rolled {2} ({3}...{4})",
                            player.ClassyName, Color.Silver, num, min, max );
            player.Message( "{0}You rolled {1} ({2}...{3})",
                            Color.Silver, num, min, max );
        }
Beispiel #29
0
        internal static void Rotate( Player player, Command cmd ) {
            if( player.CopyInformation == null ) {
                player.MessageNow( "Nothing to rotate! Copy something first." );
                return;
            }

            int degrees;
            if( !cmd.NextInt( out degrees ) || (degrees != 90 && degrees != -90 && degrees != 180 && degrees != 270) ) {
                cdRotate.PrintUsage( player );
                return;
            }

            string axisName = cmd.Next();
            RotationAxis axis = RotationAxis.Z;
            if( axisName != null ) {
                switch( axisName.ToLower() ) {
                    case "x":
                        axis = RotationAxis.X;
                        break;
                    case "y":
                        axis = RotationAxis.Y;
                        break;
                    case "z":
                    case "h":
                        axis = RotationAxis.Z;
                        break;
                    default:
                        cdRotate.PrintUsage( player );
                        return;
                }
            }


            // allocate the new buffer
            byte[, ,] oldBuffer = player.CopyInformation.Buffer;
            byte[, ,] newBuffer;

            if( degrees == 180 ) {
                newBuffer = new byte[oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 2 )];

            } else if( axis == RotationAxis.X ) {
                newBuffer = new byte[oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 2 ), oldBuffer.GetLength( 1 )];
                int dimY = player.CopyInformation.WidthY;
                player.CopyInformation.WidthY = player.CopyInformation.Height;
                player.CopyInformation.Height = dimY;

            } else if( axis == RotationAxis.Y ) {
                newBuffer = new byte[oldBuffer.GetLength( 2 ), oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 0 )];
                int dimX = player.CopyInformation.WidthX;
                player.CopyInformation.WidthX = player.CopyInformation.Height;
                player.CopyInformation.Height = dimX;

            } else {
                newBuffer = new byte[oldBuffer.GetLength( 1 ), oldBuffer.GetLength( 0 ), oldBuffer.GetLength( 2 )];
                int dimY = player.CopyInformation.WidthY;
                player.CopyInformation.WidthY = player.CopyInformation.WidthX;
                player.CopyInformation.WidthX = dimY;
            }


            // construct the rotation matrix
            int[,] matrix = new[,]{
                {1,0,0},
                {0,1,0},
                {0,0,1}
            };

            int a, b;
            switch( axis ) {
                case RotationAxis.X:
                    a = 1;
                    b = 2;
                    break;
                case RotationAxis.Y:
                    a = 0;
                    b = 2;
                    break;
                default:
                    a = 0;
                    b = 1;
                    break;
            }

            switch( degrees ) {
                case 90:
                    matrix[a, a] = 0;
                    matrix[b, b] = 0;
                    matrix[a, b] = -1;
                    matrix[b, a] = 1;
                    break;
                case 180:
                    matrix[a, a] = -1;
                    matrix[b, b] = -1;
                    break;
                case -90:
                case 270:
                    matrix[a, a] = 0;
                    matrix[b, b] = 0;
                    matrix[a, b] = 1;
                    matrix[b, a] = -1;
                    break;
            }

            // apply the rotation matrix
            int nx, ny, nz;
            for( int x = oldBuffer.GetLength( 0 ) - 1; x >= 0; x-- ) {
                for( int y = oldBuffer.GetLength( 1 ) - 1; y >= 0; y-- ) {
                    for( int z = oldBuffer.GetLength( 2 ) - 1; z >= 0; z-- ) {
                        nx = (matrix[0, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[0, 0] > 0 ? x : 0)) +
                             (matrix[0, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[0, 1] > 0 ? y : 0)) +
                             (matrix[0, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[0, 2] > 0 ? z : 0));
                        ny = (matrix[1, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[1, 0] > 0 ? x : 0)) +
                             (matrix[1, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[1, 1] > 0 ? y : 0)) +
                             (matrix[1, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[1, 2] > 0 ? z : 0));
                        nz = (matrix[2, 0] < 0 ? oldBuffer.GetLength( 0 ) - 1 - x : (matrix[2, 0] > 0 ? x : 0)) +
                             (matrix[2, 1] < 0 ? oldBuffer.GetLength( 1 ) - 1 - y : (matrix[2, 1] > 0 ? y : 0)) +
                             (matrix[2, 2] < 0 ? oldBuffer.GetLength( 2 ) - 1 - z : (matrix[2, 2] > 0 ? z : 0));
                        newBuffer[nx, ny, nz] = oldBuffer[x, y, z];
                    }
                }
            }

            player.Message( "Rotated copy by {0} degrees around {1} axis.", degrees, axis );
            player.CopyInformation.Buffer = newBuffer;
        }
        static void MarkHandler( Player player, Command cmd )
        {
            Map map = player.WorldMap;
            int x, y, z;
            Vector3I coords;
            if( cmd.NextInt( out x ) && cmd.NextInt( out y ) && cmd.NextInt( out z ) ) {
                if( cmd.HasNext ) {
                    CdMark.PrintUsage( player );
                    return;
                }
                coords = new Vector3I( x, y, z );
            } else {
                coords = player.Position.ToBlockCoords();
            }
            coords.X = Math.Min( map.Width - 1, Math.Max( 0, coords.X ) );
            coords.Y = Math.Min( map.Length - 1, Math.Max( 0, coords.Y ) );
            coords.Z = Math.Min( map.Height - 1, Math.Max( 0, coords.Z ) );

            if( player.SelectionMarksExpected > 0 ) {
                player.SelectionAddMark( coords, true );
            } else {
                player.MessageNow( "Cannot mark - no selection in progress." );
            }
        }
Beispiel #31
0
        public static void RealmCreate(Player player, Command cmd, string themeName, string templateName)
        {
            MapGenTemplate template;
            MapGenTheme theme;

            int wx, wy, height = 128;
            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                if (player.World != null)
                {
                    wx = 128;
                    wy = 128;
                    height = 128;
                }
                else
                {
                    player.Message("When used from console, /gen requires map dimensions.");

                    return;
                }
                cmd.Rewind();
                cmd.Next();
                cmd.Next();
            }

            if (!Map.IsValidDimension(wx))
            {
                player.Message("Cannot make map with width {0}: dimensions must be multiples of 16.", wx);
                return;
            }
            else if (!Map.IsValidDimension(wy))
            {
                player.Message("Cannot make map with length {0}: dimensions must be multiples of 16.", wy);
                return;
            }
            else if (!Map.IsValidDimension(height))
            {
                player.Message("Cannot make map with height {0}: dimensions must be multiples of 16.", height);
                return;
            }

            string fileName = player.Name;
            string fullFileName = null;

            if (fileName == null)
            {
                if (player.World == null)
                {
                    player.Message("When used from console, /gen requires FileName.");

                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace this realm's map with a generated one?");
                    return;
                }
            }
            else
            {
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.IsValidPath(fullFileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            bool noTrees;
            if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
            {
                theme = MapGenTheme.Forest;
                noTrees = true;
            }
            else
            {
                try
                {
                    theme = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), themeName, true);
                    noTrees = (theme != MapGenTheme.Forest);
                }
                catch (Exception)
                {
                    player.MessageNow("Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                       themeName,
                                       String.Join(", ", Enum.GetNames(typeof(MapGenTheme))));
                    return;
                }
            }

            try
            {
                template = (MapGenTemplate)Enum.Parse(typeof(MapGenTemplate), templateName, true);
            }
            catch (Exception)
            {
                player.Message("Unrecognized template \"{0}\". Available templates are: {1}",
                                templateName,
                                String.Join(", ", Enum.GetNames(typeof(MapGenTemplate))));
                return;
            }

            if (!Enum.IsDefined(typeof(MapGenTheme), theme) || !Enum.IsDefined(typeof(MapGenTemplate), template))
            {

                return;
            }

            MapGeneratorArgs args = MapGenerator.MakeTemplate(template);
            args.MapWidth = wx;
            args.MapLength = wy;
            args.MapHeight = height;
            args.MaxHeight = (int)(args.MaxHeight / 80d * height);
            args.MaxDepth = (int)(args.MaxDepth / 80d * height);
            args.Theme = theme;
            args.AddTrees = !noTrees;

            Map map;
            try
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    player.MessageNow("Generating Grass {0}...", template);
                }
                else
                {
                    player.MessageNow("Generating {0} {1}...", theme, template);
                }
                if (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat)
                {
                    map = MapGenerator.GenerateFlatgrass(args.MapWidth, args.MapLength, args.MapHeight);
                }
                else
                {
                    MapGenerator generator = new MapGenerator(args);
                    map = generator.Generate();
                }

            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "MapGenerator: Generation failed: {0}",
                            ex);
                player.MessageNow("&WAn error occured while generating the map.");
                return;
            }

            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.MessageNow("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                player.MessageNow("Generation done. Changing map...");
                player.World.ChangeMap(map);
            }
        }
        static void TreeHandler(Player player, Command cmd)
        {
            string shapeName = cmd.Next();
            int height;
            Forester.TreeShape shape;

            // that's one ugly if statement... does the job though.
            if (shapeName == null ||
                !cmd.NextInt(out height) ||
                !EnumUtil.TryParse(shapeName, out shape, true) ||
                shape == Forester.TreeShape.Stickly ||
                shape == Forester.TreeShape.Procedural)
            {
                CdTree.PrintUsage(player);
                player.Message("Available shapes: Normal, Bamboo, Palm, Cone, Round, Rainforest, Mangrove.");
                return;
            }

            if (height < 6 || height > 1024)
            {
                player.Message("Tree height must be 6 blocks or above");
                return;
            }

            Map map = player.World.Map;

            ForesterArgs args = new ForesterArgs
            {
                Height = height - 1,
                Operation = Forester.ForesterOperation.Add,
                Map = map,
                Shape = shape,
                TreeCount = 1,
                RootButtresses = false,
                Roots = Forester.RootMode.None,
                Rand = new Random()
            };
            player.SelectionStart(1, TreeCallback, args, CdTree.Permissions);
            player.MessageNow("Tree: Place a block or type /Mark to use your location.");
        }
Beispiel #33
0
        internal static void Mark( Player player, Command command ) {
            int x, y, h;
            Position pos;
            if( command.NextInt( out x ) && command.NextInt( out y ) && command.NextInt( out h ) ) {
                pos = new Position( x, y, h );
            } else {
                pos = new Position( (player.Position.X - 1) / 32,
                                    (player.Position.Y - 1) / 32,
                                    (player.Position.H - 1) / 32 );
            }
            pos.X = (short)Math.Min( player.World.Map.WidthX - 1, Math.Max( 0, (int)pos.X ) );
            pos.Y = (short)Math.Min( player.World.Map.WidthY - 1, Math.Max( 0, (int)pos.Y ) );
            pos.H = (short)Math.Min( player.World.Map.Height - 1, Math.Max( 0, (int)pos.H ) );

            if( player.SelectionMarksExpected > 0 ) {
                player.AddSelectionMark( pos, true );
            } else {
                player.MessageNow( "Cannot mark - no draw or zone commands initiated." );
            }
        }
Beispiel #34
0
 internal static void TP( Player player, Command cmd )
 {
     if( player.Can( Permissions.Teleport ) ) {
         string name = cmd.Next();
         if( name == null ) {
             player.Send( PacketWriter.MakeTeleport( 255, player.world.map.spawn ) );
         } else {
             Player target = player.world.FindPlayer( name );
             if( target != null ) {
                 Position pos = target.pos;
                 pos.x += 1;
                 pos.y += 1;
                 pos.h += 1;
                 player.Send( PacketWriter.MakeTeleport( 255, pos ) );
             } else if( cmd.Next() == null ) {
                 player.NoPlayerMessage( name );
             } else {
                 cmd.Rewind();
                 int x, y, h;
                 if( cmd.NextInt( out x ) && cmd.NextInt( out y ) && cmd.NextInt( out h ) ) {
                     if( x < 0 || x > player.world.map.widthX ||
                          y < 0 || y > player.world.map.widthY ||
                          y < 0 || y > player.world.map.height ) {
                         player.Message( "Specified coordinates are outside the map!" );
                     } else {
                         player.pos.Set( x * 32 + 16, y * 32 + 16, h * 32 + 16, player.pos.r, player.pos.l );
                         player.Send( PacketWriter.MakeTeleport( 255, player.pos ) );
                     }
                 } else {
                     player.Message( "See " + Color.Help + "/help tp" + Color.Sys + " for information on using /tp" );
                 }
             }
         }
     } else {
         player.NoAccessMessage( Permissions.Teleport );
     }
 }
Beispiel #35
0
        void GenerateHollow( Player player, Command cmd ) {
            if( !player.Can( Permissions.SaveAndLoad ) ) {
                world.NoAccessMessage( player );
                return;
            }
            int wx, wy, height;
            if( !(cmd.NextInt( out wx ) && cmd.NextInt( out wy ) && cmd.NextInt( out height )) ) {
                player.Message( "Usage: " + Color.Help + "/genh widthX widthY height type filename" );
                return;
            }
            string mode = cmd.Next();
            string filename = cmd.Next();
            if( mode == null || filename == null ) {
                player.Message( "Usage: " + Color.Help + "/genh widthX widthY height type filename" );
                return;
            }
            filename += ".fcm";

            int seed;
            if( !cmd.NextInt( out seed ) ) {
                seed = new Random().Next();
            }
            Random rand = new Random( seed );
            player.Message( "Seed: " + Convert.ToBase64String( BitConverter.GetBytes( seed ) ) );

            Map map = new Map( world, wx, wy, height );
            map.spawn.Set( map.widthX / 2 * 32 + 16, map.widthY / 2 * 32 + 16, map.height * 32, 0, 0 );

            DoGenerate( map, player, mode, filename, rand, true );
        }
Beispiel #36
0
        internal static void PlayersHandler( Player player, Command cmd ) {
            string param = cmd.Next();
            Player[] players;
            string worldName = null;
            string qualifier;
            int offset = 0;

            if( param == null || Int32.TryParse( param, out offset ) ) {
                // No world name given; Start with a list of all players.
                players = Server.Players;
                qualifier = "online";
                if( cmd.HasNext ) {
                    CdPlayers.PrintUsage( player );
                    return;
                }

            } else {
                // Try to find the world
                World world = WorldManager.FindWorldOrPrintMatches( player, param );
                if( world == null ) return;

                worldName = param;
                // If found, grab its player list
                players = world.Players;
                qualifier = String.Format( "in world {0}&S", world.ClassyName );

                if( cmd.HasNext && !cmd.NextInt( out offset ) ) {
                    CdPlayers.PrintUsage( player );
                    return;
                }
            }

            if( players.Length > 0 ) {
                // Filter out hidden players, and sort
                Player[] visiblePlayers = players.Where( player.CanSee )
                                                 .OrderBy( p => p, PlayerListSorter.Instance )
                                                 .ToArray();


                if( visiblePlayers.Length == 0 ) {
                    player.Message( "There are no players {0}", qualifier );

                } else if( visiblePlayers.Length <= PlayersPerPage || player.IsSuper ) {
                    player.MessagePrefixed( "&S  ", "&SThere are {0} players {1}: {2}",
                                            visiblePlayers.Length, qualifier, visiblePlayers.JoinToClassyString() );

                } else {
                    if( offset >= visiblePlayers.Length ) {
                        offset = Math.Max( 0, visiblePlayers.Length - PlayersPerPage );
                    }
                    Player[] playersPart = visiblePlayers.Skip( offset ).Take( PlayersPerPage ).ToArray();
                    player.MessagePrefixed( "&S   ", "&SPlayers {0}: {1}",
                                            qualifier, playersPart.JoinToClassyString() );

                    if( offset + playersPart.Length < visiblePlayers.Length ) {
                        player.Message( "Showing {0}-{1} (out of {2}). Next: &H/Players {3}{1}",
                                        offset + 1, offset + playersPart.Length,
                                        visiblePlayers.Length,
                                        (worldName == null ? "" : worldName + " ") );
                    } else {
                        player.Message( "Showing players {0}-{1} (out of {2}).",
                                        offset + 1, offset + playersPart.Length,
                                        visiblePlayers.Length );
                    }
                }
            } else {
                player.Message( "There are no players {0}", qualifier );
            }
        }
Beispiel #37
0
        static void FeedHandler( Player player, Command cmd )
        {
            string Option = cmd.Next();
            if ( Option == null ) {
                player.Message( "Argument cannot be null, try /Feed <create | remove | list>" );
                return;
            }

            if ( Option.ToLower() == "create" ) {
                player.Message( "Feed: Click 2 blocks or use &H/Mark&S to set direction." );
                player.SelectionStart( 2, FeedCallback, Option, Permission.Draw );
                return;
            }
            if ( Option.ToLower() == "list" ) {
                FeedData[] list = player.World.Feeds.Values.OrderBy( feed => feed.Id ).ToArray();
                if ( list.Length == 0 ) {
                    player.Message( "No feeds running." );
                } else {
                    player.Message( "There are {0} feeds running:", list.Length );
                    foreach ( FeedData data in list ) {
                        player.Message( "  #{0} ({1},{2},{3}) World: {4}",
                                        data.Id, data.StartPos.X, data.StartPos.Y, data.StartPos.Z, data.world.ClassyName );
                    }
                }
                return;
            }

            if ( Option.ToLower() == "remove" || Option.ToLower() == "stop" ) {
                int Id;
                if ( cmd.NextInt( out Id ) ) {
                    FeedData data = FeedData.FindFeedById( Id, player.World );
                    if ( data == null ) {
                        player.Message( "Given feed (#{0}) does not exist.", Id );
                    } else {
                        data.started = false;
                        FeedData.RemoveFeedFromList( data, player.World );
                        player.Message( "Feed #" + Id + " has been removed" );
                    }
                } else {
                    player.Message( "&WUnable to remove any feeds. Try /Feed remove <ID>" );
                }
                return;
            } else {
                player.Message( "&WUnknown argument. Check /Help Feed" );
                return;
            }
        }