public InventoryItem GetInventoryItem(int itemId) { InventoryItemDAO aDao = new InventoryItemDAO(); InventoryItem aInventoryItem = new InventoryItem(); aInventoryItem = aDao.GetInventoryItem(itemId); return aInventoryItem; }
void Start() { INVENTORY = new InventoryItem[InventorySize]; for(int i=0;i<INVENTORY.Length;i++){ INVENTORY[i] = new InventoryItem(); } }
public Stock GetStockByItemidFrominventory_kitchen_stock(InventoryItem item) { Stock stock = new Stock(); StockDAO aDao = new StockDAO(); stock = aDao.GetStockByItemidFrominventory_kitchen_stock(item.ItemId); return stock; }
private void btnSearch_Click(object sender, EventArgs e) { try { string partNumber = txtRestPartNumber.Text.Trim().ToString(); int version = Convert.ToInt32(txtRestVersion.Text.Trim().ToString()); InventoryItem item = new InventoryItem(); item.PartNumber = partNumber; item.Version = version; List<LocationQty> listLocations = PartNumberRepository.GetPartNumbersByPartNumberVersion(item); if (listLocations.Count == 0) { statusLabel.ForeColor = Color.Red; statusLabel.Text = "No PartNumber Locations availlable"; MessageBox.Show("Quantity is empty for Given PartNumber and Version","Search - PartNumber Operation",MessageBoxButtons.OK,MessageBoxIcon.Warning); } int totalQty = listLocations.Sum(x => x.Quantity); listLocations.Add(new LocationQty("Total :- ", totalQty)); dgvSearchGrid.DataSource = listLocations; } catch (Exception exp) { objLogger.LogMsg(LogModes.UI, LogLevel.ERROR, "Error while Searching Location vise Part Numbers - " + exp.Message + " StackTrace:- " + exp.StackTrace); statusLabel.ForeColor = Color.Red; statusLabel.Text = "Error while Searching Location vise Part Numbers"; MessageBox.Show("Error while Searching Location vise Part Numbers", "Searching - Part Number Locations", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public bool AddItem(Room room, InventoryItem item, out InventoryItem droppedItem, ITextProcessor textProcessor) { Guard.NullParameter(room, () => room); Guard.NullParameter(item, () => item); return AddItem(room.Name, item, out droppedItem, textProcessor); }
/* * returns true if inventory contains at least [quantity] of [item] */ public bool Contains(InventoryItem item, int quantity) { int index = GetIndex(item); if (index < 0) return false; if (items[index].amount < quantity) return false; return true; }
public void Init() { player1Observer = new MockObserver("Player1 Observer"); fullPlayerObserver = new MockObserver("FullPlayer Observer"); player1InventoryObserver = new MockObserver("Player 1 Inventory Observer"); fullPlayerInventoryObserver = new MockObserver("FullPlayer Inventory Observer"); player1 = new Player ("Player1", Gender.FEMALE, "Eve2", new Vector2 (0, 0)); player1.AddObserver(player1Observer); fullPlayer = new Player ("Ollie", Gender.MALE, "Evan1", Vector2.zero); fullPlayer.InitialiseInventory (20); fullPlayer.AddObserver(fullPlayerObserver); fullPlayer.Inventory.AddObserver(fullPlayerInventoryObserver); for (int i = 0; i < 20; i++) { InventoryItem item = new InventoryItem(); item.ItemName = "Item" + i; item.ItemId = i; item.ItemType = ItemType.RUBBISH; item.ItemDescription = string.Empty; fullPlayer.AddItem(item); } tool1 = new MockTool("Tool1"); tool2 = new MockTool("Tool2"); tool3 = new MockTool("Tool3"); fullPlayer.AddTool(tool1); fullPlayer.AddTool(tool2); fullPlayer.AddTool(tool3); }
public void SetInventoryItem(InventoryItem it) { if(it==null) return; this.it = it; Sprite.spriteName = it.Inventory.Icon; }
public void LoseItem(InventoryItem item, int quantity = 1) { if(! HasItem(item.Name)) throw new ArgumentException("Cannot lose item " + item.Name + " as there are already none!"); item.Quantity -= quantity; }
internal InventoryImage( InventoryManager manager, InventoryItem ii ) : base(manager, ii._Name, ii._Description, ii._FolderID, ii._InvType, ii._Type, ii._CreatorID) { if( (ii.InvType != 0) || (ii.Type != Asset.ASSET_TYPE_IMAGE) ) { throw new Exception("The InventoryItem cannot be converted to a Image/Texture, wrong InvType/Type."); } this.iManager = manager; this._Asset = ii._Asset; this._AssetID = ii._AssetID; this._BaseMask = ii._BaseMask; this._CRC = ii._CRC; this._CreationDate = ii._CreationDate; this._EveryoneMask = ii._EveryoneMask; this._Flags = ii._Flags; this._GroupID = ii._GroupID; this._GroupMask = ii._GroupMask; this._GroupOwned = ii._GroupOwned; this._InvType = ii._InvType; this._NextOwnerMask = ii._NextOwnerMask; this._OwnerID = ii._OwnerID; this._OwnerMask = ii._OwnerMask; this._SalePrice = ii._SalePrice; this._SaleType = ii._SaleType; this._Type = ii._Type; }
public void TestAddItemToEmptyInventory() { InventoryItem newItem = new InventoryItem(); emptyInventory.AddItem(newItem); Assert.That(emptyInventory.Items.Count == 1); Assert.That(emptyInventory.Items[0] == newItem); }
public void addItemRecord() { NetSuiteService service = new NetSuiteService(); service.CookieContainer = new CookieContainer(); NetsuiteUser user = new NetsuiteUser("3451682", "*****@*****.**", "1026", "tridenT168"); Passport passport = user.prepare(user); Status status = service.login(passport).status; string itemName = this.ItemName; SearchStringField objItemName = new SearchStringField(); objItemName.searchValue = itemName; objItemName.@operator = SearchStringFieldOperator.@is; objItemName.operatorSpecified = true; ItemSearch objItemSearch = new ItemSearch(); objItemSearch.basic = new ItemSearchBasic(); objItemSearch.basic.itemId = objItemName; SearchPreferences searchPreferences = new SearchPreferences(); searchPreferences.bodyFieldsOnly = false; service.searchPreferences = searchPreferences; SearchResult objItemResult = service.search(objItemSearch); if (objItemResult.status.isSuccess != true) throw new Exception("Cannot find Item " + itemName + " " + objItemResult.status.statusDetail[0].message); if (objItemResult.recordList.Count() != 1) throw new Exception("More than one item found for item " + itemName); InventoryItem iRecord = new InventoryItem(); iRecord = ((InventoryItem)objItemResult.recordList[0]); this.itemRecord = new InventoryItem(); this.itemRecord=iRecord; }
public List<InventoryItem> GetAllItem() { List<InventoryItem> aItems = new List<InventoryItem>(); try { this.OpenConnection(); string sqlComm = String.Format(SqlQueries.GetQuery(Query.GetAllItem)); IDataReader aReader = this.ExecuteReader(sqlComm); if (aReader != null) { while (aReader.Read()) { InventoryItem aItem = new InventoryItem(); aItem = ItemReader(aReader); aItems.Add(aItem); } } } catch (Exception ex) { MessageBox.Show(ex + " Should be input missing"); } finally { this.CloseConnection(); } return aItems; }
public InventoryItem GetInventoryItem(int itemId) { InventoryItem aItem = new InventoryItem(); try { this.OpenConnection(); string sqlComm = String.Format(SqlQueries.GetQuery(Query.GetInventoryItem), itemId); IDataReader aReader = this.ExecuteReader(sqlComm); if (aReader != null) { while (aReader.Read()) { aItem = ItemReader(aReader); } } } catch (Exception ex) { MessageBox.Show(ex + " Should be input missing"); } finally { this.CloseConnection(); } return aItem; }
public TransactionForm() { InitializeComponent(); // this.AcceptButton = saveTransactionbutton; transactionActionlabel.Visible = false; List<InventoryCategory> aaList = new List<InventoryCategory>(); InventoryCategoryBLL aBll = new InventoryCategoryBLL(); aaList = aBll.GetAllCategory(); categoryNamecomboBox.DataSource = aaList; categoryNamecomboBox.DisplayMember = "CategoryName"; categoryNamecomboBox.ValueMember = "CategoryId"; //findout item try { InventoryItemBLL aaBll = new InventoryItemBLL(); List<InventoryItem> aList = new List<InventoryItem>(); Int32 category = Convert.ToInt32(categoryNamecomboBox.SelectedValue); aList = aaBll.GetItemByCategory(category); itemNamecomboBox.DataSource = aList; itemNamecomboBox.DisplayMember = "ItemName"; itemNamecomboBox.ValueMember = "ItemId"; InventoryItem aItem = new InventoryItem(); aItem = (InventoryItem)itemNamecomboBox.SelectedItem; unittypelabel.Text = aItem.UnitName; } catch (Exception) { } // This used for package activation // BookedTransactionTypecomboboxForBusiness();// when Businees Package is active BookedTransactionTypecomboboxForProfessional();// when When Professional Package is active }
public override void DrawMe() { InventoryBox.DrawMe(); if(ItemGrid.IsClicked()) { _maestro.PlayOneShot(ButtonSound); _currentItem = (InventoryItem) ItemGrid.SelectedObject; LoadItemInCommandBar(_currentItem); } CommandBar.DrawMe(); ItemInfoLabel.DrawMe(); if(EquipItemButton.IsClicked()) { _maestro.PlayOneShot(ButtonSound); _controller.EquipItem(_currentItem); } if(UseItemButton.IsClicked()) { _maestro.PlayOneShot(ButtonSound); _controller.UseItem(_currentItem); } }
//-------------------------------------------------------------------------- // skills //-------------------------------------------------------------------------- public static void ItemTriggered(InventoryItem item) { if (Time.time - _triggerTime > 1) { _triggeredItems.Clear(); } _triggeredItems.Add(item); _triggerTime = Time.time; foreach (Skill skill in SkillDatabase.Skills) { // 1. Compare the Count if (skill._triggerSequence.Count == _triggeredItems.Count) { // 2. Compare the sequence bool match = true; for (int i=0; i<skill._triggerSequence.Count; i++) { if (skill._triggerSequence[i] !=_triggeredItems[i]) { match = false; break; } } if (match) { PlayerController._playerController.UseSkill(skill); _triggeredItems.Clear(); return; } } } }
public void LoadItemInfo(InventoryItem item) { if(icon != null) { GameObject atlas = Resources.Load(item.rpgItem.AtlasName) as GameObject; icon.atlas = atlas.GetComponent<UIAtlas>(); icon.spriteName = item.rpgItem.IconPath; } if(nameLabel != null) nameLabel.text = item.rpgItem.Name; for (int i = 0; i < stars.Length; i++) { stars[i].SetActive(false); } if(item.rpgItem.IsUpgradeable) { for (int i = 0; i < item.Level; i++) { stars[i].SetActive(true); } } if(item.IsItemEquippable && tickIcon != null) { if(item.IsItemEquipped) { tickIcon.SetActive(true); } else { tickIcon.SetActive(false); } } else { if(tickIcon != null) tickIcon.SetActive(false); } if(rarityLabel != null) { rarityLabel.color = GUIManager.Instance.GetRarityColor(item.rpgItem.Rarity); rarityLabel.text = item.rpgItem.Rarity.ToString(); } if(quantityLabel != null) quantityLabel.text = item.CurrentAmount.ToString(); if(currencyIcon != null) { if(item.rpgItem.BuyCurrency == BuyCurrencyType.CitizenPoints) currencyIcon.spriteName = GeneralData.citizenIconPath; else if(item.rpgItem.BuyCurrency == BuyCurrencyType.Magnets) currencyIcon.spriteName = GeneralData.magnetIconPath; else if(item.rpgItem.BuyCurrency == BuyCurrencyType.Coins) currencyIcon.spriteName = GeneralData.coinIconPath; } if(priceLabel != null) priceLabel.text = item.rpgItem.BuyValue.ToString(); }
public void Request(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.REQUESTED; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
public bool DoYouHaveSpaceForThisItem(InventoryItem itemToHave) { if (itemToHave == null) return false; if(itemToHave.rpgItem.Stackable) { foreach(InventoryItem item in Items) { if(item.UniqueItemId== itemToHave.UniqueItemId && item.Level == itemToHave.Level ) return true; } if(!IsFullInventory) return true; else return false; } else { if(maximumItems - Items.Count >= 1) return true; else return false; } }
public void Receive(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.IN_STOCK; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
public void RecordAsLost(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.RECORDED_AS_LOST; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
public void Order(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.ORDERED; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
public void Recall(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.RECALLED; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
/* // Confirm InventoryUpdate CRC uint test = libsecondlife.Packets.InventoryPackets.InventoryUpdateCRC ( (int)1159214416 , (byte)0 , (sbyte)7 , (sbyte)7 , (LLUUID)"00000000000000000000000000000000" , (LLUUID)"00000000000000000000000000000000" , (int)10 , (LLUUID)"25472683cb324516904a6cd0ecabf128" , (LLUUID)"25472683cb324516904a6cd0ecabf128" , (LLUUID)"77364021f09f13dfb692f036be53b9e2" , (LLUUID)"a4947fc066c247518d9854aaf90097f4" , (uint)0 , (uint)0 , (uint)2147483647 , (uint)0 , (uint)2147483647 ); if( test != (uint)895206313 ) { Console.WriteLine("CRC Generation is no longer correct."); return; } */ public static uint InventoryUpdateCRC(InventoryItem iitem) { uint CRC = 0; /* IDs */ CRC += iitem.AssetID.CRC(); // AssetID CRC += iitem.FolderID.CRC(); // FolderID CRC += iitem.ItemID == null ? LLUUID.Zero.CRC() : iitem.ItemID.CRC(); // ItemID /* Permission stuff */ CRC += iitem.CreatorID.CRC(); // CreatorID CRC += iitem.OwnerID.CRC(); // OwnerID CRC += iitem.GroupID.CRC(); // GroupID /* CRC += another 4 words which always seem to be zero -- unclear if this is a LLUUID or what */ CRC += iitem.OwnerMask; //owner_mask; // Either owner_mask or next_owner_mask may need to be CRC += iitem.NextOwnerMask; //next_owner_mask; // switched with base_mask -- 2 values go here and in my CRC += iitem.EveryoneMask; //everyone_mask; // study item, the three were identical. CRC += iitem.GroupMask; //group_mask; /* The rest of the CRC fields */ CRC += iitem.Flags; // Flags CRC += (uint)iitem.InvType; // InvType CRC += (uint)iitem.Type; // Type CRC += (uint)iitem.CreationDate; // CreationDate CRC += (uint)iitem.SalePrice; // SalePrice CRC += (uint)((uint)iitem.SaleType * 0x07073096); // SaleType return CRC; }
public void AddShopItem(InventoryItem item) { var spriteRenderer = GetComponent<SpriteRenderer>(); spriteRenderer.sprite = item.Sprite; spriteRenderer.transform.localScale = item.Scale; Item = item; }
//! Loads player data as json string to PlayerPrefs \todo pseudo code -> code public List<InventoryItem> LoadPlayerInventory() { //create list of inventory items to hold the inventory to return List <InventoryItem> inventoryLoad = new List <InventoryItem>(); //if the inventory key doesnt exist return the empty list if(!PlayerPrefs.HasKey("PlayerInventory")) { return inventoryLoad; } //obtain the inventory string from the playerprefs and fill the list of inventory items JSONNode loadedPlayerInventory = JSONClass.Parse(PlayerPrefs.GetString("PlayerInventory")); List<string> keyList = loadedPlayerInventory.Keys.ToList (); for(int count = 0; count < keyList.Count; count++) { //loads the inventory in the order the setter functions appear in the inventory item script string tempName = loadedPlayerInventory["Inventory"][count][0]; int tempType = loadedPlayerInventory["Inventory"][count][1].AsInt; string tempDescription = loadedPlayerInventory["Inventory"][count][2]; int tempValue = loadedPlayerInventory["Inventory"][count][3].AsInt; int tempAmount = loadedPlayerInventory["Inventory"][count][4].AsInt; int tempID = loadedPlayerInventory["Inventory"][count][5].AsInt; //create the inventory item and add it to the list InventoryItem new_item = new InventoryItem(tempName, tempID, tempDescription, tempValue, tempAmount, tempType); inventoryLoad.Add(new_item); } //return the list of created inventory items return inventoryLoad; }
public void Distribute(InventoryItem inventoryItem) { inventoryItem.Status = Constants.Inventory.DISTRIBUTED; inventoryItem.StatusLastChanged = DateTime.Now; this.Save(inventoryItem); }
public void Show(InventoryItem it,InventoryItemUI itUI,bool isleft=true) { this.it = it; this.itUI = itUI; gameObject.SetActive(true); Vector3 pos = transform.localPosition; this.isLeft = isleft; if(isleft) { transform.localPosition = new Vector3(-Mathf.Abs(pos.x),pos.y,pos.z); buttonnameLbel.text = "装备"; upgradeBtn.isEnabled = false; } else { transform.localPosition = new Vector3(Mathf.Abs(pos.x), pos.y, pos.z); buttonnameLbel.text = "卸下"; upgradeBtn.isEnabled = true; } icon.spriteName = it.Inventory.Icon; nameLabel.text = it.Inventory.Name; qualityLabel.text = it.Inventory.Quality.ToString(); lifeLabel.text = it.Inventory.HP.ToString(); damageLabel.text = it.Inventory.Damage.ToString(); powerLabel.text = it.Inventory.Power.ToString(); desLabel.text = it.Inventory.Des.ToString(); levelLabel.text = it.Level.ToString(); }
private void button3_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtLocation.Text)) { InventoryItem item = new InventoryItem(); item.Location = txtLocation.Text; bool locationExist = PartNumberRepository.CheckPartLocaionExist(item); if (!locationExist) { bool addStatus = PartNumberRepository.AddLocationColumn(txtLocation.Text); if(addStatus) MessageBox.Show("Location Added successfully", "Location", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); else { MessageBox.Show("Unable to Add Location", "Location", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } else { MessageBox.Show("Location already exist", "Location", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } else { MessageBox.Show("Location should not be empty", "Location", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } txtLocation.Clear(); }
public override void ReadData(ESPReader reader, long dataEnd) { while (reader.BaseStream.Position < dataEnd) { string subTag = reader.PeekTag(); switch (subTag) { case "EDID": if (EditorID == null) { EditorID = new SimpleSubrecord <String>(); } EditorID.ReadBinary(reader); break; case "OBND": if (ObjectBounds == null) { ObjectBounds = new ObjectBounds(); } ObjectBounds.ReadBinary(reader); break; case "FULL": if (Name == null) { Name = new SimpleSubrecord <String>(); } Name.ReadBinary(reader); break; case "MODL": if (Model == null) { Model = new Model(); } Model.ReadBinary(reader); break; case "ACBS": if (BaseStats == null) { BaseStats = new NPCBaseStats(); } BaseStats.ReadBinary(reader); break; case "SNAM": if (Factions == null) { Factions = new List <FactionMembership>(); } FactionMembership tempSNAM = new FactionMembership(); tempSNAM.ReadBinary(reader); Factions.Add(tempSNAM); break; case "INAM": if (DeathItem == null) { DeathItem = new RecordReference(); } DeathItem.ReadBinary(reader); break; case "VTCK": if (VoiceType == null) { VoiceType = new RecordReference(); } VoiceType.ReadBinary(reader); break; case "TPLT": if (Template == null) { Template = new RecordReference(); } Template.ReadBinary(reader); break; case "RNAM": if (Race == null) { Race = new RecordReference(); } Race.ReadBinary(reader); break; case "SPLO": if (ActorEffects == null) { ActorEffects = new List <RecordReference>(); } RecordReference tempSPLO = new RecordReference(); tempSPLO.ReadBinary(reader); ActorEffects.Add(tempSPLO); break; case "EITM": if (UnarmedAttackEffect == null) { UnarmedAttackEffect = new RecordReference(); } UnarmedAttackEffect.ReadBinary(reader); break; case "EAMT": if (UnarmedAttackAnimation == null) { UnarmedAttackAnimation = new SimpleSubrecord <UInt16>(); } UnarmedAttackAnimation.ReadBinary(reader); break; case "DEST": if (Destructable == null) { Destructable = new Destructable(); } Destructable.ReadBinary(reader); break; case "SCRI": if (Script == null) { Script = new RecordReference(); } Script.ReadBinary(reader); break; case "CNTO": if (Contents == null) { Contents = new List <InventoryItem>(); } InventoryItem tempCNTO = new InventoryItem(); tempCNTO.ReadBinary(reader); Contents.Add(tempCNTO); break; case "AIDT": if (AIData == null) { AIData = new AIData(); } AIData.ReadBinary(reader); break; case "PKID": if (Packages == null) { Packages = new List <RecordReference>(); } RecordReference tempPKID = new RecordReference(); tempPKID.ReadBinary(reader); Packages.Add(tempPKID); break; case "CNAM": if (Class == null) { Class = new RecordReference(); } Class.ReadBinary(reader); break; case "DATA": if (Data == null) { Data = new NPCData(); } Data.ReadBinary(reader); break; case "DNAM": if (Skills == null) { Skills = new NPCSkills(); } Skills.ReadBinary(reader); break; case "PNAM": if (HeadParts == null) { HeadParts = new List <RecordReference>(); } RecordReference tempPNAM = new RecordReference(); tempPNAM.ReadBinary(reader); HeadParts.Add(tempPNAM); break; case "HNAM": if (HairType == null) { HairType = new RecordReference(); } HairType.ReadBinary(reader); break; case "LNAM": if (HairLength == null) { HairLength = new SimpleSubrecord <Single>(); } HairLength.ReadBinary(reader); break; case "ENAM": if (Eyes == null) { Eyes = new RecordReference(); } Eyes.ReadBinary(reader); break; case "HCLR": if (HairColor == null) { HairColor = new SimpleSubrecord <Color>(); } HairColor.ReadBinary(reader); break; case "ZNAM": if (CombatStyle == null) { CombatStyle = new RecordReference(); } CombatStyle.ReadBinary(reader); break; case "NAM4": if (ImpactMaterialType == null) { ImpactMaterialType = new SimpleSubrecord <MaterialTypeUInt>(); } ImpactMaterialType.ReadBinary(reader); break; case "FGGS": if (FaceGenGeometrySymmetric == null) { FaceGenGeometrySymmetric = new SimpleSubrecord <Byte[]>(); } FaceGenGeometrySymmetric.ReadBinary(reader); break; case "FGGA": if (FaceGenGeometryAsymmetric == null) { FaceGenGeometryAsymmetric = new SimpleSubrecord <Byte[]>(); } FaceGenGeometryAsymmetric.ReadBinary(reader); break; case "FGTS": if (FaceGenTexture == null) { FaceGenTexture = new SimpleSubrecord <Byte[]>(); } FaceGenTexture.ReadBinary(reader); break; case "NAM5": if (Unknown == null) { Unknown = new SimpleSubrecord <UInt16>(); } Unknown.ReadBinary(reader); break; case "NAM6": if (Height == null) { Height = new SimpleSubrecord <Single>(); } Height.ReadBinary(reader); break; case "NAM7": if (Weight == null) { Weight = new SimpleSubrecord <Single>(); } Weight.ReadBinary(reader); break; default: throw new Exception(); } } }
public static InventoryItemDto AsDto(this InventoryItem item) { return(new InventoryItemDto(item.CatalogItemId, item.Quantity, item.AcquiredDate)); }
public static bool CanSwitchOrSwap_Prefix(uGUI_Equipment __instance, ref ItemAction __result, string slotB) { if (!ItemDragManager.isDragging) { return(true); } InventoryItem draggedItem = ItemDragManager.draggedItem; if (draggedItem == null) { return(true); } Pickupable item = draggedItem.item; if (item == null) { return(true); } TechType techType = item.GetTechType(); if (techType == TechType.Battery || techType == TechType.PrecursorIonBattery) { if (Equipment.GetSlotType(slotB) == EquipmentType.BatteryCharger) { Equipment equipmentValue = equipmentField.GetValue(__instance) as Equipment; InventoryItem itemInSlot = equipmentValue.GetItemInSlot(slotB); if (itemInSlot == null) { __result = ItemAction.Switch; return(false); } if (Inventory.CanSwap(draggedItem, itemInSlot)) { __result = ItemAction.Swap; return(false); } __result = ItemAction.None; return(false); } } else if (techType == TechType.PowerCell || techType == TechType.PrecursorIonPowerCell) { if (Equipment.GetSlotType(slotB) == EquipmentType.PowerCellCharger) { Equipment equipmentValue = equipmentField.GetValue(__instance) as Equipment; InventoryItem itemInSlot = equipmentValue.GetItemInSlot(slotB); if (itemInSlot == null) { __result = ItemAction.Switch; return(false); } if (Inventory.CanSwap(draggedItem, itemInSlot)) { __result = ItemAction.Swap; return(false); } __result = ItemAction.None; return(false); } } return(true); }
public void UpdateInventoryList(InventoryItem item) { inventory.Add(item); }
private void OnInventoryItemRightClicked(InventoryItem inventoryItem) { TriggerSelling(inventoryItem.Item); }
private void RodsContainer_onChangeItemPosition(InventoryItem item) { RefreshAllRods(); }
public SpoilageReported(Shop shop, InventoryItem spoilage, Guid userId) : base(shop, Trigger.Changed, userId) { }
private async Task PeriodicInventoryCheck(CancellationToken cancellationToken) { IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems = await this.StateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName); while (true) { cancellationToken.ThrowIfCancellationRequested(); IList <InventoryItem> items = new List <InventoryItem>(); using (ITransaction tx = this.StateManager.CreateTransaction()) { ServiceEventSource.Current.ServiceMessage(this, "Checking inventory stock for {0} items.", await inventoryItems.GetCountAsync(tx)); IAsyncEnumerator <KeyValuePair <InventoryItemId, InventoryItem> > enumerator = (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator(); while (await enumerator.MoveNextAsync(cancellationToken)) { InventoryItem item = enumerator.Current.Value; //Check if stock is below restockThreshold and if the item is not already on reorder if ((item.AvailableStock <= item.RestockThreshold) && !item.OnReorder) { items.Add(enumerator.Current.Value); } } } foreach (InventoryItem item in items) { cancellationToken.ThrowIfCancellationRequested(); try { ServiceUriBuilder builder = new ServiceUriBuilder(RestockRequestManagerServiceName); IRestockRequestManager restockRequestManagerClient = ServiceProxy.Create <IRestockRequestManager>( builder.ToUri(), new ServicePartitionKey()); // we reduce the quantity passed in to RestockRequest to ensure we don't overorder RestockRequest newRequest = new RestockRequest(item.Id, (item.MaxStockThreshold - item.AvailableStock)); InventoryItem updatedItem = new InventoryItem( item.Description, item.Price, item.AvailableStock, item.RestockThreshold, item.MaxStockThreshold, item.Id, true); // TODO: this call needs to be idempotent in case we fail to update the InventoryItem after this completes. await restockRequestManagerClient.AddRestockRequestAsync(newRequest); // Write operations take an exclusive lock on an item, which means we can't do anything else with that item while the transaction is open. // If something blocks before the transaction is committed, the open transaction on the item will prevent all operations on it, including reads. // Once the transaction commits, the lock is released and other operations on the item can proceed. // Operations on the transaction all have timeouts to prevent deadlocking an item, // but we should do as little work inside the transaction as possible that is not related to the transaction itself. using (ITransaction tx = this.StateManager.CreateTransaction()) { await inventoryItems.TryUpdateAsync(tx, item.Id, updatedItem, item); await tx.CommitAsync(); } ServiceEventSource.Current.ServiceMessage( this, "Restock order placed. Item ID: {0}. Quantity: {1}", newRequest.ItemId, newRequest.Quantity); } catch (Exception e) { ServiceEventSource.Current.ServiceMessage(this, "Failed to place restock order for item {0}. {1}", item.Id, e.ToString()); } } await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken); } }
public override void OnNPCAtJob(IAreaJob rawJob, ref Vector3Int positionSub, ref NPCBase.NPCState state, ref bool shouldDumpInventory) { BerryFarmerJob job = (BerryFarmerJob)rawJob; state.JobIsDone = true; if (positionSub.IsValid) { ushort type; if (job.placingMissingBush) { if (job.NPC.Colony.UsedStockpile.TryRemove(BuiltinBlocks.BerryBush)) { job.placingMissingBush = false; ServerManager.TryChangeBlock(job.bushLocation, BuiltinBlocks.BerryBush, rawJob.Owner, ServerManager.SetBlockFlags.DefaultAudio); state.SetCooldown(2.0); } else { state.SetIndicator(new Shared.IndicatorState(Random.NextFloat(8f, 14f), BuiltinBlocks.BerryBush, true, false)); } } else if (job.removingOldBush) { if (ServerManager.TryChangeBlock(job.bushLocation, 0, rawJob.Owner, ServerManager.SetBlockFlags.DefaultAudio)) { job.NPC.Colony.UsedStockpile.Add(BuiltinBlocks.BerryBush); job.removingOldBush = false; } state.SetCooldown(2.0); } else if (World.TryGetTypeAt(positionSub, out type)) { if (type == 0) { job.checkMissingBushes = true; state.SetCooldown(1.0, 4.0); } else if (type == BuiltinBlocks.BerryBush) { GatherResults.Clear(); GatherResults.Add(new ItemTypes.ItemTypeDrops(BuiltinBlocks.Berry, 1, 1.0)); GatherResults.Add(new ItemTypes.ItemTypeDrops(BuiltinBlocks.BerryBush, 1, 0.1)); ModLoader.TriggerCallbacks(ModLoader.EModCallbackType.OnNPCGathered, rawJob as IJob, positionSub, GatherResults); InventoryItem toShow = ItemTypes.ItemTypeDrops.GetWeightedRandom(GatherResults); if (toShow.Amount > 0) { state.SetIndicator(new Shared.IndicatorState(8.5f, toShow.Type)); } else { state.SetCooldown(8.5); } job.NPC.Inventory.Add(GatherResults); } else { state.SetIndicator(new Shared.IndicatorState(Random.NextFloat(8f, 14f), BuiltinBlocks.ErrorMissing)); } } else { state.SetCooldown(Random.NextFloat(3f, 6f)); } positionSub = Vector3Int.invalidPos; } else { state.SetCooldown(10.0); } }
internal SpeedOverlay CreateSpeedIconOverlay(uGUI_ItemIcon icon, InventoryItem upgradeModule) { return(new SpeedOverlay(icon, upgradeModule, this)); }
/// <summary> /// Apply all spellcraft gems bonus /// </summary> /// <param name="player"></param> /// <param name="item"></param> /// <returns></returns> private void ApplySpellcraftGems(GamePlayer player, InventoryItem item) { int maxBonusLevel = GetItemMaxImbuePoints(item); int bonusLevel = GetTotalImbuePoints(player, item); int sucessChances = 100; if (bonusLevel > maxBonusLevel) { sucessChances = CalculateChanceToOverchargeItem(player, item, maxBonusLevel, bonusLevel); } int destroyChance = 100 - CalculateChanceToPreserveItem(player, item, maxBonusLevel, bonusLevel); GamePlayer tradePartner = player.TradeWindow.Partner; if (Util.Chance(sucessChances)) { lock (player.TradeWindow.Sync) { player.Inventory.BeginChanges(); foreach (InventoryItem gem in (ArrayList)player.TradeWindow.TradeItems.Clone()) { if (item.Bonus1Type == 0) { item.Bonus1Type = gem.Bonus1Type; item.Bonus1 = gem.Bonus1; } else if (item.Bonus2Type == 0) { item.Bonus2Type = gem.Bonus1Type; item.Bonus2 = gem.Bonus1; } else if (item.Bonus3Type == 0) { item.Bonus3Type = gem.Bonus1Type; item.Bonus3 = gem.Bonus1; } else if (item.Bonus4Type == 0) { item.Bonus4Type = gem.Bonus1Type; item.Bonus4 = gem.Bonus1; } player.Inventory.RemoveCountFromStack(gem, 1); InventoryLogging.LogInventoryAction(player, "(craft)", eInventoryActionType.Craft, gem.Template); } player.Inventory.CommitChanges(); } if (tradePartner != null) { tradePartner.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.ImbuedItem", player.Name), eChatType.CT_Important, eChatLoc.CL_SystemWindow); } player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.ImbuedItem", player.Name), eChatType.CT_Important, eChatLoc.CL_SystemWindow); } else if (Util.Chance(destroyChance)) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.PowerExplodes"), eChatType.CT_Important, eChatLoc.CL_SystemWindow); lock (player.TradeWindow.Sync) { player.Inventory.BeginChanges(); // Luhz Crafting Update: // The base item is no longer lost when spellcrafting explodes - only gems are destroyed. foreach (InventoryItem gem in (ArrayList)player.TradeWindow.TradeItems.Clone()) { if (gem.Object_Type == (int)eObjectType.SpellcraftGem) { player.Inventory.RemoveCountFromStack(gem, 1); InventoryLogging.LogInventoryAction(player, "(craft)", eInventoryActionType.Craft, gem.Template); } } player.Inventory.CommitChanges(); } player.Emote(eEmote.SpellGoBoom); player.Health = 0; player.Die(player); // On official you take damages player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.Failed"), eChatType.CT_Important, eChatLoc.CL_SystemWindow); if (tradePartner != null) { if (Util.Chance(40)) { tradePartner.Emote(eEmote.SpellGoBoom); tradePartner.Health = 0; tradePartner.Die(player); } tradePartner.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.Failed"), eChatType.CT_Important, eChatLoc.CL_SystemWindow); } } else { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.Failed"), eChatType.CT_Important, eChatLoc.CL_SystemWindow); if (tradePartner != null) { tradePartner.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.ApplySpellcraftGems.Failed"), eChatType.CT_Important, eChatLoc.CL_SystemWindow); } } }
public virtual List <SOPackageInfoEx> PackByWeightMixedItems(List <INItemBoxEx> boxes, List <ItemInfo> items, Dictionary <int, List <INItemBoxEx> > boxesByInventoryLookup, Dictionary <string, List <int> > boxItemsLookup, bool restrictByVolume, int?siteID) { // коробки c пустотой (могут быть и одинаковые, расширенный выходной массив) List <advancedINItemBoxEx> advancedboxes = new List <advancedINItemBoxEx>(); // упорядочим коробки для каждого айтема foreach (KeyValuePair <int, List <INItemBoxEx> > keyValuePair in boxesByInventoryLookup) { keyValuePair.Value.Sort((x, y) => (-1 * decimal.Compare(x.MaxNetWeight, y.MaxNetWeight))); //DESC; } // упорядочим все айтемы по весу ОДНОЙ(НЕДЕЛИМОЙ) единицы items.Sort((x, y) => (-1 * decimal.Compare(x.UnitWeight.GetValueOrDefault(), y.UnitWeight.GetValueOrDefault()))); //DESC; // упорядочим все коробки для всех айтемов boxes.Sort((x, y) => (-1 * decimal.Compare(x.MaxNetWeight, y.MaxNetWeight))); //DESC; // Перебираем все айтемы начиная с самого тяжелого (одного) if (restrictByVolume) { foreach (ItemInfo item in items) { // в такие коробки будем их класть INItemBoxEx currentbox = boxesByInventoryLookup[item.InventoryID].ToArray()[0]; decimal unpackedWeight = item.TotalWeight; decimal unpackedVolume = item.TotalVolume; if (item.UnitWeight > currentbox.MaxWeight || (item.UnitVolume > currentbox.MaxVolume && currentbox.MaxVolume > 0)) { InventoryItem inv = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(graph, item.InventoryID); throw new PXException(Messages.NoBoxForItem, inv.InventoryCD.Trim()); } // может пустоты есть? foreach (advancedINItemBoxEx advancedbox in advancedboxes) { foreach (INItemBoxEx allcurrentbox in boxesByInventoryLookup[item.InventoryID].ToArray()) { if (advancedbox.BoxID == allcurrentbox.BoxID && unpackedWeight > 0) { if (advancedbox.EmptyBoxWeight >= item.UnitWeight && advancedbox.EmptyBoxVolume >= item.UnitVolume) { int numberofunitWeight; //qty that can fit in the box by weight int numberofunitVolume; //qty that can fit in the box by volume if (advancedbox.EmptyBoxWeight > unpackedWeight) { if (item.UnitWeight > 0) { numberofunitWeight = Convert.ToInt32(Math.Floor(unpackedWeight / item.UnitWeight.Value)); } else { numberofunitWeight = Convert.ToInt32(Math.Floor(item.Qty)); } } else { if (item.UnitWeight > 0) { numberofunitWeight = Convert.ToInt32(Math.Floor(advancedbox.EmptyBoxWeight / item.UnitWeight.Value)); } else { numberofunitWeight = Convert.ToInt32(Math.Floor(item.Qty)); } } if (advancedbox.EmptyBoxVolume > unpackedVolume) { if (item.UnitVolume > 0) { numberofunitVolume = Convert.ToInt32(Math.Floor(unpackedVolume / item.UnitVolume.Value)); } else { numberofunitVolume = Convert.ToInt32(Math.Floor(item.Qty)); } } else { if (item.UnitVolume > 0) { numberofunitVolume = Convert.ToInt32(Math.Floor(advancedbox.EmptyBoxVolume / item.UnitVolume.Value)); } else { numberofunitVolume = Convert.ToInt32(Math.Floor(item.Qty)); } } int numberofunit = numberofunitVolume < numberofunitWeight ? numberofunitVolume : numberofunitWeight; decimal actualweigth = numberofunit * item.UnitWeight.GetValueOrDefault(); decimal actualvolume = numberofunit * item.UnitVolume.GetValueOrDefault(); unpackedWeight = unpackedWeight - actualweigth; advancedbox.InvenoryList.Add(item.InventoryID); advancedbox.CurrentWeight = advancedbox.CurrentWeight + actualweigth; advancedbox.EmptyBoxWeight = advancedbox.MaxNetWeight - advancedbox.CurrentWeight; advancedbox.CurrentVolume = advancedbox.CurrentVolume + actualvolume; advancedbox.EmptyBoxVolume = advancedbox.MaxVolume.GetValueOrDefault() - advancedbox.CurrentVolume; } } } } if (unpackedWeight != 0) { // теперь в новые кидать будем while (unpackedWeight > currentbox.MaxNetWeight) { int numberofunitWeight; int numberofunitVolume; if (item.UnitWeight > 0) { numberofunitWeight = Convert.ToInt32(Math.Floor(currentbox.MaxNetWeight / item.UnitWeight.Value)); } else { numberofunitWeight = Convert.ToInt32(Math.Floor(item.Qty)); } if (item.UnitVolume > 0 && currentbox.MaxVolume > 0) { numberofunitVolume = Convert.ToInt32(Math.Floor(currentbox.MaxVolume.Value / item.UnitVolume.Value)); } else { numberofunitVolume = Convert.ToInt32(Math.Floor(item.Qty)); } int numberofunit = numberofunitVolume < numberofunitWeight ? numberofunitVolume : numberofunitWeight; decimal actualweigth = numberofunit * item.UnitWeight.GetValueOrDefault(); decimal actualvolume = numberofunit * item.UnitVolume.GetValueOrDefault(); unpackedWeight = unpackedWeight - actualweigth; unpackedVolume = unpackedVolume - actualvolume; advancedINItemBoxEx advancedbox = new advancedINItemBoxEx(); advancedbox.InvenoryList = new List <int>(); advancedbox.BoxID = currentbox.BoxID; advancedbox.InvenoryList.Add(item.InventoryID); advancedbox.BoxWeight = currentbox.BoxWeight; advancedbox.MaxWeight = currentbox.MaxWeight; advancedbox.EmptyBoxWeight = currentbox.MaxNetWeight - actualweigth; advancedbox.EmptyBoxVolume = currentbox.MaxVolume.GetValueOrDefault() - actualvolume; advancedbox.CurrentWeight = actualweigth; advancedbox.CurrentVolume = actualvolume; advancedboxes.Add(advancedbox); } // последние ящики while (unpackedWeight != 0) { int numberofunitWeight; int numberofunitVolume; if (currentbox.MaxNetWeight > unpackedWeight) { if (item.UnitWeight > 0) { numberofunitWeight = Convert.ToInt32(Math.Floor(unpackedWeight / item.UnitWeight.Value)); } else { numberofunitWeight = Convert.ToInt32(Math.Floor(item.Qty)); } } else { if (item.UnitWeight > 0) { numberofunitWeight = Convert.ToInt32(Math.Floor(currentbox.MaxNetWeight / item.UnitWeight.Value)); } else { numberofunitWeight = Convert.ToInt32(Math.Floor(item.Qty)); } } if (currentbox.MaxVolume > unpackedVolume) { if (item.UnitVolume > 0) { numberofunitVolume = Convert.ToInt32(Math.Floor(unpackedVolume / item.UnitVolume.Value)); } else { numberofunitVolume = Convert.ToInt32(Math.Floor(item.Qty)); } } else { if (item.UnitVolume > 0 && currentbox.MaxVolume > 0) { numberofunitVolume = Convert.ToInt32(Math.Floor(currentbox.MaxVolume.Value / item.UnitVolume.Value)); } else { numberofunitVolume = Convert.ToInt32(Math.Floor(item.Qty)); } } int numberofunit = numberofunitVolume < numberofunitWeight ? numberofunitVolume : numberofunitWeight; decimal actualweigth = numberofunit * item.UnitWeight.GetValueOrDefault(); decimal actualvolume = numberofunit * item.UnitVolume.GetValueOrDefault(); unpackedWeight = unpackedWeight - actualweigth; unpackedVolume = unpackedVolume - actualvolume; advancedINItemBoxEx advancedbox1 = new advancedINItemBoxEx(); advancedbox1.InvenoryList = new List <int>(); advancedbox1.BoxID = currentbox.BoxID; advancedbox1.InvenoryList.Add(item.InventoryID); advancedbox1.BoxWeight = currentbox.BoxWeight; advancedbox1.MaxWeight = currentbox.MaxWeight; advancedbox1.EmptyBoxWeight = currentbox.MaxNetWeight - actualweigth; advancedbox1.EmptyBoxVolume = currentbox.MaxVolume.GetValueOrDefault() - actualvolume; advancedbox1.CurrentWeight = actualweigth; advancedbox1.CurrentVolume = actualvolume; advancedboxes.Add(advancedbox1); } } } // Второй проход. Посмотрим не влезет ли товар в коробки поменьше foreach (advancedINItemBoxEx advancedbox in advancedboxes) { // пошли по всем коробкам foreach (INItemBoxEx box in boxes) { // если туда влезает именно этот товар (или товары) bool availablesmallpackage = true; foreach (int itemlist in advancedbox.InvenoryList) { if (!boxItemsLookup[box.BoxID].Contains(itemlist)) { availablesmallpackage = false; } } if (availablesmallpackage) { // и по весу проходим if (advancedbox.CurrentWeight < box.MaxNetWeight) { // и по объему if (advancedbox.CurrentVolume < box.MaxVolume) { advancedbox.BoxID = box.BoxID; } } } } } } else { foreach (ItemInfo item in items) { // в такие коробки будем их класть INItemBoxEx currentbox = boxesByInventoryLookup[item.InventoryID].ToArray()[0]; decimal unpackedWeight = item.TotalWeight; // может пустоты есть? foreach (advancedINItemBoxEx advancedbox in advancedboxes) { foreach (INItemBoxEx allcurrentbox in boxesByInventoryLookup[item.InventoryID].ToArray()) { if (advancedbox.BoxID == allcurrentbox.BoxID && unpackedWeight > 0) { if (advancedbox.EmptyBoxWeight >= item.UnitWeight) { int numberofunit; if (advancedbox.EmptyBoxWeight > unpackedWeight) { if (item.UnitWeight > 0) { numberofunit = Convert.ToInt32(Math.Ceiling(unpackedWeight / item.UnitWeight.Value)); } else { numberofunit = Convert.ToInt32(Math.Ceiling(item.Qty)); } } else { if (item.UnitWeight > 0) { numberofunit = Convert.ToInt32(Math.Ceiling(advancedbox.EmptyBoxWeight / item.UnitWeight.Value)); } else { numberofunit = Convert.ToInt32(Math.Ceiling(item.Qty)); } } decimal actualweigth = numberofunit * item.UnitWeight.GetValueOrDefault(); unpackedWeight = unpackedWeight - actualweigth; advancedbox.InvenoryList.Add(item.InventoryID); advancedbox.CurrentWeight = advancedbox.CurrentWeight + actualweigth; advancedbox.EmptyBoxWeight = advancedbox.MaxNetWeight - advancedbox.CurrentWeight; } } } } if (unpackedWeight != 0) { // теперь в новые кидать будем while (unpackedWeight > currentbox.MaxNetWeight) { int numberofunit; if (item.UnitWeight > 0) { numberofunit = Convert.ToInt32(Math.Ceiling(currentbox.MaxNetWeight / item.UnitWeight.Value)); } else { numberofunit = Convert.ToInt32(Math.Ceiling(item.Qty)); } decimal actualweigth = numberofunit * item.UnitWeight.GetValueOrDefault(); unpackedWeight = unpackedWeight - actualweigth; advancedINItemBoxEx advancedbox = new advancedINItemBoxEx(); advancedbox.InvenoryList = new List <int>(); advancedbox.BoxID = currentbox.BoxID; advancedbox.InvenoryList.Add(item.InventoryID); advancedbox.BoxWeight = currentbox.BoxWeight; advancedbox.MaxWeight = currentbox.MaxWeight; advancedbox.EmptyBoxWeight = currentbox.MaxNetWeight - actualweigth; advancedbox.CurrentWeight = actualweigth; advancedboxes.Add(advancedbox); } // и последний ящик advancedINItemBoxEx advancedbox1 = new advancedINItemBoxEx(); advancedbox1.InvenoryList = new List <int>(); advancedbox1.BoxID = currentbox.BoxID; advancedbox1.InvenoryList.Add(item.InventoryID); advancedbox1.BoxWeight = currentbox.BoxWeight; advancedbox1.MaxWeight = currentbox.MaxWeight; advancedbox1.EmptyBoxWeight = currentbox.MaxNetWeight - unpackedWeight; advancedbox1.CurrentWeight = unpackedWeight; advancedboxes.Add(advancedbox1); } } // Второй проход. Посмотрим не влезет ли товар в коробки поменьше foreach (advancedINItemBoxEx advancedbox in advancedboxes) { // пошли по всем коробкам foreach (INItemBoxEx box in boxes) { // если туда влезает именно этот товар (или товары) bool availablesmallpackage = true; foreach (int itemlist in advancedbox.InvenoryList) { if (!boxItemsLookup[box.BoxID].Contains(itemlist)) { availablesmallpackage = false; } } if (availablesmallpackage) { // и по весу проходим if (advancedbox.CurrentWeight < box.MaxNetWeight) { advancedbox.BoxID = box.BoxID; } } } } } List <SOPackageInfoEx> list = new List <SOPackageInfoEx>(); foreach (advancedINItemBoxEx advancedbox in advancedboxes) { SOPackageInfoEx temp = new SOPackageInfoEx(); temp.BoxID = advancedbox.BoxID; temp.SiteID = siteID; foreach (INItemBoxEx box in boxes) { if (box.BoxID == temp.BoxID) { temp.Weight = advancedbox.CurrentWeight + box.BoxWeight; } } list.Add(temp); } return(list); }
/// <summary> /// This function is called when player accept the combine /// </summary> /// <param name="player"></param> /// <param name="item"></param> public override bool IsAllowedToCombine(GamePlayer player, InventoryItem item) { if (!base.IsAllowedToCombine(player, item)) { return(false); } if (((InventoryItem)player.TradeWindow.TradeItems[0]).Model == 525) // first ingredient to combine is Dust => echantement { if (item.Level < 15) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.NoEnchanted"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } lock (player.TradeWindow.Sync) { foreach (InventoryItem materialToCombine in player.TradeWindow.TradeItems) { if (materialToCombine.Model != 525) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.FalseMaterial", materialToCombine.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } } } } else { ArrayList bonusToApply = new ArrayList(4); if (item.Bonus1Type != 0) { bonusToApply.Add(item.Bonus1Type); if (item.Bonus2Type != 0) { bonusToApply.Add(item.Bonus2Type); if (item.Bonus3Type != 0) { bonusToApply.Add(item.Bonus3Type); if (item.Bonus4Type != 0) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.AlreadyImbued", item.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } } } } lock (player.TradeWindow.Sync) { for (int i = 0; i < player.TradeWindow.ItemsCount; i++) { InventoryItem currentItem = (InventoryItem)player.TradeWindow.TradeItems[i]; if (currentItem.Object_Type != (int)eObjectType.SpellcraftGem) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.FalseItem"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } if (bonusToApply.Contains(currentItem.Bonus1Type)) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.NoSameBonus"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } if (bonusToApply.Count > 4) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.DifferentTypes", item.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } bonusToApply.Add(currentItem.Bonus1Type); } } int bonusLevel = GetTotalImbuePoints(player, item); if (bonusLevel > player.GetCraftingSkillValue(eCraftingSkill.SpellCrafting) / 20) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.NotEnoughSkill"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } if (bonusLevel - GetItemMaxImbuePoints(item) > 5) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "SpellCrafting.IsAllowedToCombine.NoMoreLevels", item.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow); return(false); } } return(true); }
/// <summary> /// Event called when player picks an item /// </summary> /// <param name="item"></param> void OnPickItem(InventoryItem item) { Debug.Log("Picked " + item.pickAmount + " units of " + item.name); inventory.insert(item); }
void ClearItem() { it = null; ki = null; }
/// <summary> /// Apply all magical dust /// </summary> /// <param name="player"></param> /// <param name="item"></param> /// <returns></returns> private void ApplyMagicalDusts(GamePlayer player, InventoryItem item) { int spellCrafterLevel = player.GetCraftingSkillValue(eCraftingSkill.SpellCrafting); int bonusCap; if (spellCrafterLevel < 300 || item.Level < 15) { bonusCap = 0; } else if (spellCrafterLevel < 400 || item.Level < 20) { bonusCap = 5; } else if (spellCrafterLevel < 500 || item.Level < 25) { bonusCap = 10; } else if (spellCrafterLevel < 600 || item.Level < 30) { bonusCap = 15; } else if (spellCrafterLevel < 700 || item.Level < 35) { bonusCap = 20; } else if (spellCrafterLevel < 800 || item.Level < 40) { bonusCap = 25; } else if (spellCrafterLevel < 900 || item.Level < 45) { bonusCap = 30; } else { bonusCap = 35; } player.Inventory.BeginChanges(); int bonusMod = item.Bonus; lock (player.TradeWindow.Sync) { foreach (InventoryItem gemme in player.TradeWindow.TradeItems) { switch (gemme.Name) { case "coppery imbued dust": bonusMod += 2; break; case "coppery enchanted dust": bonusMod += 4; break; case "coppery glowing dust": bonusMod += 6; break; case "coppery ensorcelled dust": bonusMod += 8; break; case "silvery imbued dust": bonusMod += 10; break; case "silvery enchanted dust": bonusMod += 12; break; case "silvery glowing dust": bonusMod += 14; break; case "silvery ensorcelled dust": bonusMod += 16; break; case "golden imbued dust": bonusMod += 18; break; case "golden enchanted dust": bonusMod += 20; break; case "golden glowing dust": bonusMod += 22; break; case "golden ensorcelled dust": bonusMod += 24; break; case "mithril imbued dust": bonusMod += 26; break; case "mithril enchanted dust": bonusMod += 28; break; case "mithril glowing dust": bonusMod += 30; break; case "mithril ensorcelled dust": bonusMod += 32; break; case "platinum imbued dust": bonusMod += 34; break; case "platinum enchanted dust": bonusMod += 36; break; case "platinum glowing dust": bonusMod += 38; break; case "platinum ensorcelled dust": bonusMod += 40; break; } player.Inventory.RemoveCountFromStack(gemme, 1); InventoryLogging.LogInventoryAction(player, "(craft)", eInventoryActionType.Craft, gemme.Template); } } item.Bonus = Math.Min(bonusMod, bonusCap); player.Inventory.CommitChanges(); }
public void Clear() { this.it = null; Label.text = ""; Sprite.spriteName = "bg_道具"; }
void RealmInventoryWindow_onDropOut(InventorySlot slot, InventoryItem itemDrop) { CurrentCapacity--; DarkestDungeonManager.Campaign.RealmInventory.Trinkets.Remove(itemDrop.ItemData as Trinket); UpdateWindow(); }
partial void OnCreateInventoryItem(CreateInventoryItemCommand command, ref InventoryItem item);
void Start() { controller = GameObject.FindGameObjectWithTag("TurnController").GetComponent <TurnController>(); item = transform.parent.gameObject.GetComponent <InventoryItem>(); inventory = GetComponentInParent <Inventory>(); }
public async void Handle(Session session, ClientPacket message) { int pageId = message.PopInt(); int itemId = message.PopInt(); string extraData = message.PopString(); int amount = message.PopInt(); CatalogPage page = Alias.Server.CatalogManager.GetCatalogPage(pageId); if (page == null) { session.Send(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); return; } if (page.Rank > session.Player.Rank) { session.Send(new AlertPurchaseUnavailableComposer(AlertPurchaseUnavailableComposer.ILLEGAL)); return; } CatalogItem item = page.GetCatalogItem(itemId); if (item == null) { session.Send(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); return; } if (item.ClubLevel > session.Player.ClubLevel) { session.Send(new AlertPurchaseUnavailableComposer(AlertPurchaseUnavailableComposer.REQUIRES_CLUB)); return; } if (amount <= 0 || amount > 100) { session.Send(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); return; } if (amount > 1 && !item.HasOffer) { session.Send(new AlertPurchaseFailedComposer(AlertPurchaseUnavailableComposer.ILLEGAL)); return; } if (item.IsLimited) { amount = 1; if (item.LimitedNumbers.Count <= 0) { session.Send(new AlertLimitedSoldOutComposer()); return; } } int limitedNumber = 0; int limitedStack = 0; if (item.IsLimited) { limitedNumber = item.GetNumber; limitedStack = item.LimitedStack; } List <InventoryItem> itemsList = new List <InventoryItem>(); int totalCredits = 0; int totalPoints = 0; for (int i = 0; i < amount; i++) { if (item.Credits <= session.Player.Credits - totalCredits) { //if (item.Points <= session.Player.Currency.TryGetCurrency(item.PointsType).Amount - totalPoints) todo: { if (((i + 1) % 6 != 0 && item.HasOffer) || !item.HasOffer) { totalCredits += item.Credits; totalPoints += item.Points; } foreach (ItemData baseItem in item.GetItems()) { for (int k = 0; k < item.GetItemAmount(baseItem.Id); k++) { if (baseItem.Interaction == ItemInteraction.BOT) { CatalogBots botData = Alias.Server.CatalogManager.GetCatalogBot(baseItem.Id); if (botData != null) { InventoryBot habboBot = new InventoryBot(-1, botData.Name, botData.Motto, botData.Look, botData.Gender); await session.Player.Inventory.AddBot(habboBot); session.Send(new AddBotComposer(habboBot)); } } else { if (baseItem.Interaction == ItemInteraction.TROPHY) { extraData = session.Player.Username + (char)9 + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + (char)9 + extraData; } if (baseItem.Interaction == ItemInteraction.TELEPORT) { InventoryItem teleportOne = new InventoryItem(-1, limitedNumber, limitedStack, baseItem.Id, session.Player.Id, extraData); await session.Player.Inventory.AddItem(teleportOne); InventoryItem teleportTwo = new InventoryItem(-1, limitedNumber, limitedStack, baseItem.Id, session.Player.Id, teleportOne.Id.ToString()); await session.Player.Inventory.AddItem(teleportTwo); teleportOne.ExtraData = teleportTwo.Id.ToString(); await session.Player.Inventory.UpdateItem(teleportOne); itemsList.Add(teleportOne); itemsList.Add(teleportTwo); } else { InventoryItem habboItem = new InventoryItem(-1, limitedNumber, limitedStack, baseItem.Id, session.Player.Id, extraData); await session.Player.Inventory.AddItem(habboItem); itemsList.Add(habboItem); } } } } } } } if (totalCredits > 0) { session.Player.Credits -= totalCredits; session.Send(new UserCreditsComposer(session.Player)); } if (totalPoints > 0) { //session.Player.Currency.GetCurrencyType(item.PointsType).Amount -= totalPoints; todo: //session.Send(new UserPointsComposer(session.Player.Currency.GetCurrencyType(item.PointsType).Amount, -totalPoints, item.PointsType)); } if (item.IsLimited) { item.AddLimited(limitedNumber); await Alias.Server.CatalogManager.AddLimitedAsync(item.Id, limitedNumber); } if (itemsList != null) { session.Send(new AddPlayerItemsComposer(itemsList)); } session.Player.AddPurchase(item); session.Send(new PurchaseOKComposer(item)); session.Send(new InventoryRefreshComposer()); }
partial void OnCommited(CreateInventoryItemCommand command, InventoryItem item);
public void SetupDescriptionAndButton(string newDescriptionString, bool isButtonUsable, InventoryItem newItem) { currentItem = newItem; descriptionText.text = newDescriptionString; useButton.SetActive(isButtonUsable); }
public void EquipWeapons() { foreach (var unit in _chapterSave.UnitRegion.Units) { var classData = Data.Database.Classes.GetByID(unit.ClassID); var items = new List <InventoryItem>(); if (classData.UsesSword) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Sword && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Sword = Unit.WeaponExperienceForRankB; } if (classData.UsesLance) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Lance && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Lance = Unit.WeaponExperienceForRankB; } if (classData.UsesAxe) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Axe && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Axe = Unit.WeaponExperienceForRankB; } if (classData.UsesShuriken) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Shuriken && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Shuriken = Unit.WeaponExperienceForRankB; } if (classData.UsesBow) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Bow && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Bow = Unit.WeaponExperienceForRankB; } if (classData.UsesTome) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Tome && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Tome = Unit.WeaponExperienceForRankB; } if (classData.UsesStaff) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Staff && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Staff = Unit.WeaponExperienceForRankB; } if (classData.UsesStone) { var weapon = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Stone && x.WeaponRank <= Enums.WeaponRank.B) .RandomElement(_rng); items.Add(InventoryItem.FromID(weapon.ItemID)); unit.WeaponExperience_Stone = Unit.WeaponExperienceForRankB; } // Maybe a healing item too. Or some other consumable. Have fun! if ((_rng.Next(100)) < 75) { var consumable = Data.Database.Items.GetAll() .Where((x) => x.Type == Enums.ItemType.Consumable) .RandomElement(_rng); var inventoryItem = InventoryItem.FromID(consumable.ItemID); inventoryItem.Uses = consumable.MaximumUses; items.Add(inventoryItem); } for (var i = 0; i < items.Count; i++) { if (i == 0) { unit.Item_1 = items[i]; } if (i == 1) { unit.Item_2 = items[i]; } if (i == 2) { unit.Item_3 = items[i]; } if (i == 3) { unit.Item_4 = items[i]; } } } }
public void Handle(CreateInventoryItem message) { var item = new InventoryItem(message.InventoryItemId, message.Name); _repository.Save(item, -1); }
public AutoDefenseIconOverlay(uGUI_ItemIcon icon, InventoryItem upgradeModule) : base(icon, upgradeModule) { zapper = MCUServices.Find.AuxCyclopsManager <AutoDefenser>(base.Cyclops); }
public static bool UpgradeHouse(House house, InventoryItem deed) { int newModel = 0; switch (deed.Id_nb) { case "housing_alb_cottage_deed": newModel = 1; break; case "housing_alb_house_deed": newModel = 2; break; case "housing_alb_villa_deed": newModel = 3; break; case "housing_alb_mansion_deed": newModel = 4; break; case "housing_mid_cottage_deed": newModel = 5; break; case "housing_mid_house_deed": newModel = 6; break; case "housing_mid_villa_deed": newModel = 7; break; case "housing_mid_mansion_deed": newModel = 8; break; case "housing_hib_cottage_deed": newModel = 9; break; case "housing_hib_house_deed": newModel = 10; break; case "housing_hib_villa_deed": newModel = 11; break; case "housing_hib_mansion_deed": newModel = 12; break; } if (newModel == 0) { return(false); } // remove all players from the home before we upgrade it foreach (GamePlayer player in house.GetAllPlayersInHouse()) { player.LeaveHouse(); } // if there is a consignment merchant, we have to re-initialize since we changed the house var merchant = GameServer.Database.SelectObject <HouseConsignmentMerchant>("HouseNumber = '" + house.HouseNumber + "'"); long oldMerchantMoney = 0; if (merchant != null) { oldMerchantMoney = merchant.Money; } RemoveHouseItems(house); // change the model of the house house.Model = newModel; // re-add the merchant if there was one if (merchant != null) { house.AddConsignment(oldMerchantMoney); } // save the house, and broadcast an update house.SaveIntoDatabase(); house.SendUpdate(); return(true); }
public override bool ReceiveItem(GameLiving source, InventoryItem item) { if (source == null || item == null) { return(false); } if (!(source is GamePlayer)) { return(false); } var player = (GamePlayer)source; if (HouseMgr.IsOwner(DatabaseItem, player)) { switch (item.Id_nb) { case "housing_alb_cottage_deed": CreateHouse(player, 1); break; case "housing_alb_house_deed": CreateHouse(player, 2); break; case "housing_alb_villa_deed": CreateHouse(player, 3); break; case "housing_alb_mansion_deed": CreateHouse(player, 4); break; case "housing_mid_cottage_deed": CreateHouse(player, 5); break; case "housing_mid_house_deed": CreateHouse(player, 6); break; case "housing_mid_villa_deed": CreateHouse(player, 7); break; case "housing_mid_mansion_deed": CreateHouse(player, 8); break; case "housing_hib_cottage_deed": CreateHouse(player, 9); break; case "housing_hib_house_deed": CreateHouse(player, 10); break; case "housing_hib_villa_deed": CreateHouse(player, 11); break; case "housing_hib_mansion_deed": CreateHouse(player, 12); break; default: return(false); } player.Inventory.RemoveItem(item); // Tolakram: Is this always null when purchasing a house? InventoryLogging.LogInventoryAction(player, "(HOUSE;" + (CurrentHouse == null ? DatabaseItem.HouseNumber : CurrentHouse.HouseNumber) + ")", eInventoryActionType.Other, item.Template, item.Count); return(true); } ChatUtil.SendSystemMessage(player, "You do not own this lot!"); return(false); }
/// <summary> /// Called each time a player push the accept button to accept the trade /// </summary> public bool AcceptTrade() { lock (Sync) { m_tradeAccept = true; GamePlayer partner = m_partnerWindow.Owner; partner.Out.SendMessage(m_owner.Name + " has accepted the trade.", eChatType.CT_System, eChatLoc.CL_SystemWindow); // Check if the tradepartner has also agreed to the trade if (!m_partnerWindow.m_tradeAccept) { return(false); } bool logTrade = ServerProperties.Properties.LOG_TRADES; if (m_owner.Client.Account.PrivLevel > 1 || partner.Client.Account.PrivLevel > 1) { logTrade = true; } // Test if we and our partner have enough money bool enoughMoney = m_owner.RemoveMoney(TradeMoney); bool partnerEnoughMoney = partner.RemoveMoney(m_partnerWindow.TradeMoney); // Check the preconditions if (!enoughMoney || !partnerEnoughMoney) { if (!enoughMoney) { // Reset the money if we don't have enough TradeMoney = 0; if (partnerEnoughMoney) { partner.AddMoney(m_partnerWindow.TradeMoney); InventoryLogging.LogInventoryAction(partner, m_owner, eInventoryActionType.Trade, m_partnerWindow.TradeMoney); } m_owner.Out.SendMessage("You don't have enough money.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); partner.Out.SendMessage(m_owner.Name + " doesn't have enough money.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); } if (!partnerEnoughMoney) { // Reset the money if our partner doesn't have enough m_partnerWindow.TradeMoney = 0; if (enoughMoney) { m_owner.AddMoney(TradeMoney); InventoryLogging.LogInventoryAction(m_owner, partner, eInventoryActionType.Trade, TradeMoney); } partner.Out.SendMessage("You don't have enough money.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); m_owner.Out.SendMessage(partner.Name + " doesn't have enough money.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); } // Update our tradewindow and return TradeUpdate(); return(false); } if (m_combine == true) { GamePlayer crafter = m_recipiant == true ? m_owner : partner; // -------------------------------------------------------------- // Luhz Crafting Update: // Players may now have any, and all, "primary" crafting skills. // AbstractCraftingSkill skill = CraftingMgr.getSkillbyEnum(crafter.CraftingPrimarySkill); AbstractCraftingSkill skill = null; lock (crafter.TradeWindow.Sync) { foreach (InventoryItem i in (ArrayList)crafter.TradeWindow.TradeItems.Clone()) { if (i.Object_Type == (int)eObjectType.AlchemyTincture) { if (m_owner.GetCraftingSkillValue(eCraftingSkill.Alchemy) > 0) { skill = CraftingMgr.getSkillbyEnum(eCraftingSkill.Alchemy); break; } } else if (i.Object_Type == (int)eObjectType.SpellcraftGem) { if (crafter.GetCraftingSkillValue(eCraftingSkill.SpellCrafting) > 0) { skill = CraftingMgr.getSkillbyEnum(eCraftingSkill.SpellCrafting); break; } } } } // -------------------------------------------------------------- if (skill != null && skill is AdvancedCraftingSkill) { ((AdvancedCraftingSkill)skill).CombineItems(crafter); } } else if (m_repair == true) { GamePlayer crafter = m_recipiant == true ? m_owner : partner; InventoryItem itemToRepair = (InventoryItem)(m_recipiant == true ? m_partnerWindow.TradeItems[0] : TradeItems[0]); if (itemToRepair != null) { crafter.RepairItem(itemToRepair); } } else { // Calculate the count of items int myTradeItemsCount = m_tradeItems.Count; int partnerTradeItemsCount = m_partnerWindow.TradeItems.Count; // Test if we and our partner have enough space in inventory int mySpaceNeeded = Math.Max(0, partnerTradeItemsCount - myTradeItemsCount); int partnerSpaceNeeded = Math.Max(0, myTradeItemsCount - partnerTradeItemsCount); bool enoughSpace = m_owner.Inventory.IsSlotsFree(mySpaceNeeded, eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack); bool partnerEnoughSpace = partner.Inventory.IsSlotsFree(partnerSpaceNeeded, eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack); // Check the preconditions if (!enoughSpace || !partnerEnoughSpace) { if (!enoughSpace) { m_owner.Out.SendMessage("You don't have enough space in your inventory.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); partner.Out.SendMessage(m_owner.Name + " doesn't have enough space in his inventory.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); } if (!partnerEnoughSpace) { partner.Out.SendMessage("You don't have enough space in your inventory.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); m_owner.Out.SendMessage(partner.Name + " doesn't have enough space in his inventory.", eChatType.CT_Merchant, eChatLoc.CL_SystemWindow); } // Update our tradewindow and return TradeUpdate(); // This was already removed above, needs to be returned to the players on trade failure. m_owner.AddMoney(TradeMoney); partner.AddMoney(m_partnerWindow.TradeMoney); return(false); } // Now transfer everything m_owner.Inventory.BeginChanges(); partner.Inventory.BeginChanges(); m_changesCount++; m_partnerWindow.m_changesCount++; // must be cloned because Inventory.RemoveItem removes it from trade window ArrayList ownerTradeItems = (ArrayList)TradeItems.Clone(); ArrayList partnerTradeItems = (ArrayList)m_partnerWindow.TradeItems.Clone(); // remove all items first to make sure there is enough space // if inventory is full but removed items count >= received count foreach (InventoryItem item in ownerTradeItems) { lock (m_owner.Inventory) { if (!m_owner.Inventory.RemoveTradeItem(item)) { if (logTrade) { GameServer.Instance.LogGMAction(" NOTItem: " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") -> " + partner.Name + "(" + partner.Client.Account.Name + ") : " + item.Name + "(" + item.Id_nb + ")"); } // BOT.Ban(m_owner, "Trade Hack"); // BOT.Ban(partner, "Trade Hack"); return(false); } } } foreach (InventoryItem item in partnerTradeItems) { lock (partner.Inventory) { if (!partner.Inventory.RemoveTradeItem(item)) { if (logTrade) { GameServer.Instance.LogGMAction(" NOTItem: " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") -> " + partner.Name + "(" + partner.Client.Account.Name + ") : " + item.Name + "(" + item.Id_nb + ")"); } // BOT.Ban(m_owner, "Trade Hack"); // BOT.Ban(partner, "Trade Hack"); return(false); } } } foreach (InventoryItem item in ownerTradeItems) { if (m_owner.Guild != partner.Guild) { item.Emblem = 0; } bool tradeSuccess = false; if (item.IsDeleted) { tradeSuccess = partner.Inventory.AddItem(eInventorySlot.FirstEmptyBackpack, item); } else { tradeSuccess = partner.Inventory.AddTradeItem(eInventorySlot.FirstEmptyBackpack, item); } if (!tradeSuccess) { log.Error("Trade item was not added to Partner first free slot. Owner = " + m_owner.Name + ", Partner = " + partner.Name + "; Item = " + item.Id_nb); } else { InventoryLogging.LogInventoryAction(m_owner, partner, eInventoryActionType.Trade, item.Template, item.Count); if (logTrade) { GameServer.Instance.LogGMAction(" Item: " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") -> " + partner.Name + "(" + partner.Client.Account.Name + ") : " + item.Name + "(" + item.Id_nb + ")"); } } } foreach (InventoryItem item in partnerTradeItems) { if (m_owner.Guild != partner.Guild) { item.Emblem = 0; } bool tradeSuccess = false; if (item.IsDeleted) { tradeSuccess = m_owner.Inventory.AddItem(eInventorySlot.FirstEmptyBackpack, item); } else { tradeSuccess = m_owner.Inventory.AddTradeItem(eInventorySlot.FirstEmptyBackpack, item); } if (!tradeSuccess) { log.Error("Trade item was not added to Owner first free slot. Owner = " + m_owner.Name + ", Partner = " + partner.Name + "; Item = " + item.Id_nb); } else { InventoryLogging.LogInventoryAction(partner, m_owner, eInventoryActionType.Trade, item.Template, item.Count); if (logTrade) { GameServer.Instance.LogGMAction(" Item: " + partner.Name + "(" + partner.Client.Account.Name + ") -> " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") : " + item.Name + "(" + item.Id_nb + ")"); } } } m_owner.Inventory.CommitChanges(); partner.Inventory.CommitChanges(); m_changesCount--; m_partnerWindow.m_changesCount--; m_owner.Out.SendMessage("Trade Completed. " + myTradeItemsCount + " items for " + partnerTradeItemsCount + " items.", eChatType.CT_System, eChatLoc.CL_SystemWindow); partner.Out.SendMessage("Trade Completed. " + partnerTradeItemsCount + " items for " + myTradeItemsCount + " items.", eChatType.CT_System, eChatLoc.CL_SystemWindow); m_owner.Inventory.SaveIntoDatabase(m_owner.InternalID); partner.Inventory.SaveIntoDatabase(partner.InternalID); } if (logTrade) { if (m_partnerWindow.TradeMoney > 0) { GameServer.Instance.LogGMAction(" Money: " + partner.Name + "(" + partner.Client.Account.Name + ") -> " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") : " + m_partnerWindow.TradeMoney + "coppers"); } if (TradeMoney > 0) { GameServer.Instance.LogGMAction(" Money: " + m_owner.Name + "(" + m_owner.Client.Account.Name + ") -> " + partner.Name + "(" + partner.Client.Account.Name + ") : " + TradeMoney + "coppers"); } } if (TradeMoney > 0 || m_partnerWindow.TradeMoney > 0) { // Now add the money m_owner.AddMoney(m_partnerWindow.TradeMoney, "You get {0}."); partner.AddMoney(TradeMoney, "You get {0}."); InventoryLogging.LogInventoryAction(m_owner, partner, eInventoryActionType.Trade, TradeMoney); InventoryLogging.LogInventoryAction(partner, m_owner, eInventoryActionType.Trade, m_partnerWindow.TradeMoney); m_owner.SaveIntoDatabase(); partner.SaveIntoDatabase(); } CloseTrade();// Close the Trade Window return(true); } }
protected GetTaxRequest BuildGetTaxRequest(PMQuote quote) { if (quote == null) { throw new PXArgumentException(ErrorMessages.ArgumentNullException); } BAccount cust = (BAccount)PXSelect <BAccount, Where <BAccount.bAccountID, Equal <Required <BAccount.bAccountID> > > > . Select(Base, quote.BAccountID); CR.Location loc = (CR.Location) PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > . Select(Base, quote.BAccountID, quote.LocationID); IAddressBase addressFrom = GetFromAddress(quote); IAddressBase addressTo = GetToAddress(quote); if (addressFrom == null) { throw new PXException(CR.Messages.FailedGetFromAddressCR); } if (addressTo == null) { throw new PXException(CR.Messages.FailedGetToAddressCR); } GetTaxRequest request = new GetTaxRequest(); request.CompanyCode = CompanyCodeFromBranch(quote.TaxZoneID, Base.Accessinfo.BranchID); request.CurrencyCode = quote.CuryID; request.CustomerCode = cust.AcctCD; request.OriginAddress = AddressConverter.ConvertTaxAddress(addressFrom); request.DestinationAddress = AddressConverter.ConvertTaxAddress(addressTo); request.DocCode = string.Format("CR.{0}", quote.OpportunityID); request.DocDate = quote.DocumentDate.GetValueOrDefault(); request.Discount = quote.CuryLineDocDiscountTotal.GetValueOrDefault(); int mult = 1; if (!string.IsNullOrEmpty(loc.CAvalaraCustomerUsageType)) { request.CustomerUsageType = loc.CAvalaraCustomerUsageType; } if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber)) { request.ExemptionNo = loc.CAvalaraExemptionNumber; } request.DocType = TaxDocumentType.SalesOrder; var select = PXSelectJoin <CROpportunityProducts, LeftJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <CROpportunityProducts.inventoryID> >, LeftJoin <Account, On <Account.accountID, Equal <InventoryItem.salesAcctID> > > >, Where <CROpportunityProducts.quoteID, Equal <Required <PMQuote.quoteID> > >, OrderBy <Asc <CROpportunityProducts.lineNbr> > > .Select(Base, quote.QuoteID); foreach (PXResult <CROpportunityProducts, InventoryItem, Account> res in select) { CROpportunityProducts tran = (CROpportunityProducts)res; InventoryItem item = (InventoryItem)res; Account salesAccount = (Account)res; var line = new TaxCartItem(); line.Index = tran.LineNbr ?? 0; line.Amount = mult * tran.CuryAmount.GetValueOrDefault(); line.Description = tran.Descr; line.DestinationAddress = request.DestinationAddress; line.OriginAddress = request.OriginAddress; line.ItemCode = item.InventoryCD; line.Quantity = tran.Qty.GetValueOrDefault(); line.Discounted = request.Discount > 0; line.RevAcct = salesAccount.AccountCD; line.TaxCode = tran.TaxCategoryID; request.CartItems.Add(line); } return(request); }