// Use this for initialization
    public ServerCraftingRecipes()
    {
        functionName = "Crafting Recipes";
        // Database tables name
        tableName = "crafting_recipes";
        functionTitle =  "Crafting Recipe Configuration";
        loadButtonLabel =  "Load Crafting Recipes";
        notLoadedText =  "No Crafting Recipe loaded.";
        // Init
        dataRegister = new Dictionary<int, CraftingRecipe> ();

        editingDisplay = new CraftingRecipe ();
        originalDisplay = new CraftingRecipe ();
    }
    public static bool tryFloorCraft(CraftingRecipe recipe, Vector3 pos)
    {
        List <ItemStack> itemStacks = Item.getItemStackInRadius(pos, floorCraftingRadius);

        if (canCraftRecipe(recipe, itemStacks))
        {
            List <Entity> items = GameManager.getEntityInRadius(ReuseableGameObject.ITEM_ENTITY, pos, floorCraftingRadius);
            foreach (ItemStack neededItem in recipe.requiredItems)
            {
                int neededAmount = neededItem.getAmount();
                foreach (Entity e in items)
                {
                    Item      item      = (Item)e;
                    ItemStack itemStack = item.getItemStack();
                    if (itemStack.Equals(neededItem))
                    {
                        if (itemStack.getAmount() > neededAmount)
                        {
                            itemStack.setAmount(itemStack.getAmount() - neededAmount);
                            neededAmount = 0;
                        }
                        else
                        {
                            neededAmount -= itemStack.getAmount();
                            item.remove();
                        }
                    }
                    if (neededAmount <= 0)
                    {
                        break;
                    }
                }
            }
            foreach (ItemStack item in recipe.getResults())
            {
                new Item(item, new Location(pos + new Vector3(0, 0.5f, 0)));;
            }
            return(true);
        }
        return(false);
    }
 private void UpdateCraftingDisplay()
 {
     if (craftingButtons == null)
     {
         return;
     }
     foreach (ItemType itemType in craftingButtons.Keys)
     {
         GameObject     btn        = craftingButtons[itemType];
         CraftingRecipe itemRecipe = ItemRegistry.GetCraftingRecipeForType(itemType);
         if (itemCollector.Craftable(itemRecipe))
         {
             btn.SetActive(true);
             btn.GetComponent <Button>().interactable = true;
         }
         else
         {
             btn.GetComponent <Button>().interactable = false;
         }
     }
 }
示例#4
0
        static public void Tra_MoonBridge(SPlayer player)
        {
            List <BuildingTech> its = Globals.GetTypeFromDB <BuildingTech>();

            its = its.FindAll(o => o.dbName.Equals("BUILDING_TECH-MOON_BRIDGE") && !player.unlockedTechs.Contains(o.dbName));

            foreach (var v in its)
            {
                foreach (var y in v.unlockRecipes)
                {
                    CraftingRecipe cr = player.unlockedRecipes.Find(o => o.recipeSource == y.ritualRecipe.dbName);
                    if (cr == null)
                    {
                        cr = CraftingRecipe.FactoryFrom(y.ritualRecipe);
                        cr.SetUnlockLevel(5);
                        player.unlockedRecipes.Add(cr);
                    }
                }
                player.unlockedTechs.Add(v.dbName);
            }
        }
示例#5
0
    private void CraftItem(CraftingRecipe recipe)
    {
        List <int> availableSlots = CheckAvailableSlots();

        if (availableSlots.Count >= 3)
        {
            Stack <Item> stack = new Stack <Item>();
            stack.Push(recipe.craftedItem);
            AddItemToSlot(availableSlots[0], stack);
            inventory.AddAt(availableSlots[0], stack);

            SpendMaterials();

            inventory.itemEvent.Raise();
            stackedEvent.Raise();
        }
        else
        {
            Debug.Log("Not enough open slots");
        }
    }
示例#6
0
        static public void Tra_UnlockAllFoodRecipes(SPlayer player)
        {
            List <ItemTech> its = Globals.GetTypeFromDB <ItemTech>();

            its = its.FindAll(o => o.dbName.StartsWith("ITEM_TECH-COOKING") && !player.unlockedTechs.Contains(o.dbName));

            foreach (var v in its)
            {
                foreach (var y in v.unlockRecipes)
                {
                    CraftingRecipe cr = player.unlockedRecipes.Find(o => o.recipeSource == y.itemRecipe.dbName);
                    if (cr == null)
                    {
                        cr = CraftingRecipe.FactoryFrom(y.itemRecipe);
                        cr.SetUnlockLevel(2);
                        player.unlockedRecipes.Add(cr);
                    }
                }
                player.unlockedTechs.Add(v.dbName);
            }
        }
        private void GraphicsEvents_OnPostRenderGuiEvent(object sender, EventArgs e)
        {
            GameMenu gm = null;

            if ((gm = (Game1.activeClickableMenu as GameMenu)) != null &&
                gm.currentTab == 4)
            {
                CraftingPage cpage =
                    (CraftingPage)Helper.Reflection
                    .GetPrivateField <List <IClickableMenu> >(gm, "pages").GetValue()[4];
                CraftingRecipe cr = Helper.Reflection
                                    .GetPrivateField <CraftingRecipe>(cpage, "hoverRecipe").GetValue();
                Point p = Game1.getMousePosition();

                if (cpage != null && cr != null)
                {
                    DrawHoverTextBox(Game1.smallFont, "Number crafted: " + Game1.player.craftingRecipes[cr.name],
                                     p.X + 31, p.Y - 30);
                }
            }
        }
        private FindCraftingRecipeResult MatchRecipe(Slot[,] craftingGrid, CraftingRecipe recipe, int xOffset, int yOffset)
        {
            var gridWidth  = craftingGrid.GetUpperBound(0) + 1;
            var gridHeight = craftingGrid.GetUpperBound(1) + 1;

            var hasMatched = new bool[gridWidth, gridHeight];
            var after      = (Slot[, ])craftingGrid.Clone();

            for (int i = 0; i < recipe.Inputs.Length; i++)
            {
                ref var recipeSlot = ref recipe.Inputs[i];

                // Anywhere, 稍后处理
                if (recipeSlot.X < 0 || recipeSlot.Y < 0)
                {
                    continue;
                }

                var     x        = recipeSlot.X + xOffset;
                var     y        = recipeSlot.Y + yOffset;
                ref var gridSlot = ref craftingGrid[x, y];
示例#9
0
 public void CraftItem(CraftingRecipe itemToCraft)
 {
     if (CheckItemsMissing(itemToCraft).Count == 0)
     {
         if (itemToCraft.processTime > 0)
         {
             currentItemProcessing = itemToCraft.itemProduced;
             currentProcessState   = processState.currentlyProcessing;
             processTimer          = itemToCraft.processTime;
             craftingMenu.UpdateProcessing();
         }
         else
         {
             outputInventory.AddItem(itemToCraft.itemProduced);
         }
         foreach (Item item in itemToCraft.requiredIngredients)
         {
             playerInventory.RemoveItem(item);
         }
     }
 }
        /// <summary>
        /// Reduces the cost of the crab pot - intended to be used if the player has the Tapper profession
        /// </summary>
        /// <param name="gameMenu">The game menu that needs its cost adjusted</param>
        private static void ReduceCrabPotCost(GameMenu gameMenu)
        {
            CraftingPage craftingPage = (CraftingPage)gameMenu.pages[GameMenu.craftingTab];

            List <Dictionary <ClickableTextureComponent, CraftingRecipe> > pagesOfCraftingRecipes =
                (List <Dictionary <ClickableTextureComponent, CraftingRecipe> >)GetInstanceField(craftingPage, "pagesOfCraftingRecipes");

            foreach (Dictionary <ClickableTextureComponent, CraftingRecipe> page in pagesOfCraftingRecipes)
            {
                foreach (ClickableTextureComponent key in page.Keys)
                {
                    CraftingRecipe recipe = page[key];
                    if (recipe.name == "Crab Pot")
                    {
                        CraftableItem         crabPot          = (CraftableItem)ItemList.Items[(int)ObjectIndexes.CrabPot];
                        Dictionary <int, int> randomizedRecipe = crabPot.LastRecipeGenerated;
                        ReduceRecipeCost(page[key], randomizedRecipe);
                    }
                }
            }
        }
示例#11
0
    public void MakeItem(CraftingRecipe recipe)
    {
        bool crafted = false;

        for (int i = 0; i < 9; i++)
        {
            if (toolbar.slots[i].itemSlot.stack.id == recipe.requiredItem)
            {
                if (toolbar.slots[i].itemSlot.stack.amount >= recipe.amountOfItem)
                {
                    toolbar.slots[i].itemSlot.Take(recipe.amountOfItem);
                    toolbar.slots[i].UpdateSlot();
                    crafted = true;
                }
            }
        }

        if (crafted)
        {
            for (int i = 0; i < 9; i++)
            {
                if (toolbar.slots[i].itemSlot.stack.id == recipe.outputItem)
                {
                    toolbar.slots[i].itemSlot.Add(recipe.amountOfOutput);
                    toolbar.slots[i].UpdateSlot();
                    return;
                }
            }
            for (int i = 0; i < 9; i++)
            {
                if (toolbar.slots[i].itemSlot.stack.id == 0)
                {
                    toolbar.slots[i].itemSlot.stack.id = recipe.outputItem;
                    toolbar.slots[i].itemSlot.Add(recipe.amountOfOutput);
                    toolbar.slots[i].UpdateSlot();
                    return;
                }
            }
        }
    }
 /// <summary>Patch for cheaper crafting recipes for Blaster and Tapper.</summary>
 private static void CraftingRecipeCtorPostfix(ref CraftingRecipe __instance)
 {
     try
     {
         if (__instance.name.Equals("Tapper") && Utility.LocalPlayerHasProfession("Tapper"))
         {
             __instance.recipeList = new Dictionary <int, int>
             {
                 { 388, 25 },                            // wood
                 { 334, 1 }                              // copper bar
             };
         }
         else if (__instance.name.Contains("Bomb") && Utility.LocalPlayerHasProfession("Blaster"))
         {
             __instance.recipeList = __instance.name switch
             {
                 "Cherry Bomb" => new Dictionary <int, int>
                 {
                     { 378, 2 },                                 // copper ore
                     { 382, 1 }                                  // coal
                 },
                 "Bomb" => new Dictionary <int, int>
                 {
                     { 380, 2 },                                 // iron ore
                     { 382, 1 }                                  // coal
                 },
                 "Mega Bomb" => new Dictionary <int, int>
                 {
                     { 384, 2 },                                 // gold ore
                     { 382, 1 }                                  // coal
                 },
                 _ => __instance.recipeList
             };
         }
     }
     catch (Exception ex)
     {
         Monitor.Log($"Failed in {nameof(CraftingRecipeCtorPostfix)}:\n{ex}");
     }
 }
示例#13
0
    public Item Make(CraftingRecipe cr)
    {
        if (cr.Components.Any(comp => !Inventory.Contains(comp)))
        {
            Debug.LogError("Tried to craft something you could not make");
            return(null);
        }

        foreach (var comp in cr.Components)
        {
            Inventory.Remove(comp);
        }

        Item it = cr.Result.Item;

        if (it.ShouldCreateNewInstanceWhenPlayerObtained())
        {
            it = ScriptableObject.Instantiate(cr.Result.Item);
            it.CreatedFromOriginal = true;
            it.OnAfterObtained();

            if (it is Weapon)
            {
                ((Weapon)it).Level = CurrentQuest.Value.Level;
            }

            if (it is Armor)
            {
                ((Armor)it).Level = CurrentQuest.Value.Level;
            }

            if (it is Headgear)
            {
                ((Headgear)it).Level = CurrentQuest.Value.Level;
            }
        }

        Inventory.Add(it, cr.Result.Amount);
        return(it);
    }
示例#14
0
        private void SetCraftUI(CraftingRecipe recipe)
        {
            if (recipe != null)
            {
                var itemToCraft = ItemDatabase.getItemByID(recipe.OutputItem.Id);
                itemToCraft.Quantity = 1;

                var itemAlreadyThere = OutputSlot.GetItem();
                if (itemAlreadyThere == null)
                {
                    OutputSlot.AddItem(itemToCraft);
                    var dragDropItemComponent = OutputSlot.gameObject.GetComponentInChildren <DragAndDropItem>();
                    dragDropItemComponent.enabled = false;
                    OutputItemTitleText.text      = itemToCraft.Name;
                    OutputItemDescText.text       = itemToCraft.Description;
                    UseButton.interactable        = true;
                }
                else if (itemAlreadyThere != null && !itemAlreadyThere.Id.Equals(itemToCraft.Id))
                {
                    OutputSlot.RemoveItem();
                    OutputSlot.AddItem(itemToCraft);
                    var dragDropItemComponent = OutputSlot.gameObject.GetComponentInChildren <DragAndDropItem>();
                    dragDropItemComponent.enabled = false;
                    OutputItemTitleText.text      = itemToCraft.Name;
                    OutputItemDescText.text       = itemToCraft.Description;
                    UseButton.interactable        = true;
                }
                ;
            }
            else
            {
                OutputItemTitleText.text = "";
                OutputItemDescText.text  = "";
                if (OutputSlot.HasItem)
                {
                    OutputSlot.RemoveItem();
                }
                UseButton.interactable = false;
            }
        }
示例#15
0
    public bool CanCraftRecipe(CraftingRecipe recipe)
    {
        List <ItemStack> ingredients = recipe.IngredientsCopy;

        if (!HasItems(ingredients))
        {
            return(false);
        }

        List <Storage>   relatedInventories = new List <Storage>();
        List <ItemStack> results            = recipe.ResultsCopy;

        for (int i = 0; i < ingredients.Count; i++)
        {
            Item.Type type = ingredients[i].ItemType;
            Storage   inv  = GetAppropriateInventory(type);
            if (relatedInventories.Contains(inv))
            {
                continue;
            }
            List <ItemStack> invStacks = inv.CreateCopyOfStacks();
            ItemStack.RemoveItems(invStacks, ingredients);
            relatedInventories.Add(inv);

            for (int j = 0; j < results.Count; j++)
            {
                Item.Type resultItemType = results[i].ItemType;
                Storage   inv2           = GetAppropriateInventory(resultItemType);
                if (inv != inv2)
                {
                    continue;
                }
                if (!ItemStack.CanFit(invStacks, results[i]))
                {
                    return(false);
                }
            }
        }
        return(true);
    }
示例#16
0
        private static string GenerateIngredientsList(CraftingRecipe craftingRecipe)
        {
            if (craftingRecipe.RequiredIngredients.Count == 0)
            {
                return("None");
            }

            StringBuilder stringBuilder = new StringBuilder();

            foreach (RecipeIngredient recipeIngredient in craftingRecipe.RequiredIngredients)
            {
                stringBuilder
                .Append("- ")
                .Append(recipeIngredient.RequiredAmount)
                .Append("x ")
                .Append(recipeIngredient.RequiredItem.ExpensiveName())
                .AppendLine()
                .AppendLine();
            }

            return(stringBuilder.ToString());
        }
示例#17
0
        private static string GenerateReagentsList(CraftingRecipe craftingRecipe)
        {
            if (craftingRecipe.RequiredReagents.Count == 0)
            {
                return("None");
            }

            StringBuilder stringBuilder = new StringBuilder();

            foreach (RecipeIngredientReagent ingredientReagent in craftingRecipe.RequiredReagents)
            {
                stringBuilder
                .Append("- ")
                .Append(ingredientReagent.RequiredAmount)
                .Append("u ")
                .Append(ingredientReagent.RequiredReagent.Name)
                .AppendLine()
                .AppendLine();
            }

            return(stringBuilder.ToString());
        }
示例#18
0
文件: Mob.cs 项目: Ville1/3DSurvival
    public bool Craft(CraftingRecipe recipe, out string message)
    {
        message = null;
        if (!Can_Craft(recipe, out message))
        {
            return(false);
        }
        foreach (KeyValuePair <string, int> input in recipe.Inputs)
        {
            for (int i = 0; i < input.Value; i++)
            {
                Inventory.Remove(input.Key);
            }
        }
        ActionData data = new ActionData(recipe.Name, string.Format(PROGRESS_TEXT, recipe.Name, 0), ActionType.Craft, false, null);

        data.Recipe            = recipe;
        data.Progress          = 0.0f;
        data.Relative_Progress = 0.0f;
        actions.Add(data);
        return(true);
    }
示例#19
0
文件: Mob.cs 项目: Ville1/3DSurvival
 public bool Can_Craft(CraftingRecipe recipe, out string message)
 {
     //TODO: Check inventory space with input <-> output
     message = null;
     if (!Can_Work(out message, true))
     {
         return(false);
     }
     if (!Has_Skills(recipe.Required_Skills, out message))
     {
         return(false);
     }
     if (!Has_Tools(recipe.Required_Tools, out message))
     {
         return(false);
     }
     if (!Has_Items(recipe.Inputs, out message))
     {
         return(false);
     }
     return(true);
 }
示例#20
0
    public void craftItem(string productName)
    {
        CraftingRecipe myRecipe = playerInventoryScript.findRecipeWithProductName(productName);
        bool           canBuy   = true;

        for (int i = 0; i < myRecipe.materialNames.Length; i++)
        {
            if (playerInventoryScript.findItemQuantityInPlayerInventory(myRecipe.materialNames [i]) < myRecipe.materialQuantities [i])
            {
                canBuy = false;
                break;
            }
        }
        if (canBuy)
        {
            playerInventoryScript.addObjectToPlayerInventory(myRecipe.productQuantity, myRecipe.productName, myRecipe.productDisplayName, false, Vector3.zero);
            for (int i = 0; i < myRecipe.materialNames.Length; i++)
            {
                playerInventoryScript.takeItemFromPlayerInventory(myRecipe.materialQuantities [i], myRecipe.materialNames [i]);
            }
        }
    }
示例#21
0
    private void SetCraftingRecipe(CraftingRecipe newCraftingRecipe, bool force)
    {
        if (!force)
        {
            Inventory[] equipments = FindObjectsOfType <Inventory>();
            for (int i = 0; i < equipments.Length; i++)
            {
                if (equipments[i].inventoryUI.name == "EquipmentUI")
                {
                    Equipment = equipments[i];
                }
                else
                {
                    HubChest = equipments[i];
                }
            }
            force = true;
        }
        recipe = newCraftingRecipe;

        if (recipe != null)
        {
            int slotIndex = 0;
            slotIndex = SetSlots(recipe.Materials, slotIndex);
            arrowParent.SetSiblingIndex(slotIndex);
            slotIndex = SetSlots(recipe.Results, slotIndex);

            for (int i = slotIndex; i < slots.Length; i++)
            {
                slots[i].transform.parent.gameObject.SetActive(false);
            }

            gameObject.SetActive(true);
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
示例#22
0
    /// <summary>
    /// Removes the required items for the craftingRecipe
    /// </summary>
    /// <param name="recipe">The recipe to craft</param>
    /// <returns>Whether there are enough materials to craft this recipe</returns>
    public bool RemoveItemsForCrafting(CraftingRecipe recipe)
    {
        for (int i = 0; i < recipe.requiredItems.Count; i++)
        {
            var requiredItem = recipe.requiredItems[i];
            if (!CheckAmountById(requiredItem.item.Id, requiredItem.amount * recipe.amountToCraft))
            {
                Debug.Log($"Not enough {requiredItem.item.name} to craft {recipe.result.item.name}");
                FeedUI.Instance.AddFeedItem($"Not enough { requiredItem.item.name} to craft!", recipe.result.item.Sprite, FeedItem.Type.Fail);
                return(false);
            }
        }

        for (int i = 0; i < recipe.requiredItems.Count; i++)
        {
            var requiredItem = recipe.requiredItems[i];
            RemoveItemById(requiredItem.item.Id, requiredItem.amount * recipe.amountToCraft);
        }
        PlayerUpdateSelectedItem();

        return(true);
    }
示例#23
0
 public void SetButton(CraftingRecipeButton button)
 {
     if (recipe != null)
     {
         recipe = null;
         craftButton.gameObject.GetComponent <Image>().sprite = buttonNormal;
         if (craftButton == button.gameObject.GetComponent <Button>())
         {
             craftButton = null;
             return;
         }
     }
     recipe = button.recipe;
     max    = Mathf.Min(button.maxQuantity, recipe.craftedItem.maxQuantity);
     if (quantity > max)
     {
         quantity = max;
     }
     qtext.text  = quantity.ToString();
     craftButton = button.gameObject.GetComponent <Button>();
     craftButton.gameObject.GetComponent <Image>().sprite = buttonSelect;
 }
示例#24
0
        private void clickCraftingRecipe(ClickableTextureComponent c, bool playSound)
        {
            CraftingRecipe recipe  = this.GetCurrentPage()[c];
            Item           crafted = recipe.createItem();

            Game1.player.checkForQuestComplete(null, -1, -1, crafted, null, 2, -1);

            if (this.heldItem == null)
            {
                recipe.consumeIngredients();
                this.heldItem = crafted;

                if (playSound)
                {
                    Game1.playSound("coin");
                }
            }
            else if (this.heldItem.Name.Equals(crafted.Name) && this.heldItem.Stack + recipe.numberProducedPerCraft - 1 < this.heldItem.maximumStackSize())
            {
                recipe.consumeIngredients();
                this.heldItem.Stack += recipe.numberProducedPerCraft;

                if (playSound)
                {
                    Game1.playSound("coin");
                }
            }

            Game1.player.craftingRecipes[recipe.name] += recipe.numberProducedPerCraft;

            Game1.stats.checkForCraftingAchievements();

            if (Game1.options.gamepadControls && this.heldItem != null && Game1.player.couldInventoryAcceptThisItem(this.heldItem))
            {
                Game1.player.addItemToInventoryBool(this.heldItem);
                this.heldItem = null;
            }
        }
示例#25
0
        private void OnMenuChanged(object sender, MenuChangedEventArgs e)
        {
            if (!Context.IsWorldReady)
            {
                return;                        //World Hasn't Loaded yet, it's definitely not the menu we want
            }
            if (e.NewMenu == null)
            {
                return;                    //Menu was closed
            }
            if (!(e.NewMenu is ShopMenu))
            {
                return;
            }
            if (!(Helper.Reflection.GetField <string>(e.NewMenu, "storeContext").GetValue() == "Saloon"))
            {
                return;
            }
            ShopMenu menu = (ShopMenu)e.NewMenu;
            //Naming is hard. This is the most recent date that a recipe can be available.
            // Example, it's Y2,S27 (Day 167) using the default config setting of 28 days (making this variable 139) Complete Breakfast (aired day 133) would be available, but Luck Lunch (day 140) would not.
            int latestRecipeDate = Game1.Date.TotalDays - Config.DaysAfterAiring;

            foreach (var kvp in FirstAirDate.Where(x => x.Value <= latestRecipeDate && !Game1.player.cookingRecipes.Keys.Contains(x.Key)))
            {
                var tmp  = new CraftingRecipe(kvp.Key, true);
                var tmp2 = new SVObject();
                tmp2.Type             = "Cooking";
                tmp2.IsRecipe         = true;
                tmp2.Stack            = 1;
                tmp2.Name             = tmp.name;
                tmp2.ParentSheetIndex = tmp.getIndexOfMenuView();
                menu.forSale.Add(tmp2);
                menu.itemPriceAndStock.Add(tmp2, new int[2] {
                    Config.Price, 1
                });
            }
        }
示例#26
0
        private void loadRecipes(string workingPath)
        {
            if (File.Exists(workingPath + "/recipies.xml"))
            {
                //We are modifying catagories, lets go
                XmlDocument craftingDoc = new XmlDocument();
                //Load the file
                craftingDoc.LoadXml(System.IO.File.ReadAllText(workingPath += "/recipies.xml"));


                //...Not gunna lie, lifted from TDL IL Code
                foreach (XmlNode current in craftingDoc.ChildNodes)
                {
                    if (current.Name != "crafting")
                    {
                        continue;
                    }
                    foreach (XmlNode xmlNodes in current.ChildNodes)
                    {
                        if (xmlNodes.Name != "recipe")
                        {
                            continue;
                        }
                        CraftingRecipe craftingRecipe = new CraftingRecipe();
                        craftingRecipe.Load(xmlNodes);
                        if (!CraftingDefinitions.recipes.ContainsKey(craftingRecipe.name))
                        {
                            CraftingDefinitions.recipes[craftingRecipe.name] = craftingRecipe;
                        }
                        else
                        {
                            TDLLogging.LogError("reci_1", string.Concat("ERROR - Duplicate recipe name in recipies.xml: ", craftingRecipe.name));
                            CraftingDefinitions.recipes[string.Concat(craftingRecipe.name, "_error")] = craftingRecipe;
                        }
                    }
                }
            }
        }
    //TODO:: Check to make sure you have the correct items in the inventory before crafting the item.
    //TODO:: Implement multiples of input items and multiples of output items
    //TODO:: Add scripts to the item slots with hovers on so you can see things related to that item
    public void UpdateUIElementsOnClick(CraftingRecipe clickedRecipe)
    {
        itemName.text = clickedRecipe.recipeName;
        //itemImage.enabled = true;
        //itemImage.sprite = clickedRecipe.re;

        foreach (Item item in clickedRecipe.inputItems)
        {//Create Input Items Interface.
            GameObject inputItemImages = Instantiate(itemSlot, inputItemPanel);
            inputItemImages.GetComponent <Image>().sprite = item.ItemImage;
        }
        foreach (Item item in clickedRecipe.outputItems)
        {//Create Output Items Interface.
            GameObject outputItemsImages = Instantiate(itemSlot, outputItemPanel);
            outputItemsImages.GetComponent <Image>().sprite = item.ItemImage;

            localOutputItems.Add(item);
            Debug.Log(localOutputItems);
        }
        foreach (Item item in clickedRecipe.toolsRequired)
        {//Create Tools Items Interface.
        }
    }
    private void SetCraftingRecipe(CraftingRecipe newCraftingRecipe)
    {
        craftingRecipe = newCraftingRecipe;

        if (craftingRecipe != null)
        {
            int slotIndex = 0;
            slotIndex = SetSlots(craftingRecipe.Materials, slotIndex);
            arrowParent.SetSiblingIndex(slotIndex);
            slotIndex = SetSlots(craftingRecipe.Results, slotIndex);

            for (int i = slotIndex; i < itemSlots.Length; i++)
            {
                itemSlots[i].transform.parent.gameObject.SetActive(false);
            }

            gameObject.SetActive(true);
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
        public void Parse(HabboHotel.GameClients.GameClient Session, ClientPacket Packet)
        {
            var result = Packet.PopString();

            CraftingRecipe recipe = null;

            foreach (CraftingRecipe Receta in RavenEnvironment.GetGame().GetCraftingManager().CraftingRecipes.Values)
            {
                if (Receta.Result.Contains(result))
                {
                    recipe = Receta;
                    break;
                }
            }

            var Final = RavenEnvironment.GetGame().GetCraftingManager().GetRecipe(recipe.Id);

            if (Final == null)
            {
                return;
            }
            Session.SendMessage(new CraftingRecipeComposer(Final));
        }
    // Load Database Data
    public override void Load()
    {
        if (!dataLoaded) {
            // Clean old data
            dataRegister.Clear ();
            displayKeys.Clear ();

            // Read all entries from the table
            string query = "SELECT * FROM " + tableName;

            // If there is a row, clear it.
            if (rows != null)
                rows.Clear ();

            // Load data
            rows = DatabasePack.LoadData (DatabasePack.contentDatabasePrefix, query);
            //Debug.Log("#Rows:"+rows.Count);
            // Read all the data
            if ((rows!=null) && (rows.Count > 0)) {
                foreach (Dictionary<string,string> data in rows) {
                    //foreach(string key in data.Keys)
                    //	Debug.Log("Name[" + key + "]:" + data[key]);
                    //return;
                    CraftingRecipe display = new CraftingRecipe ();
                    display.id = int.Parse (data ["id"]);
                    display.name = data ["name"];
                    display.icon = data ["icon"];
                    display.resultItemID = int.Parse(data["resultItemID"]);
                    display.skillID = int.Parse(data["skillID"]);
                    display.skillLevelReq = int.Parse(data["skillLevelReq"]);
                    display.stationReq = data ["stationReq"];
                    display.recipeItemID = int.Parse(data["recipeItemID"]);
                    display.allowDyes = bool.Parse(data["allowDyes"]);
                    display.allowEssences = bool.Parse(data["allowEssences"]);
                    for (int i = 1; i <= display.maxEntries; i++) {
                        int itemId = int.Parse (data ["component" + i]);
                        int count = int.Parse (data ["component" + i + "count"]);
                        RecipeComponentEntry entry = new RecipeComponentEntry(itemId, count);
                        display.entries.Add(entry);
                    }

                    display.isLoaded = true;
                    //Debug.Log("Name:" + display.name  + "=[" +  display.id  + "]");
                    dataRegister.Add (display.id, display);
                    displayKeys.Add (display.id);
                }
                LoadSelectList();
            }
            dataLoaded = true;
        }
    }
        /// <inheritdoc />
        public override ISubject GetSubject(IClickableMenu menu, int cursorX, int cursorY)
        {
            IClickableMenu targetMenu = (menu as GameMenu)?.GetCurrentPage() ?? menu;

            switch (targetMenu)
            {
            /****
            ** Inventory
            ****/
            // chest
            case MenuWithInventory inventoryMenu when !(menu is FieldOfficeMenu):
            {
                Item item = Game1.player.CursorSlotItem ?? inventoryMenu.heldItem ?? inventoryMenu.hoveredItem;
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
            }
            break;

            // inventory
            case InventoryPage inventory:
            {
                Item item = Game1.player.CursorSlotItem ?? this.Reflection.GetField <Item>(inventory, "hoveredItem").GetValue();
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
            }
            break;

            // shop
            case ShopMenu shopMenu:
            {
                ISalable entry = shopMenu.hoveredItem;
                if (entry is Item item)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
                if (entry is MovieConcession snack)
                {
                    return(new MovieSnackSubject(this.GameHelper, snack));
                }
            }
            break;

            // toolbar
            case Toolbar _:
            {
                // find hovered slot
                List <ClickableComponent> slots       = this.Reflection.GetField <List <ClickableComponent> >(menu, "buttons").GetValue();
                ClickableComponent        hoveredSlot = slots.FirstOrDefault(slot => slot.containsPoint(cursorX, cursorY));
                if (hoveredSlot == null)
                {
                    return(null);
                }

                // get inventory index
                int index = slots.IndexOf(hoveredSlot);
                if (index < 0 || index > Game1.player.Items.Count - 1)
                {
                    return(null);
                }

                // get hovered item
                Item item = Game1.player.Items[index];
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
            }
            break;


            /****
            ** GameMenu
            ****/
            // collections menu
            // derived from CollectionsPage::performHoverAction
            case CollectionsPage collectionsTab:
            {
                int currentTab = this.Reflection.GetField <int>(collectionsTab, "currentTab").GetValue();
                if (currentTab == CollectionsPage.achievementsTab || currentTab == CollectionsPage.secretNotesTab || currentTab == CollectionsPage.lettersTab)
                {
                    break;
                }

                int currentPage = this.Reflection.GetField <int>(collectionsTab, "currentPage").GetValue();

                foreach (ClickableTextureComponent component in collectionsTab.collections[currentTab][currentPage])
                {
                    if (component.containsPoint(cursorX, cursorY))
                    {
                        int     itemID = Convert.ToInt32(component.name.Split(' ')[0]);
                        SObject obj    = new SObject(itemID, 1);
                        return(this.BuildSubject(obj, ObjectContext.Inventory, knownQuality: false));
                    }
                }
            }
            break;

            // crafting menu
            case CraftingPage crafting:
            {
                // player inventory item
                Item item = this.Reflection.GetField <Item>(crafting, "hoverItem").GetValue();
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }

                // crafting recipe
                CraftingRecipe recipe = this.Reflection.GetField <CraftingRecipe>(crafting, "hoverRecipe").GetValue();
                if (recipe != null)
                {
                    return(this.BuildSubject(recipe.createItem(), ObjectContext.Inventory));
                }
            }
            break;

            // profile tab
            case ProfileMenu profileMenu:
            {
                // hovered item
                Item item = profileMenu.hoveredItem;
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
            }
            break;

            /****
            ** Other menus
            ****/
            // community center bundle menu
            case JunimoNoteMenu bundleMenu:
            {
                // hovered inventory item
                {
                    Item item = this.Reflection.GetField <Item>(menu, "hoveredItem").GetValue();
                    if (item != null)
                    {
                        return(this.BuildSubject(item, ObjectContext.Inventory));
                    }
                }

                // list of required ingredients
                for (int i = 0; i < bundleMenu.ingredientList.Count; i++)
                {
                    if (bundleMenu.ingredientList[i].containsPoint(cursorX, cursorY))
                    {
                        Bundle bundle     = this.Reflection.GetField <Bundle>(bundleMenu, "currentPageBundle").GetValue();
                        var    ingredient = bundle.ingredients[i];
                        var    item       = this.GameHelper.GetObjectBySpriteIndex(ingredient.index, ingredient.stack);
                        item.Quality = ingredient.quality;
                        return(this.BuildSubject(item, ObjectContext.Inventory));
                    }
                }

                // list of submitted ingredients
                foreach (ClickableTextureComponent slot in bundleMenu.ingredientSlots)
                {
                    if (slot.item != null && slot.containsPoint(cursorX, cursorY))
                    {
                        return(this.BuildSubject(slot.item, ObjectContext.Inventory));
                    }
                }
            }
            break;

            // Fern Islands field office menu
            case FieldOfficeMenu fieldOfficeMenu:
            {
                ClickableComponent slot = fieldOfficeMenu.pieceHolders.FirstOrDefault(p => p.containsPoint(cursorX, cursorY));
                if (slot != null)
                {
                    // donated item
                    if (slot.item != null)
                    {
                        return(this.BuildSubject(slot.item, ObjectContext.Inventory, knownQuality: false));
                    }

                    // empty slot
                    if (int.TryParse(slot.label, out int itemId))
                    {
                        return(this.BuildSubject(new SObject(itemId, 1), ObjectContext.Inventory, knownQuality: false));
                    }
                }
            }
            break;

            /****
            ** Convention (for mod support)
            ****/
            default:
            {
                Item item = this.Reflection.GetField <Item>(menu, "HoveredItem", required: false)?.GetValue();        // ChestsAnywhere
                if (item != null)
                {
                    return(this.BuildSubject(item, ObjectContext.Inventory));
                }
            }
            break;
            }

            return(null);
        }
示例#32
0
 internal static bool Prefix(ref CraftingRecipe __instance)
 {
     //consumeIngredients
     ConsumeIngredients(__instance);
     return(false);
 }
    // Draw the loaded list
    public override void DrawLoaded(Rect box)
    {
        // Setup the layout
        Rect pos = box;
        pos.x += ImagePack.innerMargin;
        pos.y += ImagePack.innerMargin;
        pos.width -= ImagePack.innerMargin;
        pos.height = ImagePack.fieldHeight;

        if (dataRegister.Count <= 0) {
            pos.y += ImagePack.fieldHeight;
            ImagePack.DrawLabel (pos.x, pos.y, "You must create a Crafting Recipe before edit it.");
            return;
        }

        // Draw the content database info
        ImagePack.DrawLabel (pos.x, pos.y, "Crafting Recipe Configuration");

        if (newItemCreated) {
            newItemCreated = false;
            LoadSelectList();
            newSelectedDisplay = displayKeys.Count - 1;
        }

        // Draw data Editor
        if (newSelectedDisplay != selectedDisplay) {
        selectedDisplay = newSelectedDisplay;
        int displayKey = displayKeys [selectedDisplay];
        editingDisplay = dataRegister [displayKey];
            originalDisplay = editingDisplay.Clone();
        }

        //if (!displayList.showList) {
            pos.y += ImagePack.fieldHeight;
            pos.x -= ImagePack.innerMargin;
            pos.y -= ImagePack.innerMargin;
            pos.width += ImagePack.innerMargin;
            DrawEditor (pos, false);
            pos.y -= ImagePack.fieldHeight;
            //pos.x += ImagePack.innerMargin;
            pos.y += ImagePack.innerMargin;
            pos.width -= ImagePack.innerMargin;
        //}

        if (state != State.Loaded) {
        // Draw combobox
        pos.width /= 2;
        pos.x += pos.width;
        newSelectedDisplay = ImagePack.DrawCombobox (pos, "", selectedDisplay, displayList);
        pos.x -= pos.width;
        pos.width *= 2;
        }
    }
    // Edit or Create
    public override void DrawEditor(Rect box, bool newItem)
    {
        if (!linkedTablesLoaded) {
            // Load items
            LoadItemList();
            LoadSkillOptions();
            stationOptions = ServerOptionChoices.LoadAtavismChoiceOptions("Crafting Station", true);
            linkedTablesLoaded = true;
        }
        // Setup the layout
        Rect pos = box;
        pos.x += ImagePack.innerMargin;
        pos.y += ImagePack.innerMargin;
        pos.width -= ImagePack.innerMargin;
        pos.height = ImagePack.fieldHeight;

        // Draw the content database info
        if (newItem) {
            ImagePack.DrawLabel (pos.x, pos.y, "Create a new crafting recipe");
            pos.y += ImagePack.fieldHeight;
        }

        editingDisplay.name = ImagePack.DrawField (pos, "Name:", editingDisplay.name, 0.5f);
        pos.width /= 2;
        pos.y += ImagePack.fieldHeight;
        int selectedItem = GetPositionOfItem(editingDisplay.recipeItemID);
        selectedItem = ImagePack.DrawSelector (pos, "Recipe:", selectedItem, itemsList);
        editingDisplay.recipeItemID = itemIds[selectedItem];
        //pos.x += pos.width;
        //editingDisplay.icon = ImagePack.DrawTextureAsset (pos, "Icon:", editingDisplay.icon);
        //pos.x -= pos.width;
        pos.y += ImagePack.fieldHeight;
        selectedItem = GetPositionOfItem(editingDisplay.resultItemID);
        selectedItem = ImagePack.DrawSelector (pos, "Creates Item:", selectedItem, itemsList);
        editingDisplay.resultItemID = itemIds[selectedItem];
        pos.y += 1.5f * ImagePack.fieldHeight;
        ImagePack.DrawLabel (pos.x, pos.y, "Requirements");
        pos.y += 1.5f * ImagePack.fieldHeight;
        int selectedSkill = GetPositionOfSkill (editingDisplay.skillID);
        selectedSkill = ImagePack.DrawSelector (pos, "Skill:", selectedSkill, skillOptions);
        editingDisplay.skillID = skillIds [selectedSkill];
        pos.x += pos.width;
        editingDisplay.skillLevelReq = ImagePack.DrawField (pos, "Skill Level:", editingDisplay.skillLevelReq);
        pos.x -= pos.width;
        pos.y += ImagePack.fieldHeight;
        editingDisplay.stationReq = ImagePack.DrawSelector (pos, "Station Req:", editingDisplay.stationReq, stationOptions);
        pos.x += pos.width;
        editingDisplay.qualityChangeable = ImagePack.DrawToggleBox (pos, "Changes Quality:", editingDisplay.qualityChangeable);
        pos.x -= pos.width;
        pos.y += ImagePack.fieldHeight;
        editingDisplay.allowDyes = ImagePack.DrawToggleBox (pos, "Allows Dyes:", editingDisplay.allowDyes);
        pos.x += pos.width;
        editingDisplay.allowEssences = ImagePack.DrawToggleBox (pos, "Allows Essences:", editingDisplay.allowEssences);
        pos.x -= pos.width;
        pos.y += 1.5f * ImagePack.fieldHeight;
        ImagePack.DrawLabel (pos.x, pos.y, "Items Required:");
        pos.y += 1.5f * ImagePack.fieldHeight;
        for (int i = 0; i < editingDisplay.maxEntries; i++) {
            if (editingDisplay.entries.Count <= i)
                editingDisplay.entries.Add(new RecipeComponentEntry(-1, 1));
            if (i == 0) {
                ImagePack.DrawText(pos, "Row 1");
                pos.y += ImagePack.fieldHeight;
            } else if (i == 4) {
                ImagePack.DrawText(pos, "Row 2");
                pos.y += ImagePack.fieldHeight;
            } else if (i == 8) {
                ImagePack.DrawText(pos, "Row 3");
                pos.y += ImagePack.fieldHeight;
            } else if (i == 12) {
                ImagePack.DrawText(pos, "Row 4");
                pos.y += ImagePack.fieldHeight;
            }
            selectedItem = GetPositionOfItem(editingDisplay.entries[i].itemId);
            selectedItem = ImagePack.DrawSelector (pos, "Item " + (i+1) + ":", selectedItem, itemsList);
            editingDisplay.entries[i].itemId = itemIds[selectedItem];
            pos.x += pos.width;
            editingDisplay.entries[i].count = ImagePack.DrawField (pos, "Count:", editingDisplay.entries[i].count);
            pos.x -= pos.width;
            pos.y += ImagePack.fieldHeight;
        }
        pos.width = pos.width * 2;

        // Save data
        pos.x -= ImagePack.innerMargin;
        pos.y += 1.4f * ImagePack.fieldHeight;
        pos.width /=3;
        if (ImagePack.DrawButton (pos.x, pos.y, "Save Data")) {
            if (newItem)
                InsertEntry ();
            else
                UpdateEntry ();

            state = State.Loaded;
        }

        // Delete data
        if (!newItem) {
            pos.x += pos.width;
            if (ImagePack.DrawButton (pos.x, pos.y, "Delete Data")) {
                DeleteEntry ();
                newSelectedDisplay = 0;
                state = State.Loaded;
            }
        }

        // Cancel editing
        pos.x += pos.width;
        if (ImagePack.DrawButton (pos.x, pos.y, "Cancel")) {
            editingDisplay = originalDisplay.Clone();
            if (newItem)
                state = State.New;
            else
                state = State.Loaded;
        }

        if (resultTimeout != -1 && resultTimeout > Time.realtimeSinceStartup) {
            pos.y += ImagePack.fieldHeight;
            ImagePack.DrawText(pos, result);
        }

        if (!newItem)
            EnableScrollBar (pos.y - box.y + ImagePack.fieldHeight + 28);
        else
            EnableScrollBar (pos.y - box.y + ImagePack.fieldHeight);
    }
 public override void CreateNewData()
 {
     editingDisplay = new CraftingRecipe ();
     originalDisplay = new CraftingRecipe ();
     selectedDisplay = -1;
 }