Example #1
0
 /// <summary>
 /// Получение всех контрактных блоков в мире игры
 /// </summary>
 public void GetContractBlocks()
 {
     try
     {
         ContractBlocks.Clear();
         var entities = new HashSet <IMyEntity>();
         ///собираем все сущности - структуры на сервере
         MyAPIGateway.Entities.GetEntities(entities);
         entities.OfType <IMyCubeGrid>().ForEach(entity =>
         {
             ///для каждой структуры проверяем наличие в ней контрактного блока
             (entity as MyCubeGrid).GridSystems.TerminalSystem.Blocks.OfType <MyContractBlock>().ToList().ForEach(contractBlock => {
                 if (PlayerUtils.IsAdmin(PlayerUtils.GetPlayer(contractBlock.OwnerId)) /* || PlayerUtils.IsNpc(contractBlock.OwnerId)*/)
                 {
                     ///если еще не был добавлен - добавляем в список
                     if (!ContractBlocks.Contains(contractBlock))
                     {
                         ContractBlocks.Add(contractBlock);
                     }
                 }
             });
         });
     } catch (Exception e)
     {
         Log.Error(e.Message);
         Log.Error(e.StackTrace);
     }
 }
Example #2
0
 /// <summary>
 /// Обработчик события провала контракта
 /// </summary>
 /// <param name="contractID"></param>
 /// <param name="player"></param>
 public void OnFailContract(long contractID, IMyPlayer player)
 {
     try
     {
         //Log.Info("start failed contract");
         LoadContracts();
         ///эксплойт !!!!!!!!!!!
         ///можно убивать охотника и апать себе награду в несколько раз и потом договариваться на слив 50/50 с другим игроком, как програмно запретить пока не придумал
         ContractStorage.BountedPlayers.Where(x => x.Contracts.Where(y => y.contract_id == contractID).Count() > 0).ForEach(x => {
             x.Contracts.ForEach(y => {
                 ///меняем статус контракта
                 if (y.HunterSteamID == player.SteamUserId)
                 {
                     y.State = MyCustomContractStateEnum.Invalid;
                 }
             });
             ///увеличиваем баланс жертвы на значение из конфига
             PlayerUtils.GetPlayer(x.SteamID).RequestChangeBalance(x.Bounty / (Plugin.Config.KillingHunterRewardPercentage / 100));
             //Log.Info("add bounty for killing hunter");
             ///добавляем к награде за голову значение из конфига
             AddPlayerBounty(x.SteamID, x.Bounty / (Plugin.Config.HuntedPlayerBountyUpByKillingHunterPercentage / 100));
         });
         ///сохраняем и пересоздаем контракты
         SaveContracts();
         ReCreateInactiveContracts();
     }
     catch (Exception e)
     {
         Log.Error(e.Message);
         Log.Error(e.StackTrace);
     }
 }
Example #3
0
        /// <summary>
        /// Добавление заказа на игрока/добавление награды к существующему заказу
        /// </summary>
        /// <param name="steamID"></param>
        /// <param name="bounty"></param>
        public void AddPlayerBounty(ulong steamID, int bounty)
        {
            try
            {
                ///загружаем список заказов и проверяем есть ли уже на игрока с указанным SteamId заказ
                LoadContracts();

                if (ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).Count() > 0)
                {
                    ///если заказ есть - добавляем к награде сумму bounty космокредитов
                    ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).ForEach(x => x.Bounty += bounty);
                }
                else
                {
                    ///если заказа нет - создаем новый и записываем в хранилище
                    var bountedPlayer = new BountedPlayer()
                    {
                        SteamID = steamID,
                        Name    = PlayerUtils.GetPlayer(steamID).DisplayName,
                        Bounty  = bounty
                    };
                    ContractStorage.BountedPlayers.Add(bountedPlayer);
                }
                ///сохраняем заказы в файл
                SaveContracts();
            } catch (Exception e)
            {
                Log.Error(e.Message);
                Log.Error(e.StackTrace);
            }
        }
Example #4
0
 private void ContractSystem_CustomFailFor(long contractId, long identityId, bool isAbandon)
 {
     if (!isAbandon)
     {
         var player = PlayerUtils.GetPlayer(identityId);
         Core.OnFailContract(contractId, player);
     }
 }
Example #5
0
 private void ContractSystem_CustomActivateContract(long contractId, long identityId)
 {
     try
     {
         var player = PlayerUtils.GetPlayer(identityId);
         Core.OnActivateContract(contractId, player);
     } catch (Exception e)
     {
         Log.Error(e, "customActivate error:" + e.Message);
     }
     ///tag checked if contract target and quest_player in one tag - failed contract
 }
Example #6
0
        private void DamageApplied(object target, ref MyDamageInformation info)
        {
            try
            {
                if (!(target is MyCharacter))
                {
                    return;
                }
                if (!(target is MyCharacter targetCharacter))
                {
                    return;
                }

                //Log.Info($"Target type {target.GetType().Name}");
                var damageInfo = info;
                //Log.Info($"target is player");
                //Log.Info($"damage amount {damageInfo.Amount}");
                //Log.Info($"attacker id {damageInfo.AttackerId}");
                //Log.Info($"deformation? {damageInfo.IsDeformation}");
                //Log.Info($"attack type {damageInfo.Type}");

                //var attackerIdentity = damageInfo.AttackerId;
                //var targetPlayer = MyPlayer.GetPlayerFromCharacter(targetCharacter);
                var targetPlayer = PlayerUtils.GetPlayer(targetCharacter.GetPlayerIdentityId());
                if (targetPlayer == null)
                {
                    return;
                }

                var targetHealth = MyVisualScriptLogicProvider.GetPlayersHealth(targetPlayer.Identity.IdentityId);
                if (targetHealth < damageInfo.Amount)
                {
                    IMyPlayer attackerPlayer = Core.GetPlayer(damageInfo.AttackerId);
                    if (attackerPlayer == null)
                    {
                        return;
                    }
                    if (attackerPlayer != null)
                    {
                        Core.OnDamage(targetPlayer, attackerPlayer);
                    }
                }
            } catch (Exception e)
            {
                Log.Error(e.Message);
                Log.Error("--------------------------");
                Log.Error(e.StackTrace);
            }
        }
Example #7
0
    void Start()
    {
        m_interactionTargetAnimator = m_interactionTarget.GetComponent <Animator>();

        m_mouseButtonAnimator  = m_interactionMouseButton.GetComponent <Animator>();
        m_menuPageOpenCollider = m_interactionMouseButton.GetComponent <Collider2D>();

        m_menuPageAnimator = m_interactionMenuPage.GetComponent <Animator>();

        m_player = PlayerUtils.GetPlayer();
        if (m_player)
        {
            m_playerCharController = m_player.GetComponent <CharController>();
        }
    }
Example #8
0
 /// <summary>
 /// Обработчик события завершения контракта
 /// </summary>
 /// <param name="contractID"></param>
 public void OnFinishContract(long contractID)
 {
     try
     {
         //Log.Info("start finish contract");
         LoadContracts();
         ContractStorage.BountedPlayers.Where(x => x.Contracts.Where(y => y.contract_id == contractID).Count() > 0).ForEach(x => {
             //Log.Info($"contracts for player {x.SteamID}");
             ///если контракт был принят - удаляем его из блока и у игроков принявших контракт
             x.Contracts.ForEach(y => {
                 if (y.contract_id != contractID && y.HunterSteamID != 0)
                 {
                     //Log.Info($"try finish contract with hunter != killer");
                     var player = PlayerUtils.GetPlayer(y.HunterSteamID);
                     MyAPIGateway.ContractSystem.TryAbandonCustomContract(y.contract_id, player.IdentityId);
                     MyAPIGateway.ContractSystem.RemoveContract(y.contract_id);
                     //Log.Info($"remove contract");
                 }
                 /// если контракт не был принят - удаляем его из контрактного блока
                 else if (y.contract_id != contractID && y.HunterSteamID == 0)
                 {
                     MyAPIGateway.ContractSystem.RemoveContract(y.contract_id);
                     //Log.Info($"remove contract");
                 }
             });
             //Log.Info($"try change bounty for target");
             ///вычитаем сумму вознаграждения из суммы за голову игрока
             AddPlayerBounty(x.SteamID, -x.Bounty);
             //Log.Info($"clear contracts");
             ///очищаем список активных контрактов
             x.Contracts.Clear();
         });
         ///сохраняем список заказов в файл
         SaveContracts();
         ///пересоздаем контракты в контрактных блоках
         ReCreateInactiveContracts();
     }
     catch (Exception e)
     {
         Log.Error(e.Message);
         Log.Error(e.StackTrace);
     }
 }
Example #9
0
        /// <summary>
        /// Метод для получения интерфейса игрока в случае если огонь велся не с ручного оружия
        /// </summary>
        /// <param name="entityID"></param>
        /// <returns></returns>
        public IMyPlayer GetPlayer(long entityID)
        {
            try
            {
                IMyPlayer player     = (IMyPlayer)null;
                IMyEntity entityById = MyAPIGateway.Entities.GetEntityById((long)entityID);
                switch (entityById)
                {
                case IMyCubeBlock _:
                    MyCubeBlock myCubeBlock = entityById is MyCubeBlock ? entityById as MyCubeBlock : (MyCubeBlock)(entityById as MyFunctionalBlock);
                    if (myCubeBlock.CubeGrid != null)
                    {
                        if (myCubeBlock.CubeGrid.HasMainCockpit() && myCubeBlock.CubeGrid.MainCockpit != null)
                        {
                            IMyShipController mainCockpit    = myCubeBlock.CubeGrid.MainCockpit as IMyShipController;
                            IMyControllerInfo controllerInfo = ((IMyControllableEntity)mainCockpit).ControllerInfo;
                            if (controllerInfo != null && controllerInfo.ControllingIdentityId > 0L)
                            {
                                player = PlayerUtils.GetPlayer(((IMyControllableEntity)mainCockpit).ControllerInfo.ControllingIdentityId);
                            }
                        }
                        if (player == null)
                        {
                            player = PlayerUtils.GetPlayer(PlayerUtils.GetOwner(myCubeBlock.CubeGrid));
                        }
                        break;
                    }
                    break;

                case IMyCubeGrid _:
                    player = PlayerUtils.GetPlayer(PlayerUtils.GetOwner(entityById as MyCubeGrid));
                    break;

                case IMyPlayer _:
                    player = entityById as IMyPlayer;
                    break;

                case IMyCharacter _:
                    player = PlayerUtils.GetPlayer((entityById as MyCharacter).GetPlayerIdentityId());
                    break;

                case IMyHandheldGunObject <MyGunBase> _:
                    player = PlayerUtils.GetPlayer((entityById as IMyHandheldGunObject <MyGunBase>).OwnerIdentityId);
                    break;

                case IMyHandheldGunObject <MyToolBase> _:
                    player = PlayerUtils.GetPlayer((entityById as IMyHandheldGunObject <MyToolBase>).OwnerIdentityId);
                    break;

                default:
                    ///если не удалось определить по какой причине умер игрок
                    Log.Warn("Undetected kill type:");
                    Log.Warn("> Name: " + entityById.DisplayName);
                    Log.Warn(string.Format("> Type: {0}", (object)((object)entityById).GetType()));
                    break;
                }
                return(player);
            } catch (Exception e)
            {
                return(null);
            }
        }
Example #10
0
        /// <summary>
        /// Добавление нового контракта за голову
        /// </summary>
        /// <param name="steamID">SteamID цели контракта</param>
        public void AddHeadHunterContract(ulong steamID)
        {
            try
            {
                ///парсим строку определения кастомного контракта и пишем в новую переменную
                MyDefinitionId definitionId;
                MyDefinitionId.TryParse("MyObjectBuilder_ContractTypeDefinition/CustomContract", out definitionId);

                ///Получаем интерфейс игрока на сервере
                var player = PlayerUtils.GetPlayer(steamID);
                ///Если игрока нет в сети или не существует - контракт не добавляется
                if (player == null)
                {
                    return;
                }
                ///Создаем описание контракта
                var contractDescr = new ContractDescription(player.DisplayName);
                ///в глобальные переменные пишем список контрактных блоков и загружаем ранее созданные контракты
                GetContractBlocks();
                LoadContracts();

                ///блокируем список на изменение в других потоках
                lock (ContractStorage)
                {
                    ///проверяем контракты, есть ли уже заказ на этого игрока
                    ContractBlocks.ForEach(contractBlock => {
                        if (ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).Count() > 0)
                        {
                            ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).ForEach(x => {
                                ///если заказ найден проверяем остаток на награде
                                ///если награда 0 - контракты не добавляются в контрактные блоки
                                if (x.Bounty == 0)
                                {
                                    return;
                                }

                                ///если награда не 0 - создаем новый контракт
                                var bounty     = x.Bounty;
                                var collateral = Plugin.Config.ContractCollateral;
                                var contract   = new MyContractCustom(definitionId, contractBlock.EntityId, bounty, collateral, 0, contractDescr.GetContractName(), contractDescr.GetDescription(), 10, -10, null);

                                ///добавляем новый контракт в систему контрактов
                                var contractAddResult = MyAPIGateway.ContractSystem.AddContract(contract);
                                ///если добавление прошло успешно - записываем в список заказов новый контракт
                                if (contractAddResult.Success)
                                {
                                    var _contract = new HeadHunterContract()
                                    {
                                        contract_id = contractAddResult.ContractId, contract_condition_id = contractAddResult.ContractConditionId, State = MyAPIGateway.ContractSystem.GetContractState(contractAddResult.ContractId)
                                    };
                                    x.Contracts.Add(_contract);
                                }
                                else
                                {
                                    Log.Info("failed add contract");
                                }
                            });
                        }
                    });
                }
                ///записываем контракты в файл
                SaveContracts();
            } catch (Exception e)
            {
                Log.Error(e.Message);
                Log.Error(e.StackTrace);
            }
        }