示例#1
0
文件: Team.cs 项目: Deeplerg/OpenAPI
 public virtual void Leave(OpenPlayer player)
 {
     if (Members.TryRemove(player.GetIdentifier(), out _))
     {
         player.SetTeam(null);
     }
 }
示例#2
0
        public bool TryAssignTeam(OpenPlayer player)
        {
            switch (Config.FillMode)
            {
            case TeamFillMode.Fill:
            {
                return(TryAssign(player, TeamFillMode.Fill));
            }

            case TeamFillMode.Spread:
            {
                return(TryAssign(player, TeamFillMode.Spread));
            }

            case TeamFillMode.FillMinSpread:
            {
                if (!TryAssign(player, TeamFillMode.FillMinSpread))
                {
                    return(TryAssign(player, TeamFillMode.Spread));
                }

                return(true);
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#3
0
        public Target FillTargets(OpenPlayer commander, OpenLevel level, string source)
        {
            Target target = ParseTarget(source);

            if (target.Selector == "closestPlayer" && target.Rules == null)
            {
                target.Players = new[] { commander };
            }
            else if (target.Selector == "closestPlayer" && target.Rules != null)
            {
                string username = target.Rules.First().Value;
                var    players  = level.GetAllPlayers().Where(p => p.Username == username);
                target.Players = players.ToArray();
            }
            else if (target.Selector == "allPlayers")
            {
                target.Players = level.GetAllPlayers();
            }
            else if (target.Selector == "allEntities")
            {
                target.Entities = level.GetEntites();
            }
            else if (target.Selector == "randomPlayer")
            {
                MiNET.Player[] players = level.GetAllPlayers();
                target.Players = new[] { players[new Random().Next(players.Length)] };
            }


            return(target);
        }
示例#4
0
        private static void RevertBlockAction(OpenPlayer player, Block block, BlockEntity blockEntity)
        {
            var message = McpeUpdateBlock.CreateObject();

            message.blockRuntimeId = (uint)block.GetRuntimeId();
            message.coordinates    = block.Coordinates;
            message.blockPriority  = 0xb;
            player.SendPacket(message);

            // Revert block entity if exists
            if (blockEntity != null)
            {
                Nbt nbt = new Nbt
                {
                    NbtFile = new NbtFile
                    {
                        BigEndian = false,
                        RootTag   = blockEntity.GetCompound()
                    }
                };

                var entityData = McpeBlockEntityData.CreateObject();
                entityData.namedtag    = nbt;
                entityData.coordinates = blockEntity.Coordinates;

                player.SendPacket(entityData);
            }
        }
 public PlayerInteractEvent(OpenPlayer player, Item item, BlockCoordinates coordinates, BlockFace face,
                            PlayerInteractType type) : base(player)
 {
     Item         = item;
     Coordinates  = coordinates;
     Face         = face;
     InteractType = type;
 }
示例#6
0
        internal object HandleCommand(OpenPlayer player, string cmdline)
        {
            var    split       = Regex.Split(cmdline, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)").Select(s => s.Trim('"')).ToArray();
            string commandName = split[0].Trim('/');

            string[] arguments = split.Skip(1).ToArray();

            Command command = null;

            command = GetCommand(player.Commands, commandName);

            //if (arguments.Length > 0 && command == null)
            //{
            //	commandName = commandName + " " + arguments[0];
            //	arguments = arguments.Skip(1).ToArray();
            //	command = GetCommand(commandName);
            //}

            if (command == null)
            {
                Log.Warn($"Found no command {commandName}");
                return(null);
            }

            foreach (var overload in command.Versions.First().Overloads.Values.OrderByDescending(o => o.Input.Parameters?.Length ?? 0))
            {
                var args = arguments;
                if (args.Length > 0 && overload.Input.Parameters?.FirstOrDefault(p => p.Name.Equals("subcommand")) != null)
                {
                    string subCommand = args[0];
                    if (overload.Input.Parameters.FirstOrDefault(p => p.Name.Equals("subcommand") && p.EnumValues[0] == subCommand) == null)
                    {
                        continue;
                    }
                    args = args.Skip(1).ToArray();
                }

                // TODO: Do we need the authorize attribute with the new permission system?
                int requiredPermission = command.Versions.First().CommandPermission;
                if (player.CommandPermission < requiredPermission)
                {
                    Log.Debug($"Insufficient permissions. Require {requiredPermission} but player had {player.CommandPermission}");
                    return(string.Format(command.Versions.First().ErrorMessage, player.CommandPermission.ToString().ToLowerInvariant(), requiredPermission.ToString().ToLowerInvariant()));
                }

                MethodInfo method = overload.Method;

                if (ExecuteCommand(method, player, args, out object retVal))
                {
                    return(retVal);
                }

                Log.Debug("No result from execution");
            }

            return(null);
        }
示例#7
0
        public FactionsPermissions GetPlayerPermission(OpenPlayer player)
        {
            if (!PlayerFactionPermissions.ContainsKey(player))
            {
                return(FactionsPermissions.None);
            }

            return(PlayerFactionPermissions[player]);
        }
示例#8
0
        public void Sound2(OpenPlayer player, LevelSoundEventType sound)
        {
            //player.Level.MakeSound(new DoorCloseSound(player.KnownPosition));

            player.Level.BroadcastSound(player.KnownPosition.GetCoordinates3D(), sound);

            //  player.SendSound(player.KnownPosition.GetCoordinates3D(), LevelSoundEventType.Explode);
            player.SendMessage("Sound send.");
        }
示例#9
0
        public static string GetIdentifier(this OpenPlayer player)
        {
            if (player.IsXbox)
            {
                return(player.CertificateData.ExtraData.Xuid);
            }

            return(player.ClientUuid.ToString());
        }
示例#10
0
 public FoodLevelChangeEvent(OpenPlayer player, int oldLevel, int newLevel, double oldExhaustion, double newExhaustion, double oldSaturation, double newSaturation) : base(player)
 {
     OldLevel      = oldLevel;
     NewLevel      = newLevel;
     OldSaturation = oldSaturation;
     NewSaturation = newSaturation;
     OldExhaustion = oldExhaustion;
     NewExhaustion = newExhaustion;
 }
示例#11
0
        public void Give(OpenPlayer player, string name, int amount = 1)
        {
            if (amount < 1)
            {
                return;
            }
            var item = ItemFactory.GetItem(name, 0, amount);

            player.Inventory.AddItem(item, true);
            player.SendMessage($"You received {name} * {amount}");
        }
示例#12
0
        public void Give(OpenPlayer player, int id, int amount = 1)
        {
            if (amount < 1)
            {
                return;
            }
            var item = ItemFactory.GetItem((short)id, 0, amount);

            player.Inventory.AddItem(item, true);
            player.SendMessage($"You received {item.ToString()} * {amount}");
        }
示例#13
0
        public void Broadcast(OpenPlayer source, OpenApi api, params string[] message)
        {
            string msg = String.Join(" ", message);

            foreach (var lvl in api.LevelManager.GetLevels)
            {
                lvl.BroadcastMessage(msg, MessageType.Chat, source);
            }

            source.SendMessage($"We tried broadcasting: {msg}");
        }
示例#14
0
        public void ModMe(OpenPlayer player)
        {
            PermissionGroup permissionGroup = new PermissionGroup("testperms");

            permissionGroup.SetPermission("testperms.mod", true);

            player.Permissions.AddPermissionGroup(permissionGroup);
            player.RefreshCommands();

            player.SendMessage($"You are a mod now!");
        }
示例#15
0
        public void About(OpenPlayer player, string pluginName)
        {
            var plugin = Api.PluginManager.GetLoadedPlugins().First(pl => pl.Info.Name.ToLower() == pluginName.ToLower());

            if (plugin is null)
            {
                player.SendMessage("This plugin doesn't exist!");
                return;
            }
            player.SendMessage($"§a{plugin.Info.Name} §e<{plugin.Info.Version}> §fMade By §3{plugin.Info.Author}");
        }
示例#16
0
        public void Plugins(OpenPlayer player)
        {
            var plugins = Api.PluginManager.GetLoadedPlugins();
            var result  = $"Plugins({plugins.Length}): ";

            foreach (LoadedPlugin plugin in plugins)
            {
                result += $"{(plugin.Enabled ? "§a" : "§c")}{plugin.Info.Name} §ev{plugin.Info.Version}§f, ";
            }
            player.SendMessage(result);
        }
示例#17
0
 public void Destroy(OpenPlayer player, string levelname)
 {
     if (Plugin.MultiVerseManager.Destroy(levelname))
     {
         player.SendPluginMessage($"The MultiVerse \"{levelname}\" has been destroyed!");
     }
     else
     {
         player.SendPluginMessage($"Could not find a MultiVerse with the name: {levelname}");
     }
 }
示例#18
0
        public void Leave(OpenPlayer player)
        {
            if (player.Level is MultiVerseLevel mvl)
            {
                var lvl = Plugin.Api.LevelManager.GetDefaultLevel();

                player.SpawnLevel(lvl, lvl.SpawnPoint, true);
                return;
            }

            player.SendPluginMessage($"You are not in a multiverse world!");
        }
示例#19
0
        /// <inheritdoc />
        public override bool PreExecute(OpenPlayer source)
        {
            PlayerItemDropEvent dropEvent = new PlayerItemDropEvent(source, source.KnownPosition, TargetItem, SourceItem);

            source.EventDispatcher.DispatchEvent(dropEvent);
            if (dropEvent.IsCancelled)
            {
                return(false);
            }

            return(true);
        }
示例#20
0
        private bool TryAssign(OpenPlayer player, TeamFillMode fillMode)
        {
            switch (fillMode)
            {
            case TeamFillMode.Fill:
            {
                var team = Teams.Values.FirstOrDefault(x => x.TryJoin(player));
                if (team == null)
                {
                    return(false);
                }

                return(true);
            }

            case TeamFillMode.Spread:
            {
                var teamWithLeast =
                    Teams.Values.FirstOrDefault(x => x.PlayerCount == Teams.Values.Min(xx => xx.PlayerCount));
                if (teamWithLeast == null)
                {
                    return(false);
                }

                if (!teamWithLeast.TryJoin(player))
                {
                    return(false);
                }

                return(true);
            }

            case TeamFillMode.FillMinSpread:
            {
                var team = Teams.Values.FirstOrDefault(x => x.PlayerCount < Config.MinPlayers);
                if (team == null)
                {
                    return(false);
                }

                if (!team.TryJoin(player))
                {
                    return(false);
                }

                return(true);
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#21
0
        public void Create(OpenPlayer player, string levelname, string generator)
        {
            if (levelname.Contains(' ') || levelname.Contains('\t'))
            {
                player.SendPluginMessage($"The level name may not contain any whitespace!");
                return;
            }

            switch (Plugin.MultiVerseManager.Create(levelname, generator, (mv) =>
            {
                if (mv.Ready)
                {
                    player.SendPluginMessage("The world has been created, you can join it by typing '/mv join {levelname}'. You may now create new worlds again!");
                }
            }))
            {
            case CreateResult.InvalidWorldGenerator:
                player.SendPluginMessage(
                    $"No generator was found with the provided name, available values are: {ChatFormatting.Reset}{String.Join(',', Plugin.GeneratorManager.GeneratorNames)}");
                break;

            case CreateResult.NameTaken:
                player.SendPluginMessage($"The provided world name has already been taken...");
                break;

            case CreateResult.UnknownError:
                player.SendPluginMessage($"Something unexpected happened while trying to create your world!");
                break;

            case CreateResult.Initializing:
                player.SendPluginMessage(
                    $"Initializing world... We will let you know once we are done!");
                break;

            case CreateResult.Busy:
                player.SendPluginMessage($"Cannot handle your request, server is busy...");
                break;

            case CreateResult.WorldExists:
                player.SendPluginMessage($"The world already exists, maybe you meant to execute '/mv load {levelname}'");
                break;

            case CreateResult.GeneratorUnavailable:

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#22
0
        internal bool TryJoin(OpenPlayer player)
        {
            if (!CanJoin())
            {
                return(false);
            }

            if (TeamManager.TryAssignTeam(player))
            {
                player.SpawnLevel(Level, Level.SpawnPoint, false);
                return(true);
            }

            return(false);
        }
示例#23
0
文件: Team.cs 项目: Deeplerg/OpenAPI
        public virtual bool TryJoin(OpenPlayer player)
        {
            lock (_teamLock)
            {
                if (PlayerCount < MaxPlayers)
                {
                    if (Members.TryAdd(player.GetIdentifier(), player))
                    {
                        player.SetTeam(this);
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#24
0
        public void Join(OpenPlayer player, string levelname)
        {
            if (Plugin.MultiVerseManager.TryGet(levelname, out var instance))
            {
                player.SendPluginMessage($"Joining multiverse world: {instance.Name}");

                player.Level.RemovePlayer(player, true);

                player.SpawnLevel(instance.Level, instance.Level.SpawnPoint, true, null, () =>
                {
                    player.SendPluginMessage($"You have joined world: {instance.Name}, to leave it type '/mv leave' or join another multiverse world.");
                });
                return;
            }

            player.SendPluginMessage($"No world with the provided name has been found!");
        }
示例#25
0
        public void List(OpenPlayer player)
        {
            var instances = Plugin.MultiVerseManager.Instances;

            if (instances.Length == 0)
            {
                player.SendPluginMessage($"No MultiVerses have been created!");
                return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (var instance in instances)
            {
                sb.AppendLine($"{instance.Name} - {instance.GeneratorName}");
            }

            player.SendPluginMessage(sb.ToString());
        }
示例#26
0
        internal bool TryJoin(OpenPlayer player)
        {
            if (!CanJoin())
            {
                return(false);
            }

            if (TeamManager.TryAssignTeam(player))
            {
                PlayerLocation spawnPosition;

                if (!TryGetSpawnPosition(out spawnPosition))
                {
                    spawnPosition = Level.SpawnPoint;
                }

                player.SpawnLevel(Level, spawnPosition, false);
                return(true);
            }

            return(false);
        }
示例#27
0
 internal void LeaveGame(OpenPlayer player)
 {
     player.GetGameAttribute().Team?.Leave(player);
 }
示例#28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="entity">The entity the player has interacted with</param>
 /// <param name="source">The player that initiated the interaction</param>
 /// <param name="action">The action that got initiated</param>
 public EntityInteractEvent(MiNET.Entities.Entity entity, OpenPlayer source, McpeInventoryTransaction.ItemUseOnEntityAction action) : base(entity)
 {
     SourcePlayer = source;
     Action       = action;
 }
示例#29
0
 public void MultiVerseCommand(OpenPlayer player)
 {
     player.SendPluginMessage($"{Plugin.Info.Name} {Plugin.Info.Version}");
 }
示例#30
0
        private bool ExecuteCommand(MethodInfo method, OpenPlayer player, string[] args, out object result)
        {
            Log.Info($"Execute command {method}");

            result = null;

            var parameters = method.GetParameters();

            int addLenght = 0;

            if (parameters.Length > 0 && typeof(OpenPlayer).IsAssignableFrom(parameters[0].ParameterType))
            {
                addLenght = 1;
            }

            object[] objectArgs = new object[parameters.Length];

            try
            {
                int i = 0;
                for (int k = 0; k < parameters.Length; k++)
                {
                    var parameter = parameters[k];
                    if (k == 0 && addLenght == 1)
                    {
                        if (typeof(OpenPlayer).IsAssignableFrom(parameter.ParameterType))
                        {
                            objectArgs[k] = player;
                            continue;
                        }
                        Log.WarnFormat("Command method {0} missing Player as first argument.", method.Name);
                        return(false);
                    }

                    if (PluginManager.Services.TryResolve(parameter.ParameterType, out var param))
                    {
                        objectArgs[k] = param;
                        continue;
                    }

                    if (parameter.IsOptional && args.Length <= i)
                    {
                        objectArgs[k] = parameter.DefaultValue;
                        continue;
                    }

                    if (args.Length < k)
                    {
                        return(false);
                    }

                    if (typeof(IParameterSerializer).IsAssignableFrom(parameter.ParameterType))
                    {
                        var ctor = parameter.ParameterType.GetConstructor(Type.EmptyTypes);
                        IParameterSerializer defaultValue = ctor.Invoke(null) as IParameterSerializer;
                        defaultValue?.Deserialize(player, args[i++]);

                        objectArgs[k] = defaultValue;

                        continue;
                    }

                    if (typeof(CustomEnum).IsAssignableFrom(parameter.ParameterType))
                    {
                        var        ctor = parameter.ParameterType.GetConstructor(Type.EmptyTypes);
                        CustomEnum c    = ctor.Invoke(null) as CustomEnum;
                        if (!c.SetValue(args[i++]))
                        {
                            return(false);
                        }

                        objectArgs[k] = c;
                        continue;
                        //param.EnumType = c.
                    }

                    if (parameter.ParameterType.BaseType == typeof(EnumBase))
                    {
                        var      ctor     = parameter.ParameterType.GetConstructor(Type.EmptyTypes);
                        EnumBase instance = (EnumBase)ctor.Invoke(null);
                        instance.Value = args[i++];
                        objectArgs[k]  = instance;
                        continue;
                    }

                    if (parameter.ParameterType == typeof(Target))
                    {
                        var target = FillTargets(player, player.Level, args[i++]);
                        objectArgs[k] = target;
                        continue;
                    }

                    if (parameter.ParameterType == typeof(BlockPos))
                    {
                        if (args.Length < i + 3)
                        {
                            return(false);
                        }

                        BlockPos blockPos = new BlockPos();

                        string val = args[i++];
                        if (val.StartsWith("~"))
                        {
                            val = val.Substring(1);
                            blockPos.XRelative = true;
                        }

                        int.TryParse(val, out var x);
                        blockPos.X = x;

                        val = args[i++];
                        if (val.StartsWith("~"))
                        {
                            val = val.Substring(1);
                            blockPos.YRelative = true;
                        }

                        int.TryParse(val, out var y);
                        blockPos.Y = y;

                        val = args[i++];
                        if (val.StartsWith("~"))
                        {
                            val = val.Substring(1);
                            blockPos.ZRelative = true;
                        }

                        int.TryParse(val, out var z);
                        blockPos.Z = z;

                        objectArgs[k] = blockPos;
                        continue;
                    }

                    if (parameter.ParameterType == typeof(string))
                    {
                        objectArgs[k] = args[i++];
                        continue;
                    }
                    if (parameter.ParameterType == typeof(byte))
                    {
                        byte value;
                        if (!byte.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(short))
                    {
                        short value;
                        if (!short.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(int))
                    {
                        int value;
                        if (!int.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(bool))
                    {
                        bool value;
                        if (!bool.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(float))
                    {
                        float value;
                        if (!float.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(double))
                    {
                        double value;
                        if (!double.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType.IsEnum)
                    {
                        string val   = args[i++];
                        Enum   value = Enum.Parse(parameter.ParameterType, val, true) as Enum;
                        if (value == null)
                        {
                            Log.Error($"Could not convert to valid enum value: {val}");
                            continue;
                        }

                        objectArgs[k] = value;
                        continue;
                    }

                    if (IsParams(parameter) && parameter.ParameterType == typeof(string[]))
                    {
                        List <string> strings = new List <string>();
                        for (int j = i++; j < args.Length; j++)
                        {
                            strings.Add(args[j]);
                        }
                        objectArgs[k] = strings.ToArray();
                        continue;
                    }

                    return(false);
                }
            }
            catch (Exception e)
            {
                //	if (Log.IsDebugEnabled)
                {
                    Log.Error("Trying to execute command overload", e);
                }

                return(false);
            }

            try
            {
                if (method.IsStatic)
                {
                    result = method.Invoke(null, objectArgs);
                }
                else
                {
                    if (_pluginCommands.TryGetValue(method, out CommandData data))
                    {
                        object instance = data.Instance;

                        Plugin.CurrentPlayer = player;                         // Setting thread local for call
                        result = method.Invoke(instance, objectArgs);
                        Plugin.CurrentPlayer = null;
                    }
                    else
                    {
                        Log.Warn($"Could not find instance of command's declaringtype!");
                        return(false);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                Log.Error($"Error while executing command {method}", e);
            }

            return(false);
        }