示例#1
0
 private void Awake()
 {
     //init weapon with missing settings
     GetComponent <ItemAttributesV2>().AddTrait(CommonTraits.Instance.Gun);
     itemStorage    = GetComponent <ItemStorage>();
     magSlot        = itemStorage.GetIndexedItemSlot(0);
     pinSlot        = itemStorage.GetIndexedItemSlot(1);
     suppressorSlot = itemStorage.GetIndexedItemSlot(2);
     registerTile   = GetComponent <RegisterTile>();
     queuedShots    = new Queue <QueuedShot>();
     if (pinSlot == null || magSlot == null || itemStorage == null)
     {
         Debug.LogWarning($"{gameObject.name} missing components, may cause issues");
     }
 }
示例#2
0
 private void Awake()
 {
     playerSprites        = GetComponent <PlayerSprites>();
     playerNetworkActions = GetComponent <PlayerNetworkActions>();
     registerTile         = GetComponent <RegisterPlayer>();
     playerHealth         = GetComponent <PlayerHealth>();
     pushPull             = GetComponent <ObjectBehaviour>();
     weaponNetworkActions = GetComponent <WeaponNetworkActions>();
     mouseInputController = GetComponent <MouseInputController>();
     hitIcon           = GetComponentInChildren <HitIcon>(true);
     playerMove        = GetComponent <PlayerMove>();
     playerDirectional = GetComponent <Directional>();
     ItemStorage       = GetComponent <ItemStorage>();
     Equipment         = GetComponent <Equipment>();
 }
 public void CloseStorageUI()
 {
     if (PlayerManager.LocalPlayer != null)
     {
         SoundManager.PlayAtPosition("Rustle#", PlayerManager.LocalPlayer.transform.position, PlayerManager.LocalPlayer);
     }
     CurrentOpenStorage = null;
     otherPlayerStorage.SetActive(false);
     foreach (var uiItemSlot in currentOpenStorageUISlots)
     {
         Destroy(uiItemSlot.transform.parent.gameObject);
     }
     currentOpenStorageUISlots.Clear();
     closeStorageUIButton.SetActive(false);
 }
示例#4
0
    private void Awake()
    {
        itemStorage = GetComponent <ItemStorage>();

        clothingItems = new Dictionary <NamedSlot, ClothingItem>();
        foreach (var clothingItem in GetComponentsInChildren <ClothingItem>())
        {
            if (clothingItem.Slot != NamedSlot.none)
            {
                clothingItems.Add(clothingItem.Slot, clothingItem);
            }
        }
        maskSlot = itemStorage.GetNamedItemSlot(NamedSlot.mask);
        InitInternals();
    }
        /// <summary>
        /// Save data to file
        /// </summary>
        /// <param name="Attempts">Number of attempts</param>
        /// <returns>True, if save was succesful</returns>
        protected async Task <bool> SaveDataAsync(int Attempts = 0)
        {
            try
            {
                foreach (var item in ItemsSource.Where(x => x.Secured && !x.Encrypted))
                {
                    item.Name        = Crypting.Encrypt(item.Name);
                    item.Description = Crypting.Encrypt(item.Description);
                    item.Encrypted   = true;
                }

                var typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

                ItemStorage <T> itemStorage = new ItemStorage <T>()
                {
                    Items      = GetFinalCollection(),
                    TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == nameof(T)))]
                };

                XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>));

                using (Stream XmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(FileName, CreationCollisionOption.ReplaceExisting))
                {
                    Serializ.Serialize(XmlStream, /*DeliveredData*/ itemStorage);
                }

                foreach (var item in ItemsSource.Where(x => x.Secured && x.Encrypted))
                {
                    item.Name        = Crypting.Decrypt(item.Name);
                    item.Description = Crypting.Decrypt(item.Description);
                    item.Encrypted   = false;
                }

                return(true);
            }

            // When file is unavailable
            catch (Exception e) when((e.Message.Contains("denied") || e.Message.Contains("is in use")) && (Attempts < 10))
            {
                return(await SaveDataAsync(Attempts + 1));
            }

            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(false);
            }
        }
示例#6
0
        void Awake()
        {
            Storage = GetComponent <ItemStorage>();
            Storage.ServerInventoryItemSlotSet += ImplantAdded;
            health = maxHealth;
            DamageInitialisation();
            UpdateSeverity();

            OrganList = GetComponents <Organ>().ToList();

            foreach (var organ in OrganList)
            {
                organ.RelatedPart = this;
                organ.Initialisation();
            }
        }
示例#7
0
        void Awake()
        {
            OrganStorage = GetComponent <ItemStorage>();
            OrganStorage.ServerInventoryItemSlotSet += BodyPartTransfer;
            OrganList.Clear();
            OrganList.AddRange(this.GetComponents <BodyPartFunctionality>());

            foreach (var Organ in OrganList)
            {
                Organ.RelatedPart = this;
            }

            health = maxHealth;
            AddModifier(DamageModifier);
            UpdateSeverity();
        }
示例#8
0
        //private MessengerManager messengerSystem;

        /// <summary>
        /// Grabs the components on the game objects and readies itself for slot changes
        /// </summary>
        private void Start()
        {
            storage         = gameObject.GetComponent <ItemStorage>();
            TabOnGameObject = gameObject.GetComponent <HasNetworkTabItem>();
            pdaId           = gameObject.GetComponent <NetworkIdentity>();
            var slot = storage.GetIndexedItemSlot(0);

            if (slot.IsEmpty != true)
            {
                IdCard = slot.Item.GetComponent <IDCard>();
            }
            slot.OnSlotContentsChangeServer.AddListener(SlotChange);
            passlist = UplinkPasswordList.Instance;
            //messengerSystem = GameObject.Find("MessengerManager").GetComponent<MessengerManager>();
            //AddSelf();
        }
示例#9
0
        void Awake()
        {
            Storage = GetComponent <ItemStorage>();
            Storage.ServerInventoryItemSlotSet += ImplantAdded;
            health = maxHealth;
            DamageInitialisation();
            UpdateSeverity();

            BodyPartModifications = this.GetComponents <BodyPartModification>().ToList();

            foreach (var bodyPartModification in BodyPartModifications)
            {
                bodyPartModification.RelatedPart = this;
                bodyPartModification.Initialisation();
            }
        }
示例#10
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (CreationTime != 0L)
            {
                hash ^= CreationTime.GetHashCode();
            }
            if (Username.Length != 0)
            {
                hash ^= Username.GetHashCode();
            }
            if (Team != 0)
            {
                hash ^= Team.GetHashCode();
            }
            if (Tutorial.Length != 0)
            {
                hash ^= Tutorial.GetHashCode();
            }
            if (avatar_ != null)
            {
                hash ^= Avatar.GetHashCode();
            }
            if (PokeStorage != 0)
            {
                hash ^= PokeStorage.GetHashCode();
            }
            if (ItemStorage != 0)
            {
                hash ^= ItemStorage.GetHashCode();
            }
            if (dailyBonus_ != null)
            {
                hash ^= DailyBonus.GetHashCode();
            }
            if (Badge.Length != 0)
            {
                hash ^= Badge.GetHashCode();
            }
            if (settings_ != null)
            {
                hash ^= Settings.GetHashCode();
            }
            hash ^= currency_.GetHashCode();
            return(hash);
        }
        //Insp -> vlastni typ pripony
        public override void Execute(object parameter)
        {
            if (parameter is ListViewBase itemList)
            {
                if (itemList.Items.Count == 0)
                {
                    return;
                }

                string itemTypeName   = itemList.Items[0].GetType().Name;
                var    typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

                var sharedData = new ItemStorage <T>
                {
                    TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == itemTypeName))]
                };

                foreach (var item in new ObservableCollection <T>(itemList.SelectedItems.Cast <T>().Select(x => (T)x.Clone()).ToList()))
                {
                    T itemToShare = item;

                    if (itemToShare.Secured)
                    {
                        itemToShare.Name        = Crypting.Encrypt(itemToShare.Name);
                        itemToShare.Description = Crypting.Encrypt(itemToShare.Description);
                    }

                    sharedData.Items.Add(item);
                }

                try
                {
                    XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>));

                    using (Stream XmlStream = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Share.tdn", CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult())
                    {
                        Serializ.Serialize(XmlStream, sharedData);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }

                DataTransferManager.ShowShareUI();
            }
        }
示例#12
0
	public void BuildSlots(int SlotAmount, ItemStorage storage, string windowTitle)
	{

		SetItemStorage = storage;

		for(int a = 0; a < SlotAmount; a++)
		{
			TitleLabel.text = windowTitle;

			GameObject slot = NGUITools.AddChild(StorageGrid.gameObject, StorageSlotTemplatePrefab);
			slot.transform.name = a.ToString("000");
			StorageSlot s = slot.GetComponent<StorageSlot>();
			s.SlotID = a;
			s.inventory = storage;

		}
	}
    public void CmdRequestItemLabel(GameObject handLabeler, string label)
    {
        ItemStorage itemStorage = gameObject.GetComponent <ItemStorage>();
        Pickupable  handItem    = itemStorage.GetActiveHandSlot().Item;

        if (handItem == null)
        {
            return;
        }
        if (handItem.gameObject != handLabeler)
        {
            return;
        }

        Chat.AddExamineMsgFromServer(gameObject, "You set the " + handLabeler.Item().InitialName.ToLower() + "s text to '" + label + "'.");
        handLabeler.GetComponent <HandLabeler>().SetLabel(label);
    }
示例#14
0
        //Insp -> vlastni typ pripony
        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            if (parameter is ListViewBase itemList)
            {
                if (itemList.Items.Count == 0)
                {
                    return;
                }

                string itemTypeName = itemList.Items[0].GetType().Name;

                var sharedData = new ItemStorage <T>
                {
                    TypeOfItem = itemTypeName
                };

                foreach (var item in new List <T>(itemList.SelectedItems.Cast <T>().Select(x => (T)x.Clone()).ToList()))
                {
                    T itemToShare = item;

                    if (itemToShare.Secured)
                    {
                        itemToShare.Name        = Crypting.Encrypt(itemToShare.Name);
                        itemToShare.Description = Crypting.Encrypt(itemToShare.Description);
                    }

                    sharedData.Items.Add(item);
                }

                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ItemStorage <T>));

                    using Stream xmlStream = ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Share.isuf", CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
                    serializer.Serialize(xmlStream, sharedData);
                }
                catch (Exception e)
                {
                    LogService.AddLogMessage(e.Message, logLevel: Base.Enum.LogLevel.Debug);
                    throw new Base.Exceptions.Exception("Unhandled exception", e);
                }

                DataTransferManager.ShowShareUI();
            }
        }
示例#15
0
 public void CloseStorageUI()
 {
     if (PlayerManager.LocalPlayer != null)
     {
         SoundManager.PlayAtPosition("Rustle#", PlayerManager.LocalPlayer.transform.position, PlayerManager.LocalPlayer);
     }
     CurrentOpenStorage = null;
     otherPlayerStorage.SetActive(false);
     foreach (var uiItemSlot in currentOpenStorageUISlots)
     {
         // remove listeners
         uiItemSlot.ItemSlot.OnSlotContentsChangeClient.RemoveListener(OnSlotContentsChangeClient);
         Destroy(uiItemSlot.transform.parent.gameObject);
     }
     currentOpenStorageUISlots.Clear();
     closeStorageUIButton.SetActive(false);
     indexedStorageCapacity.gameObject.SetActive(false);
 }
示例#16
0
        } = true;                                                       //Only used on the server

        public override void EnsureInit()
        {
            if (init)
            {
                return;
            }
            init = true;
            base.EnsureInit();
            playerNetworkActions = GetComponent <PlayerNetworkActions>();
            playerMove           = GetComponent <PlayerMove>();
            playerSprites        = GetComponent <PlayerSprites>();
            registerPlayer       = GetComponent <RegisterPlayer>();
            itemStorage          = GetComponent <ItemStorage>();
            equipment            = GetComponent <Equipment>();
            playerScript         = GetComponent <PlayerScript>();
            OnConsciousStateChangeServer.AddListener(OnPlayerConsciousStateChangeServer);
            registerPlayer.AddStatus(this);
        }
示例#17
0
        /// <summary>
        /// Decode type of item
        /// </summary>
        /// <param name="fileXmlString">Decoded XML</param>
        /// <returns>Type of item</returns>
        public ItemTypeEnum?CategoryDecode(string fileXmlString)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(fileXmlString);

            var helper = new ItemStorage <BaseItem>();
            var sel    = xmlDoc.SelectSingleNode("//" + nameof(helper.TypeOfItem));

            if (sel == null)
            {
                return(null);
            }

            var typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList();

            return(typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == sel.InnerText))]);
        }
示例#18
0
    public void PopulateItemStorage(ItemStorage toPopulate, PopulationContext context)
    {
        //if appending, start at first free slot index
        var start = 0;

        if (MergeMode == IndexedStoragePopulator.IndexedMergeMode.Append)
        {
            var freeSlot = toPopulate.GetNextFreeIndexedSlot();
            if (freeSlot == null)
            {
                Logger.LogTraceFormat("Can't populate {0}, no more free slots.", Category.Inventory, toPopulate);
                return;
            }

            start = freeSlot.SlotIdentifier.SlotIndex;
        }

        for (var i = start; i < Contents.Count; i++)
        {
            // General protection against missing items
            if (Contents[i] == null)
            {
                continue;                 // Will skip the missing item
            }

            var slot = toPopulate.GetIndexedItemSlot(i);
            if (slot == null)
            {
                Logger.LogErrorFormat("Storage {0} does not have a slot with index {1}. Please ensure" +
                                      " the Contents don't exceed the number of slots in the ItemStorage.",
                                      Category.Inventory,
                                      toPopulate, i);
                return;
            }

            if (slot.Item != null && MergeMode == IndexedStoragePopulator.IndexedMergeMode.Overwrite)
            {
                Inventory.ServerDespawn(slot);
            }

            var spawned = Spawn.ServerPrefab(Contents[i]).GameObject;
            Inventory.ServerAdd(spawned, slot);
        }
    }
示例#19
0
    /// <summary>
    /// Returns the slot in storage which is the best fit for the item.
    /// The BestSlots list will be scanned through in order. Returns the
    /// first slot in the BestSlots list for which toCheck has the
    /// indicated trait (ignored if trait is left blank) and can be put into the slot. If none of the BestSlots
    /// will fit this item, returns the first slot in storage which can hold the item.
    /// Returns null if the item cannot fit in any slots in storage.
    /// </summary>
    /// <param name="toCheck"></param>
    /// <param name="storage"></param>
    /// <param name="mustHaveUISlot">if true (default), will only return slots
    /// which are linked to a UI slot</param>
    /// <returns></returns>
    public ItemSlot GetBestSlot(Pickupable toCheck, ItemStorage storage, bool mustHaveUISlot = true)
    {
        if (toCheck == null || storage == null)
        {
            Logger.LogTrace("Cannot get best slot, toCheck or storage was null", Category.Inventory);
            return(null);
        }

        var side      = CustomNetworkManager.IsServer ? NetworkSide.Server : NetworkSide.Client;
        var itemAttrs = toCheck.GetComponent <ItemAttributesV2>();

        if (itemAttrs == null)
        {
            Logger.LogTraceFormat("Item {0} has no ItemAttributes, thus it will be put in the" +
                                  " first available slot.", Category.Inventory, toCheck);
        }
        else
        {
            //find the best slot
            var best = BestSlots.FirstOrDefault(tsm =>
                                                (!mustHaveUISlot || storage.GetNamedItemSlot(tsm.Slot)?.LocalUISlot != null) &&
                                                Validations.CanFit(storage.GetNamedItemSlot(tsm.Slot), toCheck, side) &&
                                                (tsm.Trait == null || itemAttrs.HasTrait(tsm.Trait)));
            if (best != null)
            {
                return(storage.GetNamedItemSlot(best.Slot));
            }
        }

        Logger.LogTraceFormat("Item {0} did not fit in any BestSlots, thus will" +
                              " be placed in first available slot.", Category.Inventory, toCheck);

        // Get all slots
        var allSlots = storage.GetItemSlots();

        // Filter blaclisted named slots
        var allowedSlots = allSlots.Where((slot) => !slot.NamedSlot.HasValue ||
                                          (slot.NamedSlot.HasValue && !BlackListSlots.Contains(slot.NamedSlot.Value))).ToArray();

        // Select first avaliable
        return(allowedSlots.FirstOrDefault(slot =>
                                           (!mustHaveUISlot || slot.LocalUISlot != null) &&
                                           Validations.CanFit(slot, toCheck, side)));
    }
示例#20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Storage"/> class.
 /// </summary>
 /// <param name="firstEquippableSlot">The first equippable slot.</param>
 /// <param name="lastEquippableSlot">The last equippable slot.</param>
 /// <param name="numberOfSlots">The number of slots.</param>
 /// <param name="itemStorage">The item storage.</param>
 public Storage(int firstEquippableSlot, int lastEquippableSlot, int numberOfSlots, ItemStorage itemStorage)
 {
     this.firstEquippableSlot = firstEquippableSlot;
     this.lastEquippableSlot  = lastEquippableSlot;
     this.itemArray           = new Item[numberOfSlots];
     this.firstStorageSlot    = lastEquippableSlot > 0 ? lastEquippableSlot + 1 : 0;
     this.rows        = (numberOfSlots - this.firstStorageSlot) / InventoryConstants.RowSize;
     this.usedSlots   = new bool[this.rows, InventoryConstants.RowSize];
     this.itemStorage = itemStorage;
     this.itemStorage?.Items
     .Where(item => item.ItemSlot <= lastEquippableSlot + numberOfSlots)
     .ForEach(item =>
     {
         if (!this.AddItemInternal(item.ItemSlot, item))
         {
             throw new ArgumentException("item did not fit into the storage");
         }
     });
 }
示例#21
0
 /// <summary>
 /// Adds the test jewels and potions.
 /// </summary>
 /// <param name="inventory">The inventory.</param>
 protected void AddTestJewelsAndPotions(ItemStorage inventory)
 {
     inventory.Items.Add(this.CreateJewelOfBless(12));
     inventory.Items.Add(this.CreateJewelOfBless(13));
     inventory.Items.Add(this.CreateJewelOfBless(14));
     inventory.Items.Add(this.CreateJewelOfBless(15));
     inventory.Items.Add(this.CreateJewelOfSoul(16));
     inventory.Items.Add(this.CreateJewelOfSoul(17));
     inventory.Items.Add(this.CreateJewelOfSoul(18));
     inventory.Items.Add(this.CreateJewelOfSoul(19));
     inventory.Items.Add(this.CreateHealthPotion(24, 0));
     inventory.Items.Add(this.CreateHealthPotion(25, 1));
     inventory.Items.Add(this.CreateHealthPotion(26, 2));
     inventory.Items.Add(this.CreateHealthPotion(27, 3));
     inventory.Items.Add(this.CreateManaPotion(28, 0));
     inventory.Items.Add(this.CreateManaPotion(29, 1));
     inventory.Items.Add(this.CreateManaPotion(30, 2));
     inventory.Items.Add(this.CreateAlcohol(31));
 }
示例#22
0
    private void Awake()
    {
        GetComponent <ItemAttributesV2>().AddTrait(CommonTraits.Instance.Gun);
        itemStorage  = GetComponent <ItemStorage>();
        magSlot      = itemStorage.GetIndexedItemSlot(0);
        registerTile = GetComponent <RegisterTile>();
        //init weapon with missing settings
        if (AmmoType == null)
        {
            AmmoType = "12mm";
        }

        if (Projectile == null)
        {
            Projectile = Resources.Load("Bullet_12mm") as GameObject;
        }

        queuedShots = new Queue <QueuedShot>();
    }
示例#23
0
    private static void ItemSlotText(ILContext il)
    {
        ILCursor cursor = new ILCursor(il);

        if (cursor.TryGotoNext(i => i.MatchLdloc(1), i => i.MatchLdfld <Item>("fishingPole"), i => i.MatchLdcI4(0)))
        {
            cursor.Emit(OpCodes.Ldloc, 1);
            cursor.Emit(OpCodes.Ldloc, 35);

            cursor.EmitDelegate <Func <Item, int, int> >((weapon, ammoCount) =>
            {
                foreach (BaseAmmoBag bag in GetAmmoBags(Main.LocalPlayer))
                {
                    ItemStorage storage = bag.GetItemStorage();

                    ammoCount += storage.Where(item => !item.IsAir && ItemLoader.CanChooseAmmo(weapon, item, Main.LocalPlayer)).Sum(item => item.stack);
                }

                return(ammoCount);
            });

            cursor.Emit(OpCodes.Stloc, 35);
        }

        if (cursor.TryGotoNext(i => i.MatchLdloc(1), i => i.MatchLdfld <Item>("tileWand"), i => i.MatchLdcI4(0)))
        {
            cursor.Emit(OpCodes.Ldloc, 35);

            cursor.EmitDelegate <Func <int, int> >(bait =>
            {
                foreach (FishingBelt bag in GetFishingBelts(Main.LocalPlayer))
                {
                    ItemStorage storage = bag.GetItemStorage();

                    bait += storage.Where(item => !item.IsAir && item.bait > 0).Sum(item => item.stack);
                }

                return(bait);
            });

            cursor.Emit(OpCodes.Stloc, 35);
        }
    }
示例#24
0
        public void SendAddMessage(ThrownOutItem item)
        {
            List <string> adData   = new List <string>();
            Item          itemDesc = ItemStorage.GetItemDesc(item.ItemServerId);

            adData.Add("addThrownItem");
            adData.Add(itemDesc.ItemStaticId.ToString());
            adData.Add(itemDesc.ServerId.ToString());
            adData.Add(ForgetiveServer.Base64Encode(itemDesc.DescribeMessage));
            adData.Add(ForgetiveServer.Base64Encode(itemDesc.ExtraInfo));
            adData.Add(item.Location.ToXYZ());
            for (int i = 0; i < Map.players.Count; i++)
            {
                try
                {
                    Map.players[i].SendDataPackage(adData);
                }
                catch { }
            }
        }
示例#25
0
        void Awake()
        {
            healthMaster = GetComponentInParent <LivingHealthMasterBase>();
            foreach (BodyPartSprites b in GetComponentsInParent <BodyPartSprites>())
            {
                if (b.BodyPartType.Equals(BodyPartType))
                {
                    Debug.Log(b);
                }

                //TODO: Do we need to add listeners for implant removal
            }

            if (Storage == null)
            {
                Storage = GetComponent <ItemStorage>();
            }

            Storage.ServerInventoryItemSlotSet += ImplantAdded;
        }
示例#26
0
    /// <summary>
    /// Gets the top-level ItemStorage containing this storage. I.e. if this
    /// is a crate inside a backpack will return the crate ItemStorage. If this is not in anything
    /// will simply return this
    /// </summary>
    /// <returns></returns>
    public GameObject GetRootStorageOrPlayer()
    {
        ItemStorage storage    = this;
        var         pickupable = storage.GetComponent <Pickupable>();

        while (pickupable != null && pickupable.ItemSlot != null)
        {
            storage    = pickupable.ItemSlot.ItemStorage;
            pickupable = storage.GetComponent <Pickupable>();
            if (pickupable == null)
            {
                if (storage.player != null)
                {
                    return(storage.player.gameObject);
                }
            }
        }

        return(storage.gameObject);
    }
示例#27
0
        /// <summary>
        /// Checks to see if it can put it in any hand, if it cant it will do nothing meaning the item should just drop.
        /// </summary>
        /// <param name="player"></param>
        private void HandInsert(ItemStorage player)
        {
            ItemSlot activeHand = player.GetActiveHandSlot();

            if (Inventory.ServerAdd(InsertedContainer, activeHand))
            {
                return;
            }
            switch (activeHand.NamedSlot)
            {
            case NamedSlot.leftHand:
                ItemSlot rSlot = player.GetNamedItemSlot(NamedSlot.rightHand);
                Inventory.ServerAdd(InsertedContainer, rSlot);
                break;

            case NamedSlot.rightHand:
                ItemSlot lSlot = player.GetNamedItemSlot(NamedSlot.leftHand);
                Inventory.ServerAdd(InsertedContainer, lSlot);
                break;
            }
        }
示例#28
0
    private void Start()
    {
        // get ItemStorage on a same object
        storage = GetComponent <ItemStorage>();
        if (!storage)
        {
            Logger.LogError($"FancyItemStorage on {gameObject.name} can't find ItemStorage component!", Category.Containers);
            return;
        }

        // get all slots and subscribe if any slot changed
        var allSlots = storage.GetItemSlots();

        foreach (var slot in allSlots)
        {
            slot.OnSlotContentsChangeServer.AddListener(OnStorageChanged);
        }

        // calculate occupied slots count
        objectsInsideCount = allSlots.Count((s) => s.IsOccupied);
    }
示例#29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Storage" /> class.
        /// </summary>
        /// <param name="numberOfSlots">The number of slots.</param>
        /// <param name="boxOffset">The box offset, which is the first index where the 2-dimensional box starts.</param>
        /// <param name="slotOffset">The slot offset, which means at which <see cref="Item.ItemSlot" /> this instance starts.</param>
        /// <param name="itemStorage">The item storage.</param>
        public Storage(int numberOfSlots, int boxOffset, int slotOffset, ItemStorage itemStorage)
        {
            this.ItemArray   = new Item[numberOfSlots];
            this.rows        = (numberOfSlots - boxOffset) / InventoryConstants.RowSize;
            this.usedSlots   = new bool[this.rows, InventoryConstants.RowSize];
            this.ItemStorage = itemStorage;
            this.slotOffset  = slotOffset;
            this.boxOffset   = boxOffset;

            var lastSlot = numberOfSlots + slotOffset;

            this.ItemStorage?.Items
            .Where(item => item.ItemSlot <= lastSlot && item.ItemSlot >= slotOffset)
            .ForEach(item =>
            {
                if (!this.AddItemInternal((byte)(item.ItemSlot - slotOffset), item))
                {
                    throw new ArgumentException("item did not fit into the storage");
                }
            });
        }
示例#30
0
        public void SendToNewPlayer(Player player)
        {
            List <string> data = new List <string>();

            data.Add("updateThrownItems");
            for (int i = 0; i < Items.Count; i++)
            {
                int  index    = Items[i].ItemServerId;
                Item itemdesc = ItemStorage.GetItemDesc(index);
                if (itemdesc == null)
                {
                    continue;
                }
                data.Add(itemdesc.ItemStaticId.ToString());
                data.Add(itemdesc.ServerId.ToString());
                data.Add(ForgetiveServer.Base64Encode(itemdesc.DescribeMessage));
                data.Add(ForgetiveServer.Base64Encode(itemdesc.ExtraInfo));
                data.Add(Items[i].Location.ToXYZ());
                data.Add("next");
                player.SendDataPackage(data);
            }
        }
示例#31
0
 void ReadTrees()
 {
     try
     {
         if (Trees != null)
         {
             Trees.Clear();
         }
         Trees = new List <Vector2L>();
         if (!File.Exists(filetrees))
         {
             return;
         }
         Stream          file      = ItemStorage.__FILE_GETSTREAM(filetrees);
         BinaryFormatter binFormat = new BinaryFormatter();
         Trees = (List <Vector2L>)binFormat.Deserialize(file);
     }
     catch
     {
         throw new CannotLoadExecutionContentException();
     }
 }
示例#32
0
        public static void GDocSupply(string[] args)
        {
            MUs MUList = new MUs();
            List<string> blackList = new List<string>();

            if (args.Length != 16)
            {
                ConsoleLog.WriteLine("Usage: armysupply eLogin ePassword ePin gLogin gPassword document_name sheet_name do_tanks do_food food_q period max_tanks max_health validation_type(none/MU/citizenship) do_init_block");
                ConsoleLog.WriteLine("Example: armysupply snab_org 123456 1111 [email protected] 54321 \"Army supply\" \"Sheet1\" true true 5 60 8 300 MU false");
                return;
            }

            string eLogin = args[1];
            string ePassword = args[2];
            string ePin = args[3];
            string gLogin = args[4];
            string gPassword = args[5];
            string sDocumentName = args[6];
            string sSheetName = args[7];
            bool bDoTanks = Convert.ToBoolean(args[8]);
            bool bDoFood = Convert.ToBoolean(args[9]);
            int iFoodQ = Convert.ToInt32(args[10]);
            int iPeriod = Convert.ToInt32(args[11]);
            int iMaxTanks = Convert.ToInt32(args[12]);
            int iMaxHP = Convert.ToInt32(args[13]);
            string sValidation = args[14];
            bool bDoInitBlock = Convert.ToBoolean(args[15]);

            string token = "";

            ConsoleLog.WriteLine("Loading document...");
            #region Open sheet
            SpreadsheetsService sheetService = new SpreadsheetsService("EArmy supply");
            sheetService.setUserCredentials(gLogin, gPassword);
            SpreadsheetQuery sheetQuery = new SpreadsheetQuery();
            SpreadsheetFeed sheetFeed = sheetService.Query(sheetQuery);

            SpreadsheetEntry sheetSnab = null;
            foreach (SpreadsheetEntry entry in sheetFeed.Entries)
            {
                if (entry.Title.Text == sDocumentName)
                {
                    sheetSnab = entry;
                    break;
                }
            }
            if (sheetSnab == null)
            {
                ConsoleLog.WriteLine("Document '" + sDocumentName + "' not found");
                return;
            }

            AtomLink sheetLink = sheetSnab.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);

            WorksheetQuery wsQuery = new WorksheetQuery(sheetLink.HRef.ToString());
            WorksheetFeed wsFeed = sheetService.Query(wsQuery);

            WorksheetEntry wsSnab = null;
            WorksheetEntry wsSettings = null;
            foreach (WorksheetEntry ws in wsFeed.Entries)
            {
                if (ws.Title.Text == sSheetName)
                {
                    wsSnab = ws;
                }
                if (ws.Title.Text == "Settings")
                {
                    wsSettings = ws;
                }
            }
            if (wsSnab == null)
            {
                ConsoleLog.WriteLine("Page '" + sSheetName + "' not found");
                return;
            }
            if (wsSettings != null)
            {
                LoadSettings(sheetService, wsSettings, MUList, blackList);
            }
            #endregion

            #region Login to supplier
            DonaterBot bt = new DonaterBot(
                eLogin,
                eLogin,
                ePassword,
                ePin,
                "Mozilla//4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                Globals.BotConfig.AntiGateKey,
                Globals.BotConfig.precaptchaBufferSize);
            bt.HttpClient.SetProxy(null, null);
            bool loggedIn = false;
            int iTryToConnect = 0;
            System.Random rnd = new System.Random();
            #endregion

            while (true)
            {
                try
                {
                    ConsoleLog.WriteLine("Loading cells...");
                    #region Query cells
                    AtomLink cellLink = wsSnab.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);

                    CellQuery query = new CellQuery(cellLink.HRef.ToString());
                    query.ReturnEmpty = ReturnEmptyCells.yes;
                    query.MaximumColumn = 13;
                    CellFeed feed = sheetService.Query(query);

                    List<ItemStorage> lines = new List<ItemStorage>();
                    ItemStorage item = null;
                    #endregion

                    #region Load cells
                    lines.Clear();
                    foreach (CellEntry curCell in feed.Entries)
                    {
                        if (curCell.Cell.Row < 2) continue;

                        item = lines.Find(l => l.row == curCell.Cell.Row);
                        if (item == null)
                        {
                            item = new ItemStorage();
                            lines.Add(item);
                            item.row = curCell.Cell.Row;
                        }

                        if (curCell.Cell.Column == 1)       // time
                        {
                            item.time = curCell.Cell.Value;
                        }
                        if (curCell.Cell.Column == 2)       // login
                        {
                            item.login = curCell.Cell.Value;
                        }
                        if (curCell.Cell.Column == 3)       // link to profile
                        {
                            item.personID = curCell.Cell.Value;
                            try
                            {
                                item.personID = item.personID.Substring(item.personID.LastIndexOf('/') + 1);
                                Convert.ToInt64(item.personID);
                            }
                            catch
                            {
                                item.personID = "";
                            }
                            // Cut ID from link
                        }
                        if (curCell.Cell.Column == 4)       // wellness
                        {
                            try
                            {
                                item.wellness = Convert.ToInt32(curCell.Cell.Value);
                            }
                            catch
                            {
                                item.wellness = 0;
                            }
                        }
                        if (curCell.Cell.Column == 5)       // needed tanks
                        {
                            try
                            {
                                item.tanks = Convert.ToInt32(curCell.Cell.Value);
                            }
                            catch
                            {
                                item.tanks = 0;
                            }
                        }
                        if (curCell.Cell.Column == 6)       // military unit
                        {
                            item.militaryUnit = curCell.Cell.Value;
                        }
                        if (curCell.Cell.Column == 8)       // done tanks
                        {
                            item.doneTanksCell = curCell;
                            try
                            {
                                item.doneTanks = Convert.ToInt32(curCell.Cell.Value);
                            }
                            catch
                            {
                                item.wellness = 0;
                            }
                        }
                        if (curCell.Cell.Column == 9)       // done food q
                        {
                            try
                            {
                                item.doneFoodQ = Convert.ToInt32(curCell.Cell.Value);
                            }
                            catch
                            {
                                item.doneFoodQ = 0;
                            }
                            item.doneFoodQCell = curCell;
                        }
                        if (curCell.Cell.Column == 10)      // done food
                        {
                            item.doneFoodCell = curCell;
                            try
                            {
                                item.doneFood = Convert.ToInt32(curCell.Cell.Value);
                            }
                            catch
                            {
                                item.doneFood = 0;
                            }
                        }
                        if (curCell.Cell.Column == 11)       // autocomment cell
                        {
                            item.comment = curCell.Cell.Value;
                            item.commentCell = curCell;
                        }
                        if (curCell.Cell.Column == 12)       // tanks limit cell
                        {
                            try
                            {
                                if (!String.IsNullOrEmpty(curCell.Cell.Value))
                                    item.tanksLimit = Convert.ToInt32(curCell.Cell.Value);
                                else
                                    item.tanksLimit = -1;
                            }
                            catch
                            {
                                item.tanksLimit = -1;
                            }

                            item.tanksLimitCell = curCell;
                        }
                        if (curCell.Cell.Column == 13)       // HP limit cell
                        {
                            try
                            {
                                if (!String.IsNullOrEmpty(curCell.Cell.Value))
                                    item.foodLimit = Convert.ToInt32(curCell.Cell.Value);
                                else
                                    item.foodLimit = -1;
                            }
                            catch
                            {
                                item.foodLimit = -1;
                            }

                            item.foodLimitCell = curCell;
                        }
                    }
                    ConsoleLog.WriteLine("Items loaded: " + lines.Count);
                    #endregion

                    #region Parce cells
                    int row = 0;
                    List<ItemStorage> tmpList = new List<ItemStorage>(lines);
                    foreach (ItemStorage testItem in tmpList)
                    {
                        row++;

                        if (string.IsNullOrEmpty(testItem.time))
                        {
                            lines.Remove(testItem);
                            continue;
                        }

                        if (!string.IsNullOrEmpty(testItem.comment))
                        {
                            lines.Remove(testItem);
                            continue;
                        }

                        if (string.IsNullOrEmpty(testItem.personID))
                        {
                            lines.Remove(testItem);
                            testItem.commentCell.Cell.InputValue = "Bad profile";
                            testItem.commentCell.Update();
                            continue;
                        }

                        if (blackList.Contains(testItem.login))
                        {
                            lines.Remove(testItem);
                            testItem.commentCell.Cell.InputValue = "Blacklist";
                            testItem.commentCell.Update();
                            continue;
                        }

                        if ((sValidation.ToLower() == "mu") &&
                            (String.IsNullOrEmpty(MUList[testItem.militaryUnit])))
                        {
                            lines.Remove(testItem);
                            testItem.commentCell.Cell.InputValue = "MU not in list";
                            testItem.commentCell.Update();
                            continue;
                        }

                        if ((testItem.wellness == 0) && (testItem.tanks == 0))
                        {
                            lines.Remove(testItem);
                            testItem.commentCell.Cell.InputValue = "Bad wellness/tanks";
                            testItem.commentCell.Update();
                            continue;
                        }

                        //if (testItem.tanks > 30)
                        //{
                        //    lines.Remove(testItem);
                        //    testItem.commentCell.Cell.InputValue = "Bad tanks";
                        //    testItem.commentCell.Update();
                        //    continue;
                        //}

                        if (tmpList.Find(o => (o.personID == testItem.personID && o.viewedForDuplicate)) != null)
                        {
                            lines.Remove(testItem);
                            testItem.commentCell.Cell.InputValue = "Duplicate record";
                            testItem.commentCell.Update();
                            continue;
                        }

                        if (testItem.tanksLimit == -1)
                        {
                            if (bDoInitBlock)
                            {
                                testItem.tanksLimit = 0;
                            }
                            else
                            {
                                testItem.tanksLimit = iMaxTanks;
                            }
                            testItem.tanksLimitCell.Cell.InputValue = testItem.tanksLimit.ToString();
                            testItem.tanksLimitCell.Update();
                        }

                        if (testItem.foodLimit == -1)
                        {
                            if (bDoInitBlock)
                            {
                                testItem.foodLimit = 0;
                            }
                            else
                            {
                                testItem.foodLimit = iMaxHP;
                            }
                            testItem.foodLimitCell.Cell.InputValue = testItem.foodLimit.ToString();
                            testItem.foodLimitCell.Update();
                        }

                        testItem.viewedForDuplicate = true;

                        ConsoleLog.WriteLine(
                            row + ": " +
                            testItem.time + ";" +
                            testItem.login + ";" +
                            testItem.personID + ";" +
                            testItem.wellness + ";" +
                            testItem.tanks + ";" +
                            testItem.doneTanks + ";" +
                            testItem.doneFoodQ + ";" +
                            testItem.doneFood
                            );
                    }
                    #endregion

                    #region Log in
                    if (!loggedIn)
                    {
                        iTryToConnect++;
                        if (iTryToConnect > 10)
                            break;

                        ConsoleLog.WriteLine("Trying to login (" + (iTryToConnect).ToString() + ")...");
                        if (bt.Login())
                        {
                            ConsoleLog.WriteLine("Logged in!");
                            iTryToConnect = 0;
                            loggedIn = true;
                        }
                        else
                        {
                            ConsoleLog.WriteLine("Login failed!");
                            System.Threading.Thread.Sleep(1000);
                            continue;
                        }
                    }
                    #endregion

                    //Process donations
                    foreach (ItemStorage donateItem in lines)
                    {
                        ConsoleLog.WriteLine("Donating to: login="******", id=" + donateItem.personID);

                        #region Calculate quantities
                        int foodQty;
                        if ((bDoFood) && (donateItem.wellness > 0) && (donateItem.doneFoodQ == 0))
                        {
                            foodQty = Convert.ToInt32(Math.Round((double)((double)Math.Min(donateItem.wellness, donateItem.foodLimit) / (iFoodQ * 2))));
                            foodQty = foodQty - donateItem.doneFood;
                        }
                        else
                        {
                            foodQty = 0;
                        }

                        int tankQty;

                        if (bDoTanks)
                        {
                            tankQty = Math.Min(donateItem.tanks, donateItem.tanksLimit);
                            tankQty = tankQty - donateItem.doneTanks;
                        }
                        else
                        {
                            tankQty = 0;
                        }

                        if ((foodQty <= 0) && (tankQty <= 0))
                        {
                            ConsoleLog.WriteLine("Nothing to donate");
                            continue;
                        }
                        #endregion

                        #region Open pages and validate
                        string srcPage = "http://www.erepublik.com/en/citizen/profile/" + donateItem.personID;

                        bt.CustomRequest(srcPage);

                        if (!bt.GetLastResponse().Contains("career_tab_content"))
                        {
                            ConsoleLog.WriteLine("Profile page loading failed. Try to relogin...");
                            loggedIn = false;
                            break;
                        }

                        if (bt.GetLastResponse().IndexOf("alt=\"" + donateItem.login.Trim() + "\"", StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            ConsoleLog.WriteLine("Donating login validation failed");
                            donateItem.commentCell.Cell.InputValue = "Profile != Login";
                            donateItem.commentCell.Update();
                            continue;
                        }
                        else
                        {
                            ConsoleLog.WriteLine("Login validated");
                        }

                        if ((sValidation.ToLower() == "mu") &&
                            (bt.GetLastResponse().IndexOf("alt=\"" + MUList[donateItem.militaryUnit.Trim()] + "\"", StringComparison.OrdinalIgnoreCase) == -1))
                        {
                            ConsoleLog.WriteLine("Donating MU validation failed (" + MUList[donateItem.militaryUnit.Trim()] + ")");
                            ConsoleLog.WriteLine(bt.GetLastResponse(), "Storage page");
                            donateItem.commentCell.Cell.InputValue = "Profile != MU";
                            donateItem.commentCell.Update();
                            continue;
                        }
                        else
                        {
                            ConsoleLog.WriteLine("MU validated");
                        }

                        srcPage = "http://economy.erepublik.com/en/citizen/donate/" + donateItem.personID;

                        bt.CustomRequest(srcPage);

                        if (bt.CheckPin(true))
                        {
                            bt.SubmitPin();
                        }

                        if (bt.CheckPin(true))
                        {
                            ConsoleLog.WriteLine("Pin validation failed");
                            break;
                        }

                        if (!bt.GetLastResponse().Contains("<th colspan=\"4\" valign=\"middle\">Your storage</th>"))
                        {
                            ConsoleLog.WriteLine("Donate page loading failed. Try to relogin...");
                            loggedIn = false;
                            break;
                        }

                        token = CommonUtils.GetStringBetween(
                            bt.GetLastResponse(),
                            "donate_form[_csrf_token]\" value=\"",
                            "\"");
                        #endregion

                        #region Donate food
                        if (foodQty > 0)
                        {
                            ConsoleLog.WriteLine("Donating food: " + foodQty + " (q" + iFoodQ + ")");

                            if (bt.DonateItem(foodQty.ToString(), Goods.Food.ToString(), iFoodQ.ToString(), token, srcPage))
                            //if (true)
                            {
                                ConsoleLog.WriteLine("Donating food success");
                                donateItem.doneFoodQCell.Cell.InputValue = iFoodQ.ToString();
                                donateItem.doneFoodQCell.Update();
                                donateItem.doneFoodCell.Cell.InputValue = (donateItem.doneFood + foodQty).ToString();
                                donateItem.doneFoodCell.Update();
                            }
                            else
                            {
                                ConsoleLog.WriteLine("Donating food failed");
                                //ConsoleLog.WriteLine(bt.GetLastResponse(), "DonateLog.txt");
                            }

                            ConsoleLog.WriteLine("Wait 5 sec...");
                            System.Threading.Thread.Sleep(5 * 1000);
                        }
                        else
                        {
                            ConsoleLog.WriteLine("No food needed");
                        }
                        #endregion

                        #region Donate tanks
                        if (tankQty > 0)
                        {
                            ConsoleLog.WriteLine("Donating tanks: " + tankQty);

                            if (bt.DonateItem(tankQty.ToString(), Goods.Weapon.ToString(), 5.ToString(), token, srcPage))
                            //if (true)
                            {
                                ConsoleLog.WriteLine("Donating tanks success");
                                donateItem.doneTanksCell.Cell.InputValue = (donateItem.doneTanks + tankQty).ToString();
                                donateItem.doneTanksCell.Update();
                            }
                            else
                            {
                                ConsoleLog.WriteLine("Donating tanks failed");
                                ConsoleLog.WriteLine(bt.GetLastResponse(), "DonateLog.txt");
                            }

                            ConsoleLog.WriteLine("Wait 5 sec...");
                            System.Threading.Thread.Sleep(5 * 1000);
                        }
                        else
                        {
                            ConsoleLog.WriteLine("No tanks needed");
                        }
                        #endregion
                    }
                }
                catch (System.Exception e)
                {
                    ConsoleLog.WriteLine("Donater error: " + e.Message);
                    ConsoleLog.WriteLine(bt.GetLastResponse(), "Responses.txt");
                }

                ConsoleLog.WriteLine("Waiting for next check");
                //break;
                System.Threading.Thread.Sleep(iPeriod * 1000);
            }

            ConsoleLog.WriteLine("It's OK :)");
        }
示例#33
0
		public CharacterDatabaseData(DataRow row)
			: base() {
			Skills = new CharacterSkillTree();
			Storage = new ItemStorage();
			Inventory = new ItemInventory();
			Cart = new ItemInventoryCart();
			Hotkeys = new CharacterHotkey[Global.MAX_HOTKEYS];
			Friends = new CharacterFriendList();

			if (row != null) {
				LoadFromDatabase(row);
			}
		}