Esempio n. 1
0
 public bool AddFromContainer(IChest container, string actorId, string objId, out ServerInventoryItem obj)
 {
     obj = null;
     if (container.TryGetObject(actorId, objId, out obj))
     {
         container.TryRemoveObject(actorId, objId);
         return(Add(obj.Object, obj.Count));
     }
     return(false);
 }
    private void Start() //main
    {
        // IFactory_Insect factory = new Factory_EastInsect();
        IFactory_Insect factory = new Factory_WestInsect();

        IHead  head  = factory.Create_Head();
        IChest chest = factory.Create_Chest();

        head.See();
    }
        public bool TryRefillChest(DPoint chestLocation, RefillChestMetadata refillChestData)
        {
            IChest chest = this.ChestFromLocation(chestLocation);

            if (chest == null)
            {
                throw new InvalidOperationException("No chest data found at lcoation.");
            }

            return(this.TryRefillChest(chest, refillChestData));
        }
        public void RemoveProtection(TSPlayer player, DPoint tileLocation, bool checkIfBlockTypeDeprotectableByConfig = true)
        {
            if (player == null)
            {
                throw new ArgumentNullException();
            }

            bool canDeprotectEverything = player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission);

            if (TerrariaUtils.Tiles.IsValidCoord(tileLocation))
            {
                ITile tile = TerrariaUtils.Tiles[tileLocation];
                if (tile.active())
                {
                    if (!canDeprotectEverything && checkIfBlockTypeDeprotectableByConfig && this.Config.NotDeprotectableTiles[tile.type])
                    {
                        throw new InvalidBlockTypeException(tile.type);
                    }

                    tileLocation = TerrariaUtils.Tiles.MeasureObject(tileLocation).OriginTileLocation;
                }
            }

            ProtectionEntry protection;

            lock (this.WorldMetadata.Protections)
                if (!this.WorldMetadata.Protections.TryGetValue(tileLocation, out protection))
                {
                    throw new NoProtectionException(tileLocation);
                }

            if (!canDeprotectEverything && protection.Owner != player.Account.ID)
            {
                throw new TileProtectedException(tileLocation);
            }

            if (protection.BankChestKey != BankChestDataKey.Invalid)
            {
                IChest chest = this.ChestManager.ChestFromLocation(tileLocation);
                if (chest != null)
                {
                    for (int i = 0; i < Chest.maxItems; i++)
                    {
                        chest.Items[i] = ItemData.None;
                    }
                }
            }

            lock (this.WorldMetadata.Protections)
                this.WorldMetadata.Protections.Remove(tileLocation);
        }
Esempio n. 5
0
        public bool TryRefillChest(IChest chest, RefillChestMetadata refillChestData)
        {
            for (int i = 0; i < Chest.maxItems; i++)
            {
                chest.SetItem(i, refillChestData.RefillItems[i]);
            }

            if (
                refillChestData.AutoLock && refillChestData.RefillTime != TimeSpan.Zero &&
                !TerrariaUtils.Tiles.IsChestLocked(TerrariaUtils.Tiles[chest.Location])
                )
            {
                TerrariaUtils.Tiles.LockChest(chest.Location);
            }

            return(true);
        }
Esempio n. 6
0
        public IChest ChestFromLocation(DPoint chestLocation, TSPlayer reportToPlayer = null)
        {
            Tile tile = TerrariaUtils.Tiles[chestLocation];

            if (!tile.active() || (tile.type != (int)BlockType.Chest && tile.type != (int)BlockType.Dresser))
            {
                reportToPlayer?.SendErrorMessage("There is no chest at this position.");
                return(null);
            }

            IChest chest            = null;
            int    chestIndex       = Chest.FindChest(chestLocation.X, chestLocation.Y);
            bool   isWorldDataChest = (chestIndex != -1 && chestIndex != ChestManager.DummyChestIndex);

            if (isWorldDataChest)
            {
                Chest tChest = Main.chest[chestIndex];
                if (tChest != null)
                {
                    chest = new ChestAdapter(chestIndex, Main.chest[chestIndex]);
                }
                else
                {
                    reportToPlayer?.SendErrorMessage($"World data for this chest (id {chestIndex}) were expected, but was not present.");
                }
            }
            else
            {
                lock (this.WorldMetadata.ProtectorChests) {
                    ProtectorChestData protectorChest;
                    if (this.WorldMetadata.ProtectorChests.TryGetValue(chestLocation, out protectorChest))
                    {
                        chest = protectorChest;
                    }
                    else
                    {
                        reportToPlayer?.SendErrorMessage("The data record of this chest is missing in both world data and Protector's data.");
                    }
                }
            }

            return(chest);
        }
Esempio n. 7
0
        public void DestroyChest(IChest chest)
        {
            if (chest != null)
            {
                int chestIndex;
                if (chest.IsWorldChest)
                {
                    Main.chest[chest.Index] = null;
                    chestIndex = chest.Index;
                }
                else
                {
                    lock (this.WorldMetadata.ProtectorChests)
                        this.WorldMetadata.ProtectorChests.Remove(chest.Location);

                    chestIndex = ChestManager.DummyChestIndex;
                }

                TSPlayer.All.SendData(PacketTypes.TileKill, string.Empty, 1, chest.Location.X, chest.Location.Y, 0, chestIndex);
            }
        }
Esempio n. 8
0
        public bool AddAllFromChest(IChest chest, string actorId, out ConcurrentBag <ServerInventoryItem> addedObjects)
        {
            addedObjects = new ConcurrentBag <ServerInventoryItem>();

            ConcurrentBag <string> idsForRemove = new ConcurrentBag <string>();

            ConcurrentDictionary <string, ServerInventoryItem> actorObjects = null;

            if (chest.TryGetActorObjects(actorId, out actorObjects))
            {
                foreach (var pair in actorObjects)
                {
                    if (Add(pair.Value.Object, pair.Value.Count))
                    {
                        idsForRemove.Add(pair.Value.Object.Id);
                        addedObjects.Add(pair.Value);
                    }
                }
                return(chest.TryRemoveActorObjectids(actorId, idsForRemove.ToList()));
            }
            return(false);
        }
Esempio n. 9
0
 private void PrepareLootItems(IChest chest)
 {
     int[]           lootItems   = chest.data.items;
     int[]           mineItems   = character.status.items;
     InventorySlot[] lootButtons = FillItemsTo(lootSlotsParent, lootItems);
     InventorySlot[] mineButtons = FillItemsTo(lootMineSlotsParent, mineItems);
     for (int i = 0; i < mineButtons.Length; i++)
     {
         int index = i;
         mineButtons [i].button.onClick.RemoveAllListeners();
         mineButtons [i].button.onClick.AddListener(delegate {
             chest.AddFrom(character, character.status.GetItemByID(mineButtons[index].id));
         });
     }
     for (int i = 0; i < lootButtons.Length; i++)
     {
         int index = i;
         lootButtons [i].button.onClick.RemoveAllListeners();
         lootButtons [i].button.onClick.AddListener(delegate {
             chest.CastTo(character, chest.GetItemByID(lootButtons[index].id));
         });
     }
     lootableChest = chest;
 }
        public void RemoveChestData(IChest chest)
        {
            ItemData[] content = new ItemData[Chest.maxItems];
              for (int i = 0; i < Chest.maxItems; i++)
            content[i] = chest.Items[i];

              if (chest.IsWorldChest) {
            int playerUsingChestIndex = Chest.UsingChest(chest.Index);
            if (playerUsingChestIndex != -1)
              Main.player[playerUsingChestIndex].chest = -1;

            Main.chest[chest.Index] = null;
              } else {
            lock (this.WorldMetadata.ProtectorChests)
              this.WorldMetadata.ProtectorChests.Remove(chest.Location);
              }
        }
        // Modded version of Terraria's Original
        private bool TryToStoreItemInNearbyChest(TSPlayer player, Vector2 playerPosition, Item itemToStore, IChest chest)
        {
            float quickStackRange = this.Config.QuickStackNearbyRange * 16;

              if (Chest.isLocked(chest.Location.X, chest.Location.Y))
            return false;

              Vector2 vector2 = new Vector2((chest.Location.X * 16 + 16), (chest.Location.Y * 16 + 16));
              if ((vector2 - playerPosition).Length() > quickStackRange)
            return false;

              ProtectionEntry protection;
              if (this.ProtectionManager.CheckBlockAccess(player, chest.Location, false, out protection)) {
            bool isRefillChest = (protection != null && protection.RefillChestData != null);
            bool isTradeChest = (protection != null && protection.TradeChestData != null);

            if (!isRefillChest && !isTradeChest) {
              bool isBankChest = (protection != null && protection.BankChestKey != BankChestDataKey.Invalid);
              bool hasEmptySlot = false;
              bool containsSameItem = false;

              for (int i = 0; i < Chest.maxItems; i++) {
            ItemData chestItem = chest.Items[i];

            if (chestItem.Type <= 0 || chestItem.StackSize <= 0)
              hasEmptySlot = true;
            else if (itemToStore.netID == (int)chestItem.Type) {
              int remainingStack = itemToStore.maxStack - chestItem.StackSize;

              if (remainingStack > 0) {
                if (remainingStack > itemToStore.stack)
                  remainingStack = itemToStore.stack;

                itemToStore.stack = itemToStore.stack - remainingStack;
                chestItem.StackSize = chestItem.StackSize + remainingStack;
                if (isBankChest)
                  this.ServerMetadataHandler.EnqueueUpdateBankChestItem(protection.BankChestKey, i, chestItem);

                if (itemToStore.stack <= 0) {
                  itemToStore.SetDefaults();
                  return true;
                }
              }

              containsSameItem = true;
            }
              }
              if (containsSameItem && hasEmptySlot && itemToStore.stack > 0) {
            for (int i = 0; i < Chest.maxItems; i++) {
              ItemData chestItem = chest.Items[i];

              if (chestItem.Type == 0 || chestItem.StackSize == 0) {
                ItemData itemDataToStore = ItemData.FromItem(itemToStore);
                chest.Items[i] = itemDataToStore;

                if (isBankChest)
                  this.ServerMetadataHandler.EnqueueUpdateBankChestItem(protection.BankChestKey, i, itemDataToStore);

                itemToStore.SetDefaults();
                return true;
              }
            }
              }
            }
              }

              return false;
        }
        private bool IsChestInUse(TSPlayer player, IChest chest)
        {
            int usingPlayerIndex = -1;
              if (chest.IsWorldChest)
            usingPlayerIndex = Chest.UsingChest(chest.Index);

              return
            (usingPlayerIndex != -1 && usingPlayerIndex != player.Index) ||
            (this.ChestPlayerIndexDictionary.TryGetValue(chest.Location, out usingPlayerIndex) && usingPlayerIndex != player.Index);
        }
        private void InitTrade(TSPlayer player, IChest chest, ProtectionEntry protection)
        {
            TradeChestMetadata tradeChestData = protection.TradeChestData;
              Item sellItem = new Item();
              sellItem.netDefaults(tradeChestData.ItemToSellId);
              sellItem.stack = tradeChestData.ItemToSellAmount;
              Item payItem = new Item();
              payItem.netDefaults(tradeChestData.ItemToPayId);
              payItem.stack = tradeChestData.ItemToPayAmount;

              player.SendMessage($"This is a trade chest owned by {TShock.Utils.ColorTag(GetUserName(protection.Owner), Color.Red)}.", Color.LightGray);

              Inventory chestInventory = new Inventory(chest.Items, specificPrefixes: false);
              int stock = chestInventory.Amount(sellItem.netID);
              if (stock < sellItem.stack) {
            player.SendMessage($"It was trading {TShock.Utils.ItemTag(sellItem)} for {TShock.Utils.ItemTag(payItem)} but it is out of stock.", Color.LightGray);
            return;
              }

              player.SendMessage($"Click again to purchase {TShock.Utils.ItemTag(sellItem)} for {TShock.Utils.ItemTag(payItem)}", Color.LightGray);

              CommandInteraction interaction = this.StartOrResetCommandInteraction(player);

              interaction.ChestOpenCallback += (playerLocal, chestLocation) => {
            bool complete;

            bool wasThisChestHit = (chestLocation == chest.Location);
            if (wasThisChestHit) {
              // this is important to check, otherwise players could use trade chests to easily duplicate items
              if (!this.IsChestInUse(playerLocal, chest))
            this.PerformTrade(player, protection, chestInventory, sellItem, payItem);
              else
            player.SendErrorMessage("Another player is currently viewing the content of this chest.");

              complete = false;
            } else {
              this.HandleChestGetContents(playerLocal, chestLocation, skipInteractions: true);
              complete = true;
            }

            playerLocal.SendTileSquare(chest.Location);
            return new CommandInteractionResult {IsHandled = true, IsInteractionCompleted = complete};
              };
        }
        public bool TrySwapChestData(TSPlayer player, DPoint anyChestTileLocation, out IChest newChest)
        {
            newChest = null;

              if (TerrariaUtils.Tiles[anyChestTileLocation].type != TileID.Containers && TerrariaUtils.Tiles[anyChestTileLocation].type != TileID.Dressers) {
            player.SendErrorMessage("The selected tile is not a chest or dresser.");
            return false;
              }

              DPoint chestLocation = TerrariaUtils.Tiles.MeasureObject(anyChestTileLocation).OriginTileLocation;
              IChest chest = this.ChestManager.ChestFromLocation(chestLocation, player);
              if (chest == null)
            return false;

              ItemData[] content = new ItemData[Chest.maxItems];
              for (int i = 0; i < Chest.maxItems; i++)
            content[i] = chest.Items[i];

              if (chest.IsWorldChest) {
            lock (this.WorldMetadata.ProtectorChests) {
              bool isChestAvailable = this.WorldMetadata.ProtectorChests.Count < this.Config.MaxProtectorChests;
              if (!isChestAvailable) {
            player?.SendErrorMessage("The maximum of possible Protector chests has been reached.");
            return false;
              }

              int playerUsingChestIndex = Chest.UsingChest(chest.Index);
              if (playerUsingChestIndex != -1)
            Main.player[playerUsingChestIndex].chest = -1;

              Main.chest[chest.Index] = null;
              newChest = new ProtectorChestData(chestLocation, content);

              this.WorldMetadata.ProtectorChests.Add(chestLocation, (ProtectorChestData)newChest);

              //TSPlayer.All.SendData(PacketTypes.ChestName, string.Empty, chest.Index, chestLocation.X, chestLocation.Y);

              // Tell the client to remove the chest with the given index from its own chest array.
              TSPlayer.All.SendData(PacketTypes.TileKill, string.Empty, 1, chestLocation.X, chestLocation.Y, 0, chest.Index);
              TSPlayer.All.SendTileSquare(chestLocation.X, chestLocation.Y, 2);
              player?.SendWarningMessage("This chest is now a Protector chest.");
            }
              } else {
            int availableUnnamedChestIndex = -1;
            int availableEmptyChestIndex = -1;
            for (int i = 0; i < Main.chest.Length; i++) {
              if (i == ChestManager.DummyChestIndex)
            continue;

              Chest tChest = Main.chest[i];
              if (tChest == null) {
            availableEmptyChestIndex = i;
            break;
              } else if (availableUnnamedChestIndex == -1 && string.IsNullOrWhiteSpace(tChest.name)) {
            availableUnnamedChestIndex = i;
              }
            }

            // Prefer unset chests over unnamed chests.
            int availableChestIndex = availableEmptyChestIndex;
            if (availableChestIndex == -1)
              availableChestIndex = availableUnnamedChestIndex;

            bool isChestAvailable = (availableChestIndex != -1);
            if (!isChestAvailable) {
              player?.SendErrorMessage("The maximum of possible world chests has been reached.");
              return false;
            }

            lock (this.WorldMetadata.ProtectorChests)
              this.WorldMetadata.ProtectorChests.Remove(chestLocation);

            Chest availableChest = Main.chest[availableChestIndex];
            bool isExistingButUnnamedChest = (availableChest != null);
            if (isExistingButUnnamedChest) {
              if (!this.TrySwapChestData(null, new DPoint(availableChest.x, availableChest.y), out newChest))
            return false;
            }

            availableChest = Main.chest[availableChestIndex] = new Chest();
            availableChest.x = chestLocation.X;
            availableChest.y = chestLocation.Y;
            availableChest.item = content.Select(i => i.ToItem()).ToArray();

            newChest = new ChestAdapter(availableChestIndex, availableChest);
            player?.SendWarningMessage("This chest is now a world chest.");
              }

              return true;
        }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChestInventoryEvent"/> class with the specified
 /// <paramref name="chest"/>, <paramref name="player"/>, inventory <paramref name="slot"/>, and
 /// <paramref name="item"/>.
 /// </summary>
 /// <param name="chest">The chest whose inventory is being modified.</param>
 /// <param name="player">The player modifying the chest's inventory.</param>
 /// <param name="slot">The inventory slot being modified.</param>
 /// <param name="item">The item.</param>
 public ChestInventoryEvent(IChest chest, IPlayer player, int slot, ItemStack item) : base(chest)
 {
     Player = player ?? throw new ArgumentNullException(nameof(player));
     Slot   = slot;
     Item   = item;
 }
Esempio n. 16
0
        public bool EnsureBankChest(ProtectionEntry protection, bool resetContent)
        {
            if (protection.BankChestKey == BankChestDataKey.Invalid)
            {
                return(false);
            }

            BankChestMetadata bankChest = this.ServerMetadataHandler.EnqueueGetBankChestMetadata(protection.BankChestKey).Result;

            if (bankChest == null)
            {
                protection.BankChestKey = BankChestDataKey.Invalid;
                return(false);
            }

            IChest chest = this.ChestFromLocation(protection.TileLocation);

            if (chest == null)
            {
                protection.BankChestKey = BankChestDataKey.Invalid;
                return(false);
            }

            User owner = TShock.Users.GetUserByID(protection.Owner);

            if (owner == null)
            {
                this.DestroyChest(chest);

                protection.BankChestKey = BankChestDataKey.Invalid;
                return(false);
            }

            Group ownerGroup = TShock.Groups.GetGroupByName(owner.Group);

            if (ownerGroup != null)
            {
                if (protection.SharedUsers != null && !ownerGroup.HasPermission(ProtectorPlugin.BankChestShare_Permission))
                {
                    protection.SharedUsers.Clear();
                }
                if (protection.SharedGroups != null && !ownerGroup.HasPermission(ProtectorPlugin.BankChestShare_Permission))
                {
                    protection.SharedGroups.Clear();
                }
                if (protection.IsSharedWithEveryone && !ownerGroup.HasPermission(ProtectorPlugin.BankChestShare_Permission))
                {
                    protection.IsSharedWithEveryone = false;
                }
            }

            if (resetContent)
            {
                for (int i = 0; i < Chest.maxItems; i++)
                {
                    chest.SetItem(i, bankChest.Items[i]);
                }
            }

            return(true);
        }
Esempio n. 17
0
        public void DestroyChest(IChest chest)
        {
            if (chest != null) {
            int chestIndex;
            if (chest.IsWorldChest) {
              Main.chest[chest.Index] = null;
              chestIndex = chest.Index;
            } else {
              lock (this.WorldMetadata.ProtectorChests)
            this.WorldMetadata.ProtectorChests.Remove(chest.Location);

              chestIndex = ChestManager.DummyChestIndex;
            }

            TSPlayer.All.SendData(PacketTypes.TileKill, string.Empty, 1, chest.Location.X, chest.Location.Y, 0, chestIndex);
              }
        }
Esempio n. 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChestEvent"/> class with the specified
 /// <paramref name="chest"/>.
 /// </summary>
 /// <param name="chest">The chest involved in the event.</param>
 /// <exception cref="ArgumentNullException"><paramref name="chest"/> is <see langword="null"/>.</exception>
 protected ChestEvent(IChest chest)
 {
     Chest = chest ?? throw new ArgumentNullException(nameof(chest));
 }
Esempio n. 19
0
        public void SetUpBankChest(TSPlayer player, DPoint tileLocation, int bankChestIndex, bool checkPermissions = false)
        {
            Contract.Requires <ArgumentNullException>(player != null);
            Contract.Requires <ArgumentException>(TerrariaUtils.Tiles[tileLocation] != null, "tileLocation");
            Contract.Requires <ArgumentException>(TerrariaUtils.Tiles[tileLocation].active(), "tileLocation");
            Contract.Requires <ArgumentOutOfRangeException>(bankChestIndex >= 1, "bankChestIndex");

            Tile      tile      = TerrariaUtils.Tiles[tileLocation];
            BlockType blockType = (BlockType)tile.type;

            if (blockType != BlockType.Chest && blockType != BlockType.Dresser)
            {
                throw new InvalidBlockTypeException(blockType);
            }

            if (checkPermissions && !player.Group.HasPermission(ProtectorPlugin.SetBankChests_Permission))
            {
                throw new MissingPermissionException(ProtectorPlugin.SetBankChests_Permission);
            }

            if (
                checkPermissions && !player.Group.HasPermission(ProtectorPlugin.NoBankChestLimits_Permision)
                )
            {
                if (bankChestIndex > this.Config.MaxBankChestsPerPlayer)
                {
                    throw new ArgumentOutOfRangeException("bankChestIndex", this.Config.MaxBankChestsPerPlayer, "Global bank chest limit reached.");
                }

                int byGroupLimit;
                if (
                    this.Config.MaxBankChests.TryGetValue(player.Group.Name, out byGroupLimit) &&
                    bankChestIndex > byGroupLimit
                    )
                {
                    throw new ArgumentOutOfRangeException("bankChestIndex", byGroupLimit, "Group bank chest limit reached.");
                }
            }

            DPoint          chestLocation = TerrariaUtils.Tiles.MeasureObject(tileLocation).OriginTileLocation;
            ProtectionEntry protection;

            lock (this.WorldMetadata.Protections)
                if (!this.WorldMetadata.Protections.TryGetValue(chestLocation, out protection))
                {
                    throw new NoProtectionException(chestLocation);
                }

            if (protection.RefillChestData != null)
            {
                throw new ChestIncompatibilityException();
            }

            IChest chest = this.ChestFromLocation(chestLocation);

            if (chest == null)
            {
                throw new NoChestDataException(chestLocation);
            }

            if (protection.BankChestKey != BankChestDataKey.Invalid)
            {
                throw new ChestTypeAlreadyDefinedException();
            }

            BankChestDataKey bankChestKey = new BankChestDataKey(player.User.ID, bankChestIndex);

            lock (this.WorldMetadata.Protections) {
                if (this.WorldMetadata.Protections.Values.Count(p => p.BankChestKey == bankChestKey) > 0)
                {
                    throw new BankChestAlreadyInstancedException();
                }
            }

            if (checkPermissions && !player.Group.HasPermission(ProtectorPlugin.BankChestShare_Permission))
            {
                protection.Unshare();
            }

            BankChestMetadata bankChest = this.ServerMetadataHandler.EnqueueGetBankChestMetadata(bankChestKey).Result;

            if (bankChest == null)
            {
                bankChest = new BankChestMetadata();
                for (int i = 0; i < Chest.maxItems; i++)
                {
                    bankChest.Items[i] = chest[i];
                }

                this.ServerMetadataHandler.EnqueueAddOrUpdateBankChest(bankChestKey, bankChest);
            }
            else
            {
                for (int i = 0; i < Chest.maxItems; i++)
                {
                    if (chest[i].StackSize > 0)
                    {
                        throw new ChestNotEmptyException(chestLocation);
                    }
                }

                for (int i = 0; i < Chest.maxItems; i++)
                {
                    chest.SetItem(i, bankChest.Items[i]);
                }
            }

            protection.BankChestKey = bankChestKey;
        }
        public void SetUpTradeChest(TSPlayer player, DPoint tileLocation, int sellAmount, int sellItemId, int payAmount, object payItemIdOrGroup, int lootLimit = 0, bool checkPermissions = false)
        {
            if (player == null)
            {
                throw new ArgumentNullException();
            }
            if (!(TerrariaUtils.Tiles[tileLocation] != null))
            {
                throw new ArgumentException("tileLocation");
            }
            if (!(TerrariaUtils.Tiles[tileLocation].active()))
            {
                throw new ArgumentException("tileLocation");
            }
            if (!(sellAmount > 0))
            {
                throw new ArgumentOutOfRangeException("sellAmount");
            }
            if (!(payAmount > 0))
            {
                throw new ArgumentOutOfRangeException("payAmount");
            }

            Item itemInfo = new Item();

            itemInfo.netDefaults(sellItemId);
            if (sellAmount > itemInfo.maxStack)
            {
                throw new ArgumentOutOfRangeException(nameof(sellAmount));
            }

            bool isPayItemGroup = payItemIdOrGroup is string;

            if (!isPayItemGroup)
            {
                itemInfo.netDefaults((int)payItemIdOrGroup);
                if (payAmount > itemInfo.maxStack)
                {
                    throw new ArgumentOutOfRangeException(nameof(payAmount));
                }
            }

            ITile tile = TerrariaUtils.Tiles[tileLocation];

            if (tile.type != TileID.Containers && tile.type != TileID.Containers2 && tile.type != TileID.Dressers)
            {
                throw new InvalidBlockTypeException(tile.type);
            }

            if (checkPermissions && !player.Group.HasPermission(ProtectorPlugin.SetTradeChests_Permission))
            {
                throw new MissingPermissionException(ProtectorPlugin.SetTradeChests_Permission);
            }

            DPoint          chestLocation = TerrariaUtils.Tiles.MeasureObject(tileLocation).OriginTileLocation;
            ProtectionEntry protection;

            lock (this.WorldMetadata.Protections)
                if (!this.WorldMetadata.Protections.TryGetValue(chestLocation, out protection))
                {
                    throw new NoProtectionException(chestLocation);
                }

            if (protection.BankChestKey != BankChestDataKey.Invalid)
            {
                throw new ChestIncompatibilityException();
            }

            IChest chest = this.ChestFromLocation(chestLocation);

            if (chest == null)
            {
                throw new NoChestDataException(chestLocation);
            }

            bool isNewTradeChest = (protection.TradeChestData == null);

            if (isNewTradeChest && checkPermissions && this.CooperationHandler.IsSeconomyAvailable && !player.Group.HasPermission(ProtectorPlugin.FreeTradeChests_Permission))
            {
        #if SEconomy
                if (this.CooperationHandler.Seconomy_GetBalance(player.Name) < this.Config.TradeChestPayment)
                {
                    throw new PaymentException(this.Config.TradeChestPayment);
                }

                this.CooperationHandler.Seconomy_TransferToWorld(player.Name, this.Config.TradeChestPayment, "Trade Chest", "Setup Price");
        #endif
            }

            protection.TradeChestData = protection.TradeChestData ?? new TradeChestMetadata();
            protection.TradeChestData.ItemToSellAmount = sellAmount;
            if (protection.TradeChestData.ItemToSellId != sellItemId)
            {
                protection.TradeChestData.LootersTable.Clear();
            }

            protection.TradeChestData.ItemToSellId    = sellItemId;
            protection.TradeChestData.ItemToPayAmount = payAmount;
            if (isPayItemGroup)
            {
                protection.TradeChestData.ItemToPayGroup = (payItemIdOrGroup as string).ToLowerInvariant();
            }
            else
            {
                protection.TradeChestData.ItemToPayId = (int)payItemIdOrGroup;
            }
            protection.TradeChestData.LootLimitPerPlayer = lootLimit;

            // TODO: uncomment
            //this.PluginTrace.WriteLineVerbose($"{player.Name} just setup a trade chest selling {sellAmount}x {sellItemId} for {payAmount}x {payItemId} with a limit of {lootLimit} at {tileLocation}");
        }
Esempio n. 21
0
        public bool TryRefillChest(IChest chest, RefillChestMetadata refillChestData)
        {
            for (int i = 0; i < Chest.maxItems; i++)
            chest.Items[i] = refillChestData.RefillItems[i];

              if (
            refillChestData.AutoLock && refillChestData.RefillTime != TimeSpan.Zero &&
            !TerrariaUtils.Tiles.IsChestLocked(TerrariaUtils.Tiles[chest.Location])
              ) {
            TerrariaUtils.Tiles.LockChest(chest.Location);
              }

              return true;
        }
Esempio n. 22
0
        /// <returns>
        ///   A <c>bool</c> which is <c>false</c> if a refill chest already existed at the given location and thus just its refill
        ///   time was set or <c>true</c> if a new refill chest was actually defined.
        /// </returns>
        public bool SetUpRefillChest(
            TSPlayer player, DPoint tileLocation, TimeSpan?refillTime, bool?oneLootPerPlayer = null, int?lootLimit = null,
            bool?autoLock = null, bool?autoEmpty = null, bool fairLoot = false, bool checkPermissions = false
            )
        {
            Contract.Requires <ArgumentNullException>(player != null);
            Contract.Requires <ArgumentException>(TerrariaUtils.Tiles[tileLocation] != null, "tileLocation");
            Contract.Requires <ArgumentException>(TerrariaUtils.Tiles[tileLocation].active(), "tileLocation");
            Contract.Requires <ArgumentOutOfRangeException>(lootLimit == null || lootLimit >= -1);

            Tile      tile      = TerrariaUtils.Tiles[tileLocation];
            BlockType blockType = (BlockType)tile.type;

            if (blockType != BlockType.Chest && blockType != BlockType.Dresser)
            {
                throw new InvalidBlockTypeException(blockType);
            }

            if (checkPermissions && !player.Group.HasPermission(ProtectorPlugin.SetRefillChests_Permission))
            {
                throw new MissingPermissionException(ProtectorPlugin.SetRefillChests_Permission);
            }

            DPoint          chestLocation = TerrariaUtils.Tiles.MeasureObject(tileLocation).OriginTileLocation;
            ProtectionEntry protection;

            lock (this.WorldMetadata.Protections)
                if (!this.WorldMetadata.Protections.TryGetValue(chestLocation, out protection))
                {
                    throw new NoProtectionException(chestLocation);
                }

            if (protection.BankChestKey != BankChestDataKey.Invalid)
            {
                throw new ChestIncompatibilityException();
            }

            RefillChestMetadata refillChestData;

            if (protection.RefillChestData != null)
            {
                refillChestData = protection.RefillChestData;

                if (refillTime != null)
                {
                    refillChestData.RefillTimer.TimeSpan = refillTime.Value;
                }
                if (oneLootPerPlayer != null)
                {
                    refillChestData.OneLootPerPlayer = oneLootPerPlayer.Value;
                }
                if (lootLimit != null)
                {
                    refillChestData.RemainingLoots = lootLimit.Value;
                }
                if (autoLock != null)
                {
                    refillChestData.AutoLock = autoLock.Value;
                }
                if (autoEmpty != null)
                {
                    refillChestData.AutoEmpty = autoEmpty.Value;
                }

                if (refillChestData.OneLootPerPlayer || refillChestData.RemainingLoots > 0)
                {
                    if (refillChestData.Looters == null)
                    {
                        refillChestData.Looters = new Collection <int>();
                    }
                    else
                    {
                        refillChestData.Looters = null;
                    }
                }

                this.RefillTimers.RemoveTimer(refillChestData.RefillTimer);

                return(false);
            }

            IChest chest = this.ChestFromLocation(chestLocation);

            if (chest == null)
            {
                throw new NoChestDataException(chestLocation);
            }

            TimeSpan actualRefillTime = TimeSpan.Zero;

            if (refillTime != null)
            {
                actualRefillTime = refillTime.Value;
            }

            refillChestData             = new RefillChestMetadata(player.User.ID);
            refillChestData.RefillTimer = new Timer(actualRefillTime, refillChestData, this.RefillTimerCallbackHandler);
            if (oneLootPerPlayer != null)
            {
                refillChestData.OneLootPerPlayer = oneLootPerPlayer.Value;
            }
            if (lootLimit != null)
            {
                refillChestData.RemainingLoots = lootLimit.Value;
            }

            if (refillChestData.OneLootPerPlayer || refillChestData.RemainingLoots > 0)
            {
                refillChestData.Looters = new Collection <int>();
            }
            else
            {
                refillChestData.Looters = null;
            }

            if (autoLock != null)
            {
                refillChestData.AutoLock = autoLock.Value;
            }

            if (autoEmpty != null)
            {
                refillChestData.AutoEmpty = autoEmpty.Value;
            }

            bool fairLootPutItem = fairLoot;

            for (int i = 0; i < Chest.maxItems; i++)
            {
                ItemData item = chest[i];
                if (item.StackSize == 0 && fairLootPutItem)
                {
                    try {
                        bool isLocked;
                        item.Type = TerrariaUtils.Tiles.GetItemTypeFromChestType(TerrariaUtils.Tiles.GetChestStyle(tile, out isLocked));

                        item.StackSize = 1;
                        chest.SetItem(i, item);
                    } catch (ArgumentException) {}

                    fairLootPutItem = false;
                }

                refillChestData.RefillItems[i] = item;
            }

            protection.RefillChestData = refillChestData;

            return(true);
        }
Esempio n. 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChestOpenEvent"/> class with the specified
 /// <paramref name="chest"/> and <paramref name="player"/>.
 /// </summary>
 /// <param name="chest">The chest being opened.</param>
 /// <param name="player">The player opening the chest.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="chest"/> or <paramref name="player"/> are <see langword="null"/>.
 /// </exception>
 public ChestOpenEvent(IChest chest, IPlayer player) : base(chest)
 {
     Player = player ?? throw new ArgumentNullException(nameof(player));
 }
Esempio n. 24
0
 public void SetChest(IChest chest)
 {
     this.chest = chest;
 }