Inheritance: MonoBehaviour
Example #1
0
 public void BuildButton(ShopItem item, ShopMenu shopMenu)
 {
     ShopMenu         = shopMenu;
     ShopItem         = item;
     ItemName.text    = item.Item.itemName;
     ItemImage.sprite = item.Item.itemIcon;
     ItemPrice.text   = $"{item.Price}g";
 }
    public void ShowMenu(ShopMenu menu)
    {
        if (CurrentMenu != null)
            CurrentMenu.IsOpen =  false;

        CurrentMenu = menu;
        CurrentMenu.IsOpen = true;
    }
Example #3
0
        /// <summary>Helper method getting which item in the shop was clicked.</summary>
        /// <param name="reflection">Reflection helper.</param>
        /// <param name="shopMenu">Native shop menu.</param>
        /// <param name="p">Mouse location.</param>
        /// <returns>The clicked item or null if none was clicked.</returns>
        public static ISalable GetClickedShopItem(IReflectionHelper reflection, ShopMenu shopMenu, Point p)
        {
            var itemsForSale = reflection.GetField <List <ISalable> >(shopMenu, "forSale").GetValue();
            int index        = GetClickedItemIndex(reflection, shopMenu, p);

            Debug.Assert(index < itemsForSale.Count);
            return(index >= 0 ? itemsForSale[index] : null);
        }
Example #4
0
 public override void _Process(float delta)
 {
     if (canBeTalkedTo && Input.IsActionJustPressed("Continue") && !GameData.isPlayerTalking)
     {
         ShopMenu.StartShop(starterText, speakerName, itemsToSell);
         GameData.isPlayerTalking = true;
     }
 }
Example #5
0
 public ShopSetupEvent(ShopMenu menu, string owner, Dictionary <Item, int[]> itemsForSale, List <int> categoriesToSellHere, List <Item> forSale)
 {
     this.Menu             = menu;
     this.ShopOwner        = owner;
     this.ItemsForSale     = itemsForSale;
     this.CategoriesToSell = categoriesToSellHere;
     this.ForSale          = forSale;
 }
Example #6
0
 /// <summary>Constructs an instance.</summary>
 /// <param name="menu">The native shop menu.</param>
 /// <param name="item">The item to buy.</param>
 public SellAction(ShopMenu menu, Item item)
     : base(menu, item)
 {
     // Default amount
     // +1 before /2 ensures we get the number rounded UP
     this.Amount = (this.ClickedItem.Stack + 1) / 2;
     Log.TraceIfD($"[{nameof(SellAction)}] Instantiated for shop {menu} item {item}, GUID = {GUID}");
 }
    private void loadInventories(Scene scene, LoadSceneMode mode)
    {
        ShopMenu shopMenu = GameObject.Find("EventSystem").GetComponent <ShopMenu>();

        shopMenu.npcInv           = npcInv;
        shopMenu.playerInv        = GameObject.Find("WalkableCharacter").GetComponent <Inventory>();
        SceneManager.sceneLoaded -= loadInventories;
    }
Example #8
0
 /// <summary>
 /// Adds in ore to clint's shop.
 /// </summary>
 private static void AddOreToClintsShop(ShopMenu Menu)
 {
     AddItemToShop(Menu, ModCore.ObjectManager.resources.getOre("Tin", 1), ModCore.Configs.shops_blacksmithConfig.tinOreSellPrice, -1);
     AddItemToShop(Menu, ModCore.ObjectManager.resources.getOre("Bauxite", 1), ModCore.Configs.shops_blacksmithConfig.bauxiteOreSellPrice, -1);
     AddItemToShop(Menu, ModCore.ObjectManager.resources.getOre("Lead", 1), ModCore.Configs.shops_blacksmithConfig.leadOreSellPrice, -1);
     AddItemToShop(Menu, ModCore.ObjectManager.resources.getOre("Silver", 1), ModCore.Configs.shops_blacksmithConfig.silverOreSellPrice, -1);
     AddItemToShop(Menu, ModCore.ObjectManager.resources.getOre("Titanium", 1), ModCore.Configs.shops_blacksmithConfig.titaniumOreSellPrice, -1);
 }
Example #9
0
    /// <summary> Shows the tower menu (see <see cref="towerMenuPrefab"/>) at the same
    /// screen position as the parameter LymphNode <paramref name="lymphNode"/>. Called
    /// by a LymphNode object when it is clicked with a tower on it. </summary>
    internal GameObject ShowTowerMenu(Transform lymphNode, Tower tower)
    {
        GameObject towerMenu = Instantiate(towerMenuPrefab, new Vector3(0f, 0f, -1.2f), activeGameUIPanel.rotation);

        towerMenu.transform.SetParent(activeGameUIPanel, false);

        // if this tower is not upgradeable (i.e. the current tower...
        // ...level is the last one), don't show the "upgrade" button
        int currLevel = tower.GetCurrentLevel();
        //int maxLevel = tower.numberOfLevels;
        int  maxLevel    = tower.GetNumberOfLevels();
        bool upgradeable = currLevel < maxLevel;

        if (!upgradeable)
        {
            Transform buttonUpgradeTower = towerMenu.transform.Find(Constants.ButtonUpgradeTower);
            buttonUpgradeTower.gameObject.SetActive(false);
        }

        // if this is a melee tower, show the "set rally point" button
        if (tower as MeleeTower != null)
        {
            Transform buttonSetRallyPoint = towerMenu.transform.Find(Constants.ButtonSetRallyPoint);
            buttonSetRallyPoint.gameObject.SetActive(true);
        }


        /////////////////////////////////////

        // gather the cost data

        int sellValue   = -1;
        int upgradeCost = -1;

        sellValue   = tower.GetCurrentSellValue();
        upgradeCost = tower.GetNextLevelCost();

        ShopMenu shopMenu = towerMenu.GetComponent <ShopMenu>();

        shopMenu.SetValueSell(sellValue);
        shopMenu.SetCostUpgrade(upgradeCost);

        /////////////////////////////////////

        // UI elements and other scene objects use different coordinate systems;
        // in order to position the menu where the lymph node is (on the screen)...
        // ...we have to do some conversions between World and Viewport
        RectTransform towerMenuRT          = towerMenu.GetComponent <RectTransform>();
        RectTransform canvasRT             = activeGameUIPanel.parent.GetComponent <RectTransform>();                                           // this assumes that this panel is the child of the top-level UI panel
        Vector2       viewportPosition     = Camera.main.WorldToViewportPoint(lymphNode.position);
        Vector2       uiOffset             = new Vector2((float)canvasRT.sizeDelta.x / 2f, (float)canvasRT.sizeDelta.y / 2f);                   // screen offset for the canvas
        Vector2       proportionalPosition = new Vector2(viewportPosition.x * canvasRT.sizeDelta.x, viewportPosition.y * canvasRT.sizeDelta.y); // position on the canvas

        // set the position and remove the screen offset
        towerMenuRT.localPosition = proportionalPosition - uiOffset;

        return(towerMenu);
    }
Example #10
0
 public void init(bool _belongToPlayer, int _value, ShopMenu _menu, ShopMenu _otherMenu, int _storeIdx)
 {
     menu            = _menu;
     otherMenu       = _otherMenu;
     value           = _value;
     valueField.text = value.ToString();
     belongToPlayer  = _belongToPlayer;
     storeIdx        = _storeIdx;
 }
Example #11
0
    public void SetupShop()
    {
        ShopMenu spmu = GameObject.Find("ShopMenu(Clone)").GetComponent <ShopMenu>();

        spmu.shop = this;
        names     = GameObject.Find("ShopItems");
        infoTxt   = GameObject.Find("InfoText").GetComponent <Text>();
        DrawInv();
    }
Example #12
0
        public static bool mailbox()
        {
            try
            {
                if (Game1.player.mailbox.Count == 0 && Game1.player.CurrentTool is Tool tool)
                {
                    if (Game1.player.toolBeingUpgraded.Value == null)
                    {
                        if (tool is Axe || tool is Pickaxe || tool is Hoe || tool is WateringCan)
                        {
                            Dictionary <ISalable, int[]> blacksmithUpgradeStock = Utility.getBlacksmithUpgradeStock(Game1.player);
                            int[] cost = blacksmithUpgradeStock
                                         .Where(s => s.Key.GetType() == tool.GetType())
                                         .Select(s => s.Value)
                                         .FirstOrDefault();
                            if (cost != null)
                            {
                                int       price    = cost[0];
                                int       barIndex = cost[2];
                                const int barCount = 5;
                                if (Game1.player.Money >= price)
                                {
                                    if (Game1.player.hasItemInInventory(barIndex, barCount))
                                    {
                                        ShopMenu.chargePlayer(Game1.player, 0, price);
                                        Game1.player.removeItemsFromInventory(barIndex, barCount);

                                        Game1.drawObjectDialogue(DataLoader.I18N.Get("Shipment.Clint.UpgradeLetter.ToolSent", new { Tool = tool.DisplayName }));

                                        tool.UpgradeLevel++;
                                        Game1.player.removeItemFromInventory(tool);
                                        Game1.player.toolBeingUpgraded.Value      = tool;
                                        Game1.player.daysLeftForToolUpgrade.Value = 2;
                                        Game1.playSound("parry");
                                    }
                                    else
                                    {
                                        Game1.drawObjectDialogue(DataLoader.I18N.Get("Shipment.Clint.UpgradeLetter.NoBars", new { Tool = tool.DisplayName }));
                                    }
                                }
                                else
                                {
                                    Game1.drawObjectDialogue(DataLoader.I18N.Get("Shipment.Clint.UpgradeLetter.NoMoney", new { Tool = tool.DisplayName }));
                                }
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MailServicesModEntry.ModMonitor.Log("Error trying to send the tool to upgrade.", LogLevel.Error);
                MailServicesModEntry.ModMonitor.Log($"The error message above:{e.Message}", LogLevel.Trace);
            }
            return(true);
        }
Example #13
0
        private static bool BeforeShopMenuReceiveLeftClick(ShopMenu __instance, int x, int y)
        {
            if (__instance.upperRightCloseButton.containsPoint(x, y))
            {
                ClickToMoveManager.GetOrCreate(Game1.currentLocation).ResetRotatingFurniture();
            }

            return(true);
        }
Example #14
0
 public static StoreHelper Read(ShopMenu m)
 {
     return(new StoreHelper
     {
         menu = m,
         stock = (Dictionary <Item, int[]>)invInfo.GetValue(m),
         forsale = (List <Item>)forSaleInfo.GetValue(m),
     });
 }
Example #15
0
        /// <summary>
        /// Opens the shop if conditions are met. If not, display the closed message
        /// </summary>
        public void DisplayShop(bool debug = false)
        {
            ModEntry.monitor.Log($"Attempting to open the shop \"{ShopName}\"", LogLevel.Trace);

            //if conditions aren't met, display closed message if there is one
            //skips condition checking if debug mode
            if (!debug && !APIs.Conditions.CheckConditions(When))
            {
                if (ClosedMessage != null)
                {
                    Game1.activeClickableMenu = new DialogueBox(ClosedMessage);
                }

                return;
            }

            int currency = 0;

            switch (StoreCurrency)
            {
            case "festivalScore":
                currency = 1;
                break;

            case "clubCoins":
                currency = 2;
                break;
            }

            var shopMenu = new ShopMenu(StockManager.ItemPriceAndStock, currency: currency);

            if (CategoriesToSellHere != null)
            {
                shopMenu.categoriesToSellHere = CategoriesToSellHere;
            }

            if (_portrait != null)
            {
                shopMenu.portraitPerson = new NPC();
                //only add a shop name the first time store is open each day so that items added from JA's side are only added once
                if (!_shopOpenedToday)
                {
                    shopMenu.portraitPerson.Name = "STF." + ShopName;
                }

                shopMenu.portraitPerson.Portrait = _portrait;
            }

            if (Quote != null)
            {
                shopMenu.potraitPersonDialogue = Game1.parseText(Quote, Game1.dialogueFont, 304);
            }

            Game1.activeClickableMenu = shopMenu;
            _shopOpenedToday          = true;
        }
Example #16
0
 /// <summary>Constructs an instance.</summary>
 /// <param name="menu">The native shop menu.</param>
 /// <param name="item">The item to buy.</param>
 public BuyAction(ShopMenu menu, ISalable item)
     : base(menu, item)
 {
     // Default
     if (CanPerformAction())
     {
         this.Amount = Math.Min(Mod.Config.DefaultShopAmount, GetMaxPurchasable());
     }
     Log.TraceIfD($"[{nameof(BuyAction)}] Instantiated for shop {menu} item {item}, Amount = {this.Amount}, GUID = {GUID}");
 }
Example #17
0
        /// <summary>Verifies the conditions to perform te action.</summary>
        public override bool CanPerformAction()
        {
            var heldItem      = this.Reflection.GetField <Item>(this.NativeShopMenu, "heldItem").GetValue();
            int currentMonies = ShopMenu.getPlayerCurrencyAmount(Game1.player, this.ShopCurrencyType);

            return(this.ClickedItem != null &&
                   (heldItem == null || (this.ClickedItem.canStackWith(heldItem) && heldItem.Stack < heldItem.maximumStackSize())) && // Holding the same item and not hold max stack
                   this.ClickedItem.canStackWith(this.ClickedItem) &&                                                                 // Item type is stackable
                   currentMonies >= this.ClickedItem.salePrice());                                                                    // Can afford
        }
Example #18
0
 internal static void Shop(StardewValley.Farmer who, string[] arguments, Vector2 tile)
 {
     try
     {
         if (!ModEntry.PatchData.Shops.Any(p => p.Name == arguments[0]))
         {
             Game1.activeClickableMenu = new ShopMenu(new List <Item>(), 0, null);
             ModEntry.Logger.Log("Unable to open shop, shop not found: " + arguments[0], StardewModdingAPI.LogLevel.Error);
         }
         else
         {
             Configs.ShopConfig shop  = ModEntry.PatchData.Shops.First(p => p.Name == arguments[0]);
             List <Item>        stock = new List <Item>();
             NPC portrait             = new NPC();
             portrait.Portrait = ModEntry.SHelper.Content.Load <Texture2D>(shop.Portrait);
             portrait.name     = shop.Owner;
             foreach (Configs.ShopItem item in shop.Items)
             {
                 if (!string.IsNullOrEmpty(item.Conditions) && !ModEntry.SHelper.Conditions().ValidateConditions(item.Conditions))
                 {
                     continue;
                 }
                 StardewValley.Object result;
                 if (item.Price != null)
                 {
                     result = new StardewValley.Object(item.Id, item.Stock, false, (int)item.Price);
                 }
                 else
                 {
                     result = new StardewValley.Object(item.Id, item.Stock, false, -1);
                 }
                 if (item.Stack > 1)
                 {
                     stock.Add(new StackableShopObject(result, item.Stack));
                 }
                 else
                 {
                     stock.Add(result);
                 }
             }
             if (stock.Count == 0)
             {
                 ModEntry.Logger.Log("No stock: " + arguments[0] + ", if this is intended this message can be ignored.", StardewModdingAPI.LogLevel.Warn);
             }
             ShopMenu menu = new ShopMenu(stock);
             menu.portraitPerson        = portrait;
             menu.potraitPersonDialogue = shop.Messages[_Random.Next(shop.Messages.Count)];
             Game1.activeClickableMenu  = menu;
         }
     }
     catch (Exception err)
     {
         ModEntry.Logger.Log("Unable to open shop due to unexpected error: ", StardewModdingAPI.LogLevel.Error, err);
     }
 }
Example #19
0
 public static void Draw_Postfix(ShopMenu __instance, SpriteBatch b)
 {
     try
     {
         ConvenientInventory.PostMenuDraw(__instance, b);
     }
     catch (Exception e)
     {
         ModEntry.Instance.Monitor.Log($"Failed in {nameof(Draw_Postfix)}:\n{e}", LogLevel.Error);
     }
 }
Example #20
0
        private void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e)
        {
            if (Game1.activeClickableMenu is ShopMenu)
            {
                ShopMenu shop = (ShopMenu)Game1.activeClickableMenu;
                Dictionary <Item, int[]> items = Helper.Reflection.GetField <Dictionary <Item, int[]> >(shop, "itemPriceAndStock").GetValue();
                List <Item> selling            = Helper.Reflection.GetField <List <Item> >(shop, "forSale").GetValue();
                int         currency           = Helper.Reflection.GetField <int>(shop, "currency").GetValue();
                bool        isCatalogue        = (currency == 0 && selling.Count > 0 && selling[0] is Furniture);
                string      shopkeeper         = "Robin";


                if (shop.portraitPerson != null || isCatalogue)
                {
                    Dictionary <Item, int> newItemsToSell = new Dictionary <Item, int>();

                    foreach (CustomFurniture f in furniture.Values)
                    {
                        if (!f.data.sellAtShop || (f.data.conditions != "none" && !meetsConditions(f.data.conditions)))
                        {
                            continue;
                        }

                        if (Game1.getCharacterFromName(f.data.shopkeeper) is NPC sk && !sk.isInvisible)
                        {
                            shopkeeper = f.data.shopkeeper;
                        }
                        else
                        {
                            shopkeeper = "Robin";
                        }

                        if (f.data.instantGift != "none")
                        {
                            Game1.player.addItemByMenuIfNecessary(f);
                            Game1.player.mailReceived.Remove(f.data.instantGift);
                            continue;
                        }

                        if ((shop.portraitPerson is NPC shopk && shopk.name == shopkeeper) || isCatalogue)
                        {
                            newItemsToSell.Add(f, isCatalogue ? 0 : f.price);
                        }
                    }

                    foreach (Item item in newItemsToSell.Keys)
                    {
                        if (!items.ContainsKey(item))
                        {
                            items.Add(item, new int[] { newItemsToSell[item], int.MaxValue });
                            selling.Add(item);
                        }
                    }
                }
Example #21
0
    void Awake()
    {
        m_loginMenu = GameObject.FindObjectOfType<LoginMenu>();
        m_mainMenu = GameObject.FindObjectOfType<MainMenu>();
        m_optionMenu = GameObject.FindObjectOfType<OptionMenu>();
        m_artworkMenu = GameObject.FindObjectOfType<ArtworksMenu>();
        m_creditsMenu = GameObject.FindObjectOfType<CreditsMenu>();
        m_shopMenu = GameObject.FindObjectOfType<ShopMenu>();

        m_singleton = this;
    }
Example #22
0
        public static void FixShopMenu(ShopMenu menu)
        {
            // Remove the invalid -1 hat from the inventory.
            RemoveHatFromMenu(menu, -1);

            // If the achievement has not been attained, remove the actual hat.
            if (Which != -1 && !AchievementEditor.HasAchievement())
            {
                RemoveHatFromMenu(menu, Which);
            }
        }
Example #23
0
 private void Awake()
 {
     if (_instance != null && _instance != this)
     {
         Destroy(this.gameObject);
     }
     else
     {
         _instance = this;
     }
 }
Example #24
0
 /// <summary>Raised after a game menu is opened, closed, or replaced.</summary>
 /// <param name="sender">The event sender.</param>
 /// <param name="e">The event arguments.</param>
 private void onMenuChanged(object sender, MenuChangedEventArgs e)
 {
     if (e.NewMenu is ShopMenu shopMenu)
     {
         Log.trace("Found shop menu!");
         initShop(shopMenu);
     }
     else
     {
         shop = null;
     }
 }
Example #25
0
        public void BuyHoveredItem(ShopMenu menu, int amount, Point clickLocation)
        {
            Item hoverItem = this.Helper.Reflection.GetField <Item>(menu, "hoveredItem").GetValue();

            if (hoverItem == null)
            {
                return;
            }

            var heldItem           = this.Helper.Reflection.GetField <Item>(menu, "heldItem").GetValue();
            var priceAndStockField = this.Helper.Reflection.GetField <Dictionary <Item, int[]> >(menu, "itemPriceAndStock");
            var priceAndStockMap   = priceAndStockField.GetValue();
            //Debug.Assert(priceAndStockMap.ContainsKey(hoverItem));

            // Calculate the number to purchase
            int numInStock       = priceAndStockMap[hoverItem][1];
            int itemPrice        = priceAndStockMap[hoverItem][0];
            int ShopCurrencyType = this.Helper.Reflection.GetField <int>(menu, "currency").GetValue();
            int currentMonies    = ShopMenu.getPlayerCurrencyAmount(Game1.player, ShopCurrencyType);

            amount = Math.Min(Math.Min(amount, currentMonies / itemPrice), Math.Min(numInStock, hoverItem.maximumStackSize()));

            // If we couldn't grab all that we wanted then only subtract the amount we were able to grab
            int numHeld  = heldItem?.Stack ?? 0;
            int overflow = Math.Max((numHeld + amount) - hoverItem.maximumStackSize(), 0);

            amount -= overflow;

            this.Monitor.Log($"Attempting to purchase {amount} of {hoverItem.Name} for {itemPrice * amount}");

            if (amount <= 0)
            {
                return;
            }

            // Try to purchase the item - method returns true if it should be removed from the shop since there's no more.
            var purchaseMethodInfo = this.Helper.Reflection.GetMethod(menu, "tryToPurchaseItem");
            int index = this.GetClickedItemIndex(this.Helper.Reflection, menu, clickLocation);

            if (purchaseMethodInfo.Invoke <bool>(hoverItem, heldItem, amount, clickLocation.X, clickLocation.Y, index))
            {
                this.Monitor.Log($"Purchase of {hoverItem.Name} successful");

                // remove the purchased item from the stock etc.
                priceAndStockMap.Remove(hoverItem);
                priceAndStockField.SetValue(priceAndStockMap);

                var itemsForSaleField = this.Helper.Reflection.GetField <List <Item> >(menu, "forSale");
                var itemsForSale      = itemsForSaleField.GetValue();
                itemsForSale.Remove(hoverItem);
                itemsForSaleField.SetValue(itemsForSale);
            }
        }
Example #26
0
 private void onMenuChanged(object sender, EventArgsClickableMenuChanged args)
 {
     if (args.NewMenu != null && args.NewMenu is ShopMenu shopMenu)
     {
         Log.trace("Found shop menu!");
         initShop(shopMenu);
     }
     else
     {
         shop = null;
     }
 }
Example #27
0
 private static void AddItems <T>(Shop shop, ShopMenu shopMenu, List <T> items)
 {
     foreach (var item in items)
     {
         if (ItemDefinitions.GetExtInfo(item, out ExtItemInfo extInfo) && extInfo.SellingCondition.IsFulfilled(shop))
         {
             Item saleItem = CreateItemInstance(item);
             shopMenu.forSale.Add(saleItem);
             shopMenu.itemPriceAndStock.Add(saleItem, new int[] { extInfo.Price, 1 });
         }
     }
 }
Example #28
0
        internal static void Postfix(ShopMenu __instance, SpriteBatch b)
        {
            if (__instance.portraitPerson == null || !(Game1.viewport.Width > 800 && Game1.options.showMerchantPortraits))
            {
                return;
            }

            ScaledTexture2D texture = TextureLoader.getPortrait(__instance.portraitPerson.Name);

            __instance.portraitPerson.Portrait = texture;
            return;
        }
Example #29
0
 void Awake()
 {
     if (shopMenu != null)
     {
         //Destroy(shopMenu);
     }
     else
     {
         shopMenu = this;
     }
     DontDestroyOnLoad(this);
 }
Example #30
0
        public static void DoShop(string key, ShopMenu shop)
        {
            if (!Mod.State.TodaysShopEntries.ContainsKey(key))
            {
                return;
            }

            foreach (var entry in Mod.State.TodaysShopEntries[key])
            {
                entry.AddToShop(shop);
            }
        }
Example #31
0
        public void AddToShop(ShopMenu shop)
        {
            // Check to see if this shopEntry has already been added to this shop--if so, don't add
            if (shop.itemPriceAndStock.ContainsKey(this.Item))
            {
                return;
            }

            int qty = this.Quantity;

            if (this.Item is StardewValley.Object {
                IsRecipe : true
            })
Example #32
0
        private void btnShop_Click(object sender, EventArgs e)
        {
            if (_loggedInEmployee.AccessID != 3)
            {
                MessageBox.Show("You are not authorized.");
            }

            else
            {
                var f = new ShopMenu(_loggedInEmployee);
                f.ShowDialog();
            }
        }