Inheritance: MonoBehaviour
	public void AddShopItem(int shopId , int idx , ShopItem  shopItem){
		if(shopInfosDic[shopId].ContainsKey(idx)){
			shopInfosDic[shopId][idx] = shopItem;
			return;
		}
		shopInfosDic[shopId].Add(idx , shopItem);
	}
    public void SetShopitem(ShopItem shopItem)
    {
        _shopItem = shopItem;
        if (_shopItem.Item.ChromieType != eChromieType.None)
        {
            ChromieDefenition chromieDefenition = ChromezData.Instance.GetChromie(_shopItem.Item.ChromieType);
            if (chromieDefenition != null)
            {
                _itemImage.sprite = chromieDefenition.ChromieSprite;
                _titleLabel.text = chromieDefenition.ChromieName;

                _priceLabel.text = shopItem.Price.Amount.ToString();

                if (shopItem.IsUnique && InventoryManager.Instance.HasItem(shopItem.Item.ID))
                {
                    _purchaseButton.SetActive(false);
                }
                else
                {
                    _purchaseButton.SetActive(true);
                }
                return;
            }
        }
    }
Example #3
0
	public ShopItem(ShopItem item)
	{
		FieldInfo[] fields_of_class = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
		foreach(FieldInfo fi in fields_of_class)
		{
			fi.SetValue(this,fi.GetValue(item));
		}
	}
    private void SelectShopItem(ShopItem shopItem)
    {
        _selectedShopitem = shopItem;

        if (_itemDisplayController != null)
        {
            _itemDisplayController.SetShopitem(_selectedShopitem);
        }
    }
 private void OnCurrencyShopItemCellPurchaceHandler(ShopItem shopitem)
 {
     ShopManager.Instance.Purchase(shopitem, (sucsess) =>
     {
         if (sucsess && _closeOnPurchase)
         {
             ClosePopup();
         }
     });
 }
	public void BindingData(ShopItem data){
		if(data == null){
			this.shopItem = data;
			RegistAction();
			return;
		}
		UnregistAction();
		this.shopItem = data;
		RegistAction();
	}
	public void BindingData(ShopItem shopItem){
		if(this.shopItem == null){
			this.shopItem = shopItem;
			RegistAction();
			return;
		}
		UnregistAction();
		this.shopItem = shopItem;
		RegistAction();
	}
 public void SetShopitem(ShopItem shopItem)
 {
     _shopItem = shopItem;
     if (_shopItem.Item.ChromieType != eChromieType.None)
     {
         ChromieDefenition chromieDefenition = ChromezData.Instance.GetChromie(_shopItem.Item.ChromieType);
         if (chromieDefenition != null)
         {
             _itemImage.sprite = chromieDefenition.ChromieSprite;
         }
     }
 }
    public void FeatureRandomItem()
    {
        ShopItem randomItem = null;
        while (randomItem == null || randomItem == StaticFeaturedItem)
        {
            randomItem = _items[Random.Range(0, _items.Length - 1)];
        }

        // Both sub-contexts are assigned here,
        // but only dynamic one will trigger the UI update.
        StaticFeaturedItem = randomItem;
        DynamicFeaturedItem = randomItem;
    }
Example #10
0
 public void AddItemToShop()
 {
     Item item = new Item("ID0001", "Cestitka 1");
     Shop shop = new Shop("trgovina 1");
     Price price = new Price(4, 3.2) {ItemId = item.UniqueId, ShopId = shop.Id};
     ShopItem shopItem = new ShopItem {ItemId = item.UniqueId, ShopId = shop.Id, PriceId = price.Id};
     Assert.IsNotNull(shopItem, "Items not added to shop!");
     shopItem.SetNumberOfItems(3);
     Assert.AreEqual(3, shopItem.NumberOfItems, "ShopItem missmatch!");
     Overview overview = new Overview();
     overview.AddShopItem(shopItem);
     Overview temp = overview;
 }
    public void SetShopitem(ShopItem shopItem)
    {
        _shopItem = shopItem;

        if (_ItemTitleLabel != null)
        {
            _ItemTitleLabel.text = shopItem.Name;
        }

        if (_purchaseButtonLabel != null)
        {
            _purchaseButtonLabel.text = shopItem.Price.Amount + "$";
        }
    }
Example #12
0
    public ShopContext()
    {
        _items = new []
        {
            new ShopItem { Name = "Boots of Speed", Price = 450 },
            new ShopItem { Name = "Power Treads", Price = 1400 },
            new ShopItem { Name = "Phase Boots", Price = 1350 },
            new ShopItem { Name = "Tranquil Boots", Price = 975 },
            new ShopItem { Name = "Boots of Travel", Price = 2450 },
            new ShopItem { Name = "Arcane Boots", Price = 1450 },
        };
        
		StaticFeaturedItem = _items[0];
		DynamicFeaturedItem = _items[0];
	}
Example #13
0
    public void TransitToShopScene(ShopItem[] itemPrefabArray)
    {
        var ml = Player.MyCharList;

        foreach( var obj in ml )
        {
            Debug.Log ( obj.name );
        }
        Action endAct = () => {
            //ShopManager.Activate(Player.MyCharList, itemPrefabArray);
            gameObject.SetActive(false);
        };
        Action act = () =>{
            ShopManager.Activate(Player.MyCharList, itemPrefabArray);
            StartCoroutine("FadeIn", endAct );
        };
        base.TransitWithFadeOut(act);

        //		ShopManager.Activate(Player.MyCharList, itemPrefabArray);
        //		gameObject.SetActive(false);
    }
Example #14
0
 public void DeleteShopItem()
 {
     Guid itemId = Guid.NewGuid();
     Guid shopId = Guid.NewGuid();
     Guid priceId = Guid.NewGuid();
     const int numberOfItems = 666;
     ShopItem newShopItem = new ShopItem
         {
             DateTime = new DateTime(DateTime.Now.Ticks),
             ItemId = itemId,
             ShopId = shopId,
             PriceId = priceId,
             NumberOfItems = numberOfItems,
         };
     Assert.IsTrue(dataBase.InsertShopItem(newShopItem));
     DataSet shopItems = dataBase.GetShopItems();
     int count = shopItems.Tables[Misc.DataTableNameOfShopItems].Rows.Count;
     dataBase.DeleteShopItem(newShopItem.Id);
     shopItems = dataBase.GetShopItems();
     Assert.AreEqual(count - 1, shopItems.Tables[Misc.DataTableNameOfShopItems].Rows.Count);
 }
Example #15
0
    void Update() {
        if (Util.hit != null && Util.hit.GetComponent<ShopItem>() != null) {
            if (currItem == null) {
                currItem = Util.hit.GetComponent<ShopItem>();
				itemDescriptor.showDescription(currItem.getItem());
            } else if (currItem != Util.hit.GetComponent<ShopItem>()) {
                currItem = Util.hit.GetComponent<ShopItem>();
                itemDescriptor.showDescription(currItem.getItem());
            } else if (!itemDescriptor.isOnScreen()) {
                currItem = Util.hit.GetComponent<ShopItem>();
				itemDescriptor.showDescription(currItem.getItem());
            }
        } else if (currItem != null) {
            itemDescriptor.hideDescription();
            currItem = null;
        }
        if (currItem != null && Input.GetMouseButtonDown(1)) {
            currItem.buyItem();
            itemDescriptor.hideDescription();
            currItem = null;
        }
    }
Example #16
0
    private static void Parse(JSONNode json)
    {
        CoinItems = new List<ShopItem>();

        var coins = json["coins"];
        
        for (int i = 0; i < coins.AsArray.Count; i++)
        {
            var item = new ShopItem();

            var pos = new ShopPosition
            {
                Index = coins[i]["index"],
                Count = coins[i]["count"].AsInt,
                ShopItemType = ShopItemType.Coins
            };

            item.Positions = new List<ShopPosition> {pos};
            item.Price = coins[i]["price"].AsFloat;

            CoinItems.Add(item);
        }
    }
Example #17
0
	void ShopSettings(ConfigManager config)
	{
		
		EditorGUILayout.LabelField("Game In Apps", EditorStyles.miniBoldLabel);
		
		if (GUILayout.Button(!config.showInApps ? "Open InApps" : "Close InApps")) config.showInApps = !config.showInApps;
		
		if (!config.showInApps)
		{
			EditorGUILayout.LabelField("Mostra InApps", EditorStyles.whiteMiniLabel);
		}
		else
		{
			ConfigManagerShop.DrawInApps(config);
			
			EditorGUILayout.Space();
			
			if(GUILayout.Button("New InApp"))
			{
				ShopInApp inapp = new ShopInApp();
				
				config.shopInApps.Add(inapp,ref config.shopInApps);
			}
		}
			
		EditorGUILayout.LabelField("Game Items", EditorStyles.miniBoldLabel);
		
		if (GUILayout.Button(!config.showShopItems ? "Open Shop Items" : "Close Shop Items")) config.showShopItems = !config.showShopItems;
		
		if (!config.showShopItems)
		{
			EditorGUILayout.LabelField("Mostra Itens comprados com coins", EditorStyles.whiteMiniLabel);
		}
		else
		{
			ConfigManagerShop.DrawShopItems(config);
			
			EditorGUILayout.Space();
			
			if(GUILayout.Button("New Shop Item"))
			{
				ShopItem shopItem = new ShopItem();
				
				config.shopItems.Add(shopItem,ref config.shopItems);
			}
		}
		
		EditorGUILayout.LabelField("Game Features", EditorStyles.miniBoldLabel);
		
		if (GUILayout.Button(!config.showShopFeatures ? "Open Shop Features" : "Close Shop Features")) config.showShopFeatures = !config.showShopFeatures;
		
		if (!config.showShopFeatures)
		{
			EditorGUILayout.LabelField("Mostra Features", EditorStyles.whiteMiniLabel);
		}
		else
		{
			ConfigManagerShop.DrawFeatures(config);
		}
		
		if(GUILayout.Button("Download Shop Info From Server"))
		{
			Debug.Log("oi");
			config.GetComponent<ShopManager>().RefreshShop(false);
		}
		
		if(GUILayout.Button("Delete All"))
		{
			config.shopInApps = new ShopInApp[]{};
			config.shopFeatures = new ShopFeatures();
			config.shopItems = new ShopItem[]{};
		}
	}
Example #18
0
	public void OfferCoinPackAndBuyItem(ShopDelegate callback, ShopItem item)
	{
		// nao tem coins
		int difference = item.coinPrice - Flow.header.coins;
		ShopInApp coinPackToOffer = new ShopInApp();
		ShopInApp biggestPack = new ShopInApp();
		foreach(ShopInApp pack in coinPacks)
		{
			Debug.Log(pack.coinsCount);
			if(pack.coinsCount >= difference)
			{
				Debug.Log("coinpack selecionado: "+ pack.appleBundle);
				coinPackToOffer = pack;
				break;
			}
			
			int mostCoins = 0;
			if(mostCoins < pack.coinsCount) 
			{
				mostCoins = pack.coinsCount;
				biggestPack = pack;
			}
		}
		
		if(coinPackToOffer.name == null)
		{
			coinPackToOffer = biggestPack;
		}
		
#if UNITY_ANDROID && !UNITY_EDITOR
		string packBundle = coinPackToOffer.androidBundle;
#elif UNITY_IPHONE && !UNITY_EDITOR
		string packBundle = coinPackToOffer.appleBundle;
		Debug.Log("caiu no iOS e o packBundle: "+ coinPackToOffer.appleBundle);
#else
		string packBundle;
		Flow.game_native.showMessage("Not Enough Coins", "You don't have enough coins to buy this item");
		
		return;
#endif
		//List<string> tList = new List<string>();
		
		Flow.game_native.startLoading();
		UIManager.instance.blockInput = true;
		
		IAP.purchaseConsumableProduct(packBundle, purchased =>
		{
			Flow.game_native.stopLoading();
			UIManager.instance.blockInput = false;
			if(purchased)
			{
				Flow.header.coins += coinPackToOffer.coinsCount;
				
				if(Flow.header.coins >= item.coinPrice) 
				{
					Flow.header.coins -= item.coinPrice;
				
					foreach(ShopItem iw in item.itemsWithin)
					{
						//comprou o pack e agora tem coins suficientes pra comprar o item
						
						if(Save.HasKey(PlayerPrefsKeys.ITEM+iw.id) && iw.type == ShopItemType.Consumable)
						{
							int userStock = Save.GetInt(PlayerPrefsKeys.ITEM+iw.id);
							userStock += iw.count;
							Save.Set (PlayerPrefsKeys.ITEM+iw.id,userStock);
						}
						else if(!Save.HasKey(PlayerPrefsKeys.ITEM+iw.id) && iw.type == ShopItemType.NonConsumable)
						{
							Save.Set(PlayerPrefsKeys.ITEM+iw.id,1);
						}
						else
						{
							Save.Set(PlayerPrefsKeys.ITEM+iw.id, iw.count);
						}
					}
					
					Save.SaveAll();
					
					callback(ShopResultStatus.Success, item.id);
				
					if(Save.HasKey(PlayerPrefsKeys.TOKEN))
					{
						// se a compra deu sucesso e o cara esta logado, registrar no server
						GameJsonAuthConnection conn = new GameJsonAuthConnection(Flow.URL_BASE + "login/shop/buy.php", BuyingConfirmation);
						WWWForm form = new WWWForm();
						
						for(int i = 0 ; i < item.itemsWithin.Length ; i++)
						{
							form.AddField("items["+i+"][id]", item.itemsWithin[i].id);
							form.AddField("items["+i+"][count]", Save.GetInt(PlayerPrefsKeys.ITEM+item.itemsWithin[i].id));
							form.AddField("coins", Flow.header.coins);
						}
						
						conn.connect(form);
					}
				}
				else
				{
					// comprou o pack e mesmo assim nao tem coins suficientes pra comprar o item
					Flow.game_native.showMessage("Not Enough Coins", "You'll need to buy another pack to buy this item!");
					callback(ShopResultStatus.Failed, item.id);
				}
				//Save.Set(PlayerPrefsKeys.COINS.ToString(),Flow.header.coins);
				
				
			}
			else
			{
				// nao tem coins para comprar o item
				Flow.game_native.showMessage("Not Enough Coins", "You don't have enough coins to buy this item");
				callback(ShopResultStatus.Failed, item.id);
			}		
		});
		
	}
Example #19
0
 public Result(BxDictionary serialized) : base(serialized)
 {
     shopItem = new ShopItem((BxDictionary)serialized["shopItem"]);
     id       = serialized["id"].ToGuid();
 }
Example #20
0
        private bool Shipyard_Buy(ShopItem item)
        {
            var newShip = (ShipModel) item.ItemObject;

            if (Player.Credits < item.Price)
            {
                EventLog.Print("Planet_NoMoneyToBuy");
                HighlightArea();
                return false;
            }

            EventLog.HighlightArea();
            var result = false;
            var toBuy = EventLog.Get_YesNo("Shipyard_Confirmation", Player.Ship.ModelName, newShip.ModelName, true);
            if (toBuy)
            {
                var oldShipName = Player.Ship.ModelName;
                Player.Ship = newShip;

                for (var i = 0; i < Enums.All_Merchandise.Count; i++)
                {
                    var merch = (Merchandise) i;
                    if (IsLegal(merch))
                    {
                        Player.Credits += (GoodsPrices[merch] + CurrentSystem.PriceChanges[i]) * Player.CurrentCargo[merch];
                        Player.CurrentCargo[merch] = 0;
                    }
                }

                Player.CurrentCargo.Clear();
                Player.CurrentHP = Player.MaxHP;
                Player.CurrentMissiles = Math.Min(Player.CurrentMissiles, Player.MaxMissiles);
                Player.Credits -= item.Price;
                PlayerStats.Draw_PlayerStats();

                EventLog.Print("Shipyard_Exchanged", oldShipName, newShip.ModelName);
                result = true;
            }
            HighlightArea();
            return result;
        }
Example #21
0
	public ShopItem GetShopItem(string id)
	{
		ShopItem item = new ShopItem();
		
		Debug.Log("nome: "+id);
		Debug.Log(itemList.Length);
		
		for (int i = 0 ; i < itemList.Length ; i++)
		{
			Debug.Log(itemList[i].id);
			if(itemList[i].id == id)
			{
				item = new ShopItem(itemList[i]);
				
				Debug.Log(item.type);
				break;
			}
		}
		return item;
	}
Example #22
0
 public void DirtGroundOnClick() => SelectedItem = dirtGround;
Example #23
0
File: Buy7.cs Project: dahlia/lib9c
 public SellerResult(Bencodex.Types.Dictionary serialized) : base(serialized)
 {
     shopItem = new ShopItem((Bencodex.Types.Dictionary)serialized["shopItem"]);
     id       = serialized["id"].ToGuid();
     gold     = serialized["gold"].ToFungibleAssetValue();
 }
Example #24
0
 public void ClearItemSelectionAndDestroyObject()
 {
     SelectedItem = null;
     PlayerSpawner.instance.DestroyNotPlacedItem();
     PlayerSpawnGroundController.instance.DestroyNotPlacedGround();
 }
Example #25
0
 private void ResetBorder(ShopItem item) => item.itemBorderImage.sprite = defaultBorder;
Example #26
0
 public void LaserShooterOnClick() => SelectedItem = laserShooter;
Example #27
0
 public void BombShooterOnClick() => SelectedItem = bombShooter;
Example #28
0
 public void BulletShooterOnClick() => SelectedItem = bulletShooter;
Example #29
0
 public void SoldierFactoryOnClick() => SelectedItem = soldierFactory;
Example #30
0
 public void OrcFactoryOnClick() => SelectedItem = orcFactory;
Example #31
0
 public void KnightFactoryOnClick() => SelectedItem = knightFactory;
Example #32
0
        void pnl_HoverEnter(Base sender, EventArgs arguments)
        {
            if (InputHandler.MouseFocus != null)
            {
                return;
            }

            mMouseOver = true;
            mCanDrag   = true;
            if (Globals.InputManager.MouseButtonDown(GameInput.MouseButtons.Left))
            {
                mCanDrag = false;

                return;
            }

            if (mDescWindow != null)
            {
                mDescWindow.Dispose();
                mDescWindow = null;
            }

            if (Globals.GameShop == null)
            {
                if (Globals.Me.Inventory[mMySlot]?.Base != null)
                {
                    mDescWindow = new ItemDescWindow(
                        Globals.Me.Inventory[mMySlot].Base, Globals.Me.Inventory[mMySlot].Quantity, mInventoryWindow.X,
                        mInventoryWindow.Y, Globals.Me.Inventory[mMySlot].StatBuffs
                        );
                }
            }
            else
            {
                var      invItem  = Globals.Me.Inventory[mMySlot];
                ShopItem shopItem = null;
                for (var i = 0; i < Globals.GameShop.BuyingItems.Count; i++)
                {
                    var tmpShop = Globals.GameShop.BuyingItems[i];

                    if (invItem.ItemId == tmpShop.ItemId)
                    {
                        shopItem = tmpShop;

                        break;
                    }
                }

                if (Globals.GameShop.BuyingWhitelist && shopItem != null)
                {
                    var hoveredItem = ItemBase.Get(shopItem.CostItemId);
                    if (hoveredItem != null && Globals.Me.Inventory[mMySlot]?.Base != null)
                    {
                        mDescWindow = new ItemDescWindow(
                            Globals.Me.Inventory[mMySlot].Base, Globals.Me.Inventory[mMySlot].Quantity,
                            mInventoryWindow.X, mInventoryWindow.Y, Globals.Me.Inventory[mMySlot].StatBuffs, "",
                            Strings.Shop.sellsfor.ToString(shopItem.CostItemQuantity, hoveredItem.Name)
                            );
                    }
                }
                else if (shopItem == null)
                {
                    var hoveredItem = ItemBase.Get(invItem.ItemId);
                    var costItem    = Globals.GameShop.DefaultCurrency;
                    if (hoveredItem != null && costItem != null && Globals.Me.Inventory[mMySlot]?.Base != null)
                    {
                        mDescWindow = new ItemDescWindow(
                            Globals.Me.Inventory[mMySlot].Base, Globals.Me.Inventory[mMySlot].Quantity,
                            mInventoryWindow.X, mInventoryWindow.Y, Globals.Me.Inventory[mMySlot].StatBuffs, "",
                            Strings.Shop.sellsfor.ToString(hoveredItem.Price, costItem.Name)
                            );
                    }
                }
                else
                {
                    if (invItem?.Base != null)
                    {
                        mDescWindow = new ItemDescWindow(
                            invItem.Base, invItem.Quantity, mInventoryWindow.X, mInventoryWindow.Y, invItem.StatBuffs,
                            "", Strings.Shop.wontbuy
                            );
                    }
                }
            }
        }
 private void Awake()
 {
     entityController = FindObjectOfType <EntityController>();
     shopItem         = GetComponentInChildren <ShopItem>();
 }
Example #34
0
        private static async Task OnReactionAdded(Cacheable <IUserMessage, ulong> incomingMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            try
            {
                // Don't react to your own reacts!
                if (reaction.UserId == Program.DiscordClient.CurrentUser.Id)
                {
                    return;
                }

                // Only handle reacts to shop embed
                if (!activeShops.ContainsKey(incomingMessage.Id))
                {
                    return;
                }

                // Only handle reacts from the original user, remove the reaction
                if (activeShops[incomingMessage.Id] != reaction.UserId)
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    return;
                }

                // Only handle relevant reacts
                if (!shopEmotes.Contains(reaction.Emote))
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    return;
                }

                if (channel is SocketGuildChannel guildChannel)
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    // Try to get the purchasing item
                    ShopItem itemToBuy = shopItems.FirstOrDefault(x => x.ReactionEmote.GetString() == reaction.Emote.GetString());

                    User user = await UserService.GetUser(guildChannel.Guild.Id, reaction.UserId);

                    if (user.TotalKupoNutsCurrent >= itemToBuy.Cost)
                    {
                        // Take payment
                        user.UpdateTotalKupoNuts(-itemToBuy.Cost);

                        // Add to inventory
                        user.UpdateInventory(itemToBuy.Name, 1);

                        // Convert to success embed
                        await message.ModifyAsync(x => x.Embed = GetSuccessEmbed());

                        await Task.Delay(5000);

                        // Delete shop message
                        await message.DeleteAsync();

                        // Delete calling command
                        if (message.ReferencedMessage != null)
                        {
                            await message.ReferencedMessage.DeleteAsync();
                        }
                    }
                    else
                    {
                        SocketGuildUser failUser = guildChannel.GetUser(reaction.UserId);

                        // Convert message to failure embed
                        Embed embed = GetFailureEmbed(failUser.GetName(), "a " + itemToBuy.Name);
                        await message.ModifyAsync(x => x.Embed = embed);

                        await Task.Delay(5000);

                        await message.DeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
Example #35
0
 public void GrassGroundOnClick() => SelectedItem = grassGround;
Example #36
0
File: Buy7.cs Project: dahlia/lib9c
 public BuyerResult(Bencodex.Types.Dictionary serialized) : base(serialized)
 {
     shopItem = new ShopItem((Bencodex.Types.Dictionary)serialized["shopItem"]);
     id       = serialized["id"].ToGuid();
 }
Example #37
0
 public void Initialize(ShopUI shopUI, ShopItem entryData)
 {
     this.shopUI    = shopUI;
     this.entryData = entryData;
     UpdateEntry();
 }
 protected void LinkButtonAddItemToShopClick(object sender, EventArgs e)
 {
     Log.Debug("Add Item To Shop");
     DataBase dataBase = new DataBase();
     string selectedItem = dropDownListManageShopItemsBodyInputItems.SelectedValue;
     Item item = dataBase.GetItem(new Guid(selectedItem));
     if (item == null)
     {
         return;
     }
     string selectedShop = dropDownListManageShopItemsBodyInputShops.SelectedValue;
     Shop shop = dataBase.GetShop(selectedShop);
     if (shop == null)
     {
         return;
     }
     string gross = textBoxManageShopItemsBodyInputPriceGross.Text.Trim();
     string net = textBoxManageShopItemsBodyInputPriceNet.Text.Trim();
     if (gross.Length < 1 || net.Length < 1)
     {
         Log.WarnFormat("Price not in correct format! Gross='{0}', Net='{1}'", gross, net);
         return;
     }
     Double priceGross = Double.Parse(gross);
     Double priceNet = Double.Parse(net);
     int numberOfItems = Misc.String2Number(textBoxManageShopItemsBodyInputNumberOfItems.Text.Trim());
     Price price = new Price(priceGross, priceNet) {ItemId = item.UniqueId, ShopId = shop.Id};
     if (!dataBase.InsertPrice(price))
     {
         return;
     }
     ShopItem shopItem = new ShopItem
         {
             ItemId = item.UniqueId,
             ShopId = shop.Id,
             PriceId = price.Id,
             DateTime = new DateTime(DateTime.Now.Ticks),
         }.SetNumberOfItems(numberOfItems);
     dataBase.InsertShopItem(shopItem);
     Populate();
 }
Example #39
0
 public void AddShopItem(ShopItem shopItem)
 {
     _shopItemsContext.ShopItems.Add(shopItem);
     _shopItemsContext.SaveChanges();
 }
Example #40
0
 public void SetShopItemToUse(ShopItem shopItem)
 {
     shopItemToUse = shopItem;
     PlayerPrefs.SetString(shopItemToUsePlayerPrefString, shopItem.name);
 }
Example #41
0
	public void BuyItem(ShopDelegate callback, ShopItem item)
	{
		Debug.Log(item.id);
		foreach(ShopItem itemWithin in item.itemsWithin)
		{
			if(Save.HasKey(PlayerPrefsKeys.ITEM+itemWithin.id) && itemWithin.type == ShopItemType.NonConsumable)
			{
				// ja tem o item
				Flow.game_native.showMessage("Already has item","You already have this item.");
				callback(ShopResultStatus.Failed, item.id);
				return;
			}
			//else if(itemWithin.forFree
		}
			
		//Flow.game_native.startLoading();
		
		if(item.coinPrice > Flow.header.coins)
		{
			// nao tem coins
			OfferCoinPackAndBuyItem(callback, item);
		}
		else
		{
			Debug.Log("tem coins, soma eh: "+item.coinPrice);
			// tem coins
			Flow.header.coins -= item.coinPrice;
			
			foreach(ShopItem iw in item.itemsWithin)
			{
				Debug.Log(iw.id);
				Debug.Log(Save.HasKey(PlayerPrefsKeys.ITEM+iw.id));
				Debug.Log(iw.type.ToString());
				
				if(Save.HasKey(PlayerPrefsKeys.ITEM+iw.id) && iw.type == ShopItemType.Consumable)
				{
					int userStock = Save.GetInt(PlayerPrefsKeys.ITEM+iw.id);
					userStock += iw.count;
					Save.Set(PlayerPrefsKeys.ITEM+iw.id,userStock);
					Debug.Log("tem item, eh consumivel");
				}
				else if(!Save.HasKey(PlayerPrefsKeys.ITEM+iw.id) && iw.type == ShopItemType.NonConsumable)
				{
					Save.Set(PlayerPrefsKeys.ITEM+iw.id,1);
					Debug.Log("nao tem item, eh nao consumivel");
				}
				else
				{
					Save.Set(PlayerPrefsKeys.ITEM+iw.id, iw.count);
					Debug.Log("nao tem item, eh consumivel");
				}
			}
			
			if(item.type == ShopItemType.NonConsumable) Save.Set(PlayerPrefsKeys.ITEMSPACK+item.id,true);
			//Save.Set(PlayerPrefsKeys.COINS,Flow.header.coins);
			Save.SaveAll();
			
			callback(ShopResultStatus.Success, item.id);
			
			if(Save.HasKey(PlayerPrefsKeys.TOKEN))
			{
				// se a compra deu sucesso e o cara esta logado, registrar no server
				GameJsonAuthConnection conn = new GameJsonAuthConnection(Flow.URL_BASE + "login/shop/buy.php", BuyingConfirmation);
				WWWForm form = new WWWForm();
				
				for(int i = 0 ; i < item.itemsWithin.Length ; i++)
				{
					form.AddField("items["+i+"][id]", item.itemsWithin[i].id);
					form.AddField("items["+i+"][count]", Save.GetInt(PlayerPrefsKeys.ITEM+item.itemsWithin[i].id));
					form.AddField("coins", Flow.header.coins);
				}
				
				conn.connect(form);
			}
		}
		
	}
Example #42
0
        public bool CanPurchase(ShopItem i)
        {
            int cost = i.cost;

            return(CanPurchase(cost));
        }
Example #43
0
	public void OnRefreshShop(string error, IJSonObject data, object state)
	{
		bool refreshPrime = (bool) state;
		
		if(error != null) Debug.Log(error);
		else
		{
			//Debug.Log(data);
			
			IJSonObject inapps = data["inapps"];
			IJSonObject items = data["items"];
			IJSonObject features = data["features"];
			
			foreach(IJSonObject inapp in inapps.ArrayItems)
			{
				ShopInApp tempInApp = new ShopInApp();
				
				tempInApp.androidBundle = inapp["android"].StringValue;
				tempInApp.appleBundle = inapp["apple"].StringValue;
				tempInApp.dolarPrice = inapp["price"].ToFloat();
				tempInApp.name = inapp["name"].StringValue;
				tempInApp.id = inapp["id"].Int32Value;
				tempInApp.description = inapp["description"].StringValue;
				tempInApp.isPackOfCoins = inapp["coins"].Int32Value > 0;
				tempInApp.type = inapp["type"].StringValue == "Consumable"? ShopInAppType.Consumable : ShopInAppType.NonConsumable;
				tempInApp.goodCount = inapp["goodCount"].Int32Value;
				tempInApp.coinsCount = inapp["coins"].Int32Value;
				
				//Debug.Log(tempInApp.name);
				
				bool foundInApp = false;
				
				for(int i = 0 ; i < Flow.config.GetComponent<ConfigManager>().shopInApps.Length ; i++)
				{	
					if(Flow.config.GetComponent<ConfigManager>().shopInApps[i].appleBundle == tempInApp.appleBundle || Flow.config.GetComponent<ConfigManager>().shopInApps[i].androidBundle == tempInApp.androidBundle)
					{
						tempInApp.image = Flow.config.GetComponent<ConfigManager>().shopInApps[i].image;
						Flow.config.GetComponent<ConfigManager>().shopInApps[i] = tempInApp;
						
						foundInApp = true;
						break;
					}
				}
				
				if(!foundInApp)
				{
					Flow.config.GetComponent<ConfigManager>().shopInApps.Add(tempInApp, ref Flow.config.GetComponent<ConfigManager>().shopInApps);
				}
			}
			
			Array.Sort(Flow.config.GetComponent<ConfigManager>().shopInApps, delegate(ShopInApp a, ShopInApp b) {
						return a.id.CompareTo(b.id);	
			});
			
			bool hasToRefreshGoodsScroll = false;
			foreach(IJSonObject item in items.ArrayItems)
			{
				ShopItem tempItem = new ShopItem();
				
				tempItem.id = item["item_id"].StringValue;
				tempItem.name = item["name"].StringValue;
				tempItem.coinPrice = item["price"].Int32Value;
				tempItem.type = item["type"].StringValue == "Item"? ShopItemType.NonConsumable : ShopItemType.Consumable;
				tempItem.hide = item["hide"].Int32Value == 1;
				
				string[] ids = {};
				string[] counts = {};
				
				try
				{
					ids = item["itemsWithin"].StringValue.Split(',');
					counts = item["itemsCount"].StringValue.Split(',');
				}
				catch
				{
					ids = new string[]{ item["itemsWithin"].StringValue };
					counts = new string[]{ item["itemsCount"].StringValue };
				}
				
				if(!item["itemsWithin"].IsNull) 
				{
					List<ShopItem> tempIWList = new List<ShopItem>();
				
					for(int i = 0 ; i < ids.Length ; i++)
					{
						//Debug.Log("iti: "+ids[i]);
						//Debug.Log("counti: "+counts[i]);
						ShopItem iw = GetShopItem(ids[i].Trim());
						//ShopItem jose = new ShopItem();
						
						iw.count = int.Parse(counts[i]);
						iw.id = ids[i].Trim();
						
						tempIWList.Add(iw);
					}
				
					tempItem.arraySize = tempIWList.Count;
					tempItem.itemsWithin = tempIWList.ToArray();
				}
				else
				{
					tempItem.arraySize = 0;
					tempItem.itemsWithin = new ShopItem[]{};
				}
				tempItem.description = item["description"].StringValue;
				//tempItem.hide = item["hide"].Int32Value == 1;
				
				//Debug.Log("item: "+tempItem.name);
				
				bool foundItem = false;
				
				for(int i = 0 ; i < Flow.config.GetComponent<ConfigManager>().shopItems.Length ; i++)
				{
					if(Flow.config.GetComponent<ConfigManager>().shopItems[i].id == tempItem.id)
					{
						tempItem.image = Flow.config.GetComponent<ConfigManager>().shopItems[i].image;
						Flow.config.GetComponent<ConfigManager>().shopItems[i] = tempItem;
						
						foundItem = true;
						hasToRefreshGoodsScroll = true;
						break;
					}
				}
				
				if(!foundItem)
				{
					//Debug.Log("adicionando "+tempItem.name);
					hasToRefreshGoodsScroll = true;
					Flow.config.GetComponent<ConfigManager>().shopItems.Add(tempItem, ref Flow.config.GetComponent<ConfigManager>().shopItems);
				}
				
			}
			
			Array.Sort(Flow.config.GetComponent<ConfigManager>().shopItems, delegate(ShopItem a, ShopItem b) {
						return a.id.CompareTo(b.id);	
			});
			
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsFacebook = features["facebook"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsInvite = features["invite"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsLike = features["like"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsRate = features["rate"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsShare = features["share"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsVideo = features["video"].Int32Value;
			Flow.config.GetComponent<ConfigManager>().shopFeatures.coinsWidget = features["widget"].Int32Value;
			
			if(refreshPrime && hasToRefreshGoodsScroll && Application.loadedLevelName == "Mainmenu") UIPanelManager.instance.transform.FindChild("ShopScenePanel").GetComponent<Shop>().RefreshItemsScroll();
			
		}
		
		if(refreshPrime) Init();
		
	}
Example #44
0
 public static string GetDescription(ShopItem item)
 {
     // Summarize products of the shop
     // for example, top three products that the owner selceted as hit items.
     return(item.ShopInfo.ShopName + " 의 3가지 히트상품(견본)");
 }
Example #45
0
 private void addShopInfo(ShopItem shopItem)
 {
     _shop.GetCollection().Add(shopItem.shopInfo);
     saveShop();
 }
Example #46
0
File: Buy7.cs Project: dahlia/lib9c
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx    = context;
            var            states = ctx.PreviousStates;

            if (ctx.Rehearsal)
            {
                foreach (var purchaseInfo in purchaseInfos)
                {
                    Address shardedShopAddress =
                        ShardedShopState.DeriveAddress(purchaseInfo.itemSubType, purchaseInfo.productId);
                    states = states
                             .SetState(shardedShopAddress, MarkChanged)
                             .SetState(purchaseInfo.sellerAvatarAddress, MarkChanged)
                             .MarkBalanceChanged(
                        GoldCurrencyMock,
                        ctx.Signer,
                        purchaseInfo.sellerAgentAddress,
                        GoldCurrencyState.Address);
                }
                return(states
                       .SetState(buyerAvatarAddress, MarkChanged)
                       .SetState(ctx.Signer, MarkChanged)
                       .SetState(Addresses.Shop, MarkChanged));
            }

            CheckObsolete(BlockChain.Policy.BlockPolicySource.V100080ObsoleteIndex, context);

            var addressesHex = GetSignerAndOtherAddressesHex(context, buyerAvatarAddress);

            var sw = new Stopwatch();

            sw.Start();
            var started = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}Buy exec started", addressesHex);

            if (!states.TryGetAvatarState(ctx.Signer, buyerAvatarAddress, out var buyerAvatarState))
            {
                throw new FailedLoadStateException(
                          $"{addressesHex}Aborted as the avatar state of the buyer was failed to load.");
            }

            sw.Stop();
            Log.Verbose("{AddressesHex}Buy Get Buyer AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            if (!buyerAvatarState.worldInformation.IsStageCleared(GameConfig.RequireClearedStageLevel.ActionsInShop))
            {
                buyerAvatarState.worldInformation.TryGetLastClearedStageId(out var current);
                throw new NotEnoughClearedStageLevelException(addressesHex,
                                                              GameConfig.RequireClearedStageLevel.ActionsInShop, current);
            }

            List <PurchaseResult> purchaseResults = new List <PurchaseResult>();
            List <SellerResult>   sellerResults   = new List <SellerResult>();
            MaterialItemSheet     materialSheet   = states.GetSheet <MaterialItemSheet>();

            buyerMultipleResult  = new BuyerMultipleResult();
            sellerMultipleResult = new SellerMultipleResult();

            foreach (var purchaseInfo in purchaseInfos)
            {
                PurchaseResult purchaseResult     = new PurchaseResult(purchaseInfo.productId);
                Address        shardedShopAddress =
                    ShardedShopState.DeriveAddress(purchaseInfo.itemSubType, purchaseInfo.productId);
                Address sellerAgentAddress  = purchaseInfo.sellerAgentAddress;
                Address sellerAvatarAddress = purchaseInfo.sellerAvatarAddress;
                Guid    productId           = purchaseInfo.productId;

                purchaseResults.Add(purchaseResult);

                if (purchaseInfo.sellerAgentAddress == ctx.Signer)
                {
                    purchaseResult.errorCode = ErrorCodeInvalidAddress;
                    continue;
                }

                if (!states.TryGetState(shardedShopAddress, out Bencodex.Types.Dictionary shopStateDict))
                {
                    ShardedShopState shardedShopState = new ShardedShopState(shardedShopAddress);
                    shopStateDict = (Dictionary)shardedShopState.Serialize();
                }

                sw.Stop();
                Log.Verbose("{AddressesHex}Buy Get ShopState: {Elapsed}", addressesHex, sw.Elapsed);
                sw.Restart();

                Log.Verbose(
                    "{AddressesHex}Execute Buy; buyer: {Buyer} seller: {Seller}",
                    addressesHex,
                    buyerAvatarAddress,
                    sellerAvatarAddress);
                // Find product from ShardedShopState.
                List       products               = (List)shopStateDict[ProductsKey];
                IValue     productIdSerialized    = productId.Serialize();
                IValue     sellerAgentSerialized  = purchaseInfo.sellerAgentAddress.Serialize();
                IValue     sellerAvatarSerialized = purchaseInfo.sellerAvatarAddress.Serialize();
                Dictionary productSerialized      = products
                                                    .Select(p => (Dictionary)p)
                                                    .FirstOrDefault(p =>
                                                                    p[LegacyProductIdKey].Equals(productIdSerialized) &&
                                                                    p[LegacySellerAvatarAddressKey].Equals(sellerAvatarSerialized) &&
                                                                    p[LegacySellerAgentAddressKey].Equals(sellerAgentSerialized));

                bool fromLegacy = false;
                if (productSerialized.Equals(Dictionary.Empty))
                {
                    if (purchaseInfo.itemSubType == ItemSubType.Hourglass ||
                        purchaseInfo.itemSubType == ItemSubType.ApStone)
                    {
                        purchaseResult.errorCode = ErrorCodeItemDoesNotExist;
                        continue;
                    }
                    // Backward compatibility.
                    IValue rawShop = states.GetState(Addresses.Shop);
                    if (!(rawShop is null))
                    {
                        Dictionary legacyShopDict = (Dictionary)rawShop;
                        Dictionary legacyProducts = (Dictionary)legacyShopDict[LegacyProductsKey];
                        IKey       productKey     = (IKey)productId.Serialize();
                        // SoldOut
                        if (!legacyProducts.ContainsKey(productKey))
                        {
                            purchaseResult.errorCode = ErrorCodeItemDoesNotExist;
                            continue;
                        }

                        productSerialized = (Dictionary)legacyProducts[productKey];
                        legacyProducts    = (Dictionary)legacyProducts.Remove(productKey);
                        legacyShopDict    = legacyShopDict.SetItem(LegacyProductsKey, legacyProducts);
                        states            = states.SetState(Addresses.Shop, legacyShopDict);
                        fromLegacy        = true;
                    }
                }

                ShopItem shopItem = new ShopItem(productSerialized);
                if (!shopItem.SellerAgentAddress.Equals(sellerAgentAddress))
                {
                    purchaseResult.errorCode = ErrorCodeItemDoesNotExist;
                    continue;
                }

                sw.Stop();
                Log.Verbose("{AddressesHex}Buy Get Item: {Elapsed}", addressesHex, sw.Elapsed);
                sw.Restart();

                if (0 < shopItem.ExpiredBlockIndex && shopItem.ExpiredBlockIndex < context.BlockIndex)
                {
                    purchaseResult.errorCode = ErrorCodeShopItemExpired;
                    continue;
                }

                if (!shopItem.Price.Equals(purchaseInfo.price))
                {
                    purchaseResult.errorCode = ErrorCodeInvalidPrice;
                    continue;
                }

                if (!states.TryGetAvatarState(sellerAgentAddress, sellerAvatarAddress, out var sellerAvatarState))
                {
                    purchaseResult.errorCode = ErrorCodeFailedLoadingState;
                    continue;
                }

                sw.Stop();
                Log.Verbose("{AddressesHex}Buy Get Seller AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed);
                sw.Restart();

                // Check Balance.
                FungibleAssetValue buyerBalance = states.GetBalance(context.Signer, states.GetGoldCurrency());
                if (buyerBalance < shopItem.Price)
                {
                    purchaseResult.errorCode = ErrorCodeInsufficientBalance;
                    continue;
                }

                // Check Seller inventory.
                ITradableItem tradableItem;
                int           count = 1;
                if (!(shopItem.ItemUsable is null))
                {
                    tradableItem = shopItem.ItemUsable;
                }
Example #47
0
	public bool PurchaseItem(ShopItem item, int cost)
	{
		Debug.Log ("køb ("+item+"), cost: " + cost);
		if ((score >= cost) && (liv < startLiv)) 
		{
			Debug.Log ("Ja");
			score -= cost;
			switch (item) 
			{
			case ShopItem.life:
				liv += 5;
				liv = (liv > startLiv)?startLiv:liv;
				break;
				default:
					Debug.Log ("unknown!");
				break;
			}
			return true;
		} 
		else
			return false;
	}
Example #48
0
 public void LavaGroundOnClick() => SelectedItem = lavaGround;
Example #49
0
        private static void PrintItem(int x, int y, Shop shop, ShopItem item, bool isBBC = false, bool isSelected = false)
        {
            if (item.IsNotItem)
            {
                ZOutput.PrintBB(x, y, item.Name, item.IsActive ? ItemColor : InactiveItemColor, SelectedItemColor, Color.DarkGray, isSelected ? SelectedItemBackColor : ItemBackColor);
                return;
            }

            if (isBBC)
            {
                var advert = (Advert) item.ItemObject;
                ZOutput.PrintBB(x, y, string.Format(item.Name, Enums.Get_Name(advert.Merchandise), advert.Price).PadRight(shop.Header.Length, ' '),
                    item.IsActive ? ItemColor : InactiveItemColor, SelectedItemColor, Color.DarkGray, isSelected ? SelectedItemBackColor : ItemBackColor);
            }
            else
            {
                ZOutput.Print(x, y, item.Name.PadRight(shop.Header.Length-4, ' '),
                    isSelected ? SelectedItemColor : item.IsActive ? ItemColor : InactiveItemColor,
                    isSelected ? SelectedItemBackColor : ItemBackColor);

                if (item.IsActive)
                    ZIOX.Draw_Currency(x + shop.Header.Length-5, y, item.Price, 4, false);
                else
                    ZOutput.Print(x + shop.Header.Length-2, y, "--", InactiveItemColor);
            }
        }
Example #50
0
        private void AddItemPanel(ShopItem item, bool visible)
        {
            var control = new ShopItemPanel(item)
            {
                Visible = visible
            };

            control.Action += itemPanel_Action;
            itemPanels.Add(item.GetHashCode(), control);
            flowPanel.SuspendLayout();
            flowPanel.Controls.Add(control);
            flowPanel.ResumeLayout();
        }
Example #51
0
	void DisplayShopItem(ShopItem item)
	{
		//ConditionsUtils.Conditions(item.Conditions, Data);

		EditorGUILayout.BeginHorizontal();
		//EditorGUILayout.PrefixLabel("Item");
		
		//item.Preffix = (ItemTypeEnum)EditorGUILayout.EnumPopup(item.Preffix, GUILayout.Width(200));
		EditorGUILayout.PrefixLabel(" ID: ");
		item.ID = EditorGUILayout.IntField(item.ID, GUILayout.Width(50));
		EditorGUILayout.PrefixLabel(" level: ");
		item.Level = EditorGUILayout.IntField(item.Level, GUILayout.Width(50));
		EditorGUILayout.PrefixLabel(" amount: ");
		item.StackAmount = EditorGUILayout.IntField(item.StackAmount, GUILayout.Width(50));
		EditorGUILayout.PrefixLabel("Item Type");
		item.itemType = (ItemType)EditorGUILayout.EnumPopup(item.itemType , GUILayout.Width(100));
		EditorGUILayout.EndHorizontal();
		
	}
Example #52
0
 private void SetItem(object obj)
 {
     shopItemToConfirm = (ShopItem)obj;
     PopulateView();
 }
Example #53
0
 public void ChangeDescription(ShopItem i, string newDesk)
 {
     i.Description = Encoding.UTF8.GetString(Utils.UtilsIO.GenerateArray(Encoding.UTF8.GetBytes(newDesk), 1024));
 }
Example #54
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx    = context;
            var            states = ctx.PreviousStates;

            if (ctx.Rehearsal)
            {
                states = states.SetState(ShopState.Address, MarkChanged);
                return(states.SetState(sellerAvatarAddress, MarkChanged));
            }

            var addressesHex = GetSignerAndOtherAddressesHex(context, sellerAvatarAddress);

            var sw = new Stopwatch();

            sw.Start();
            var started = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}Sell Cancel exec started", addressesHex);

            if (!states.TryGetAgentAvatarStates(ctx.Signer, sellerAvatarAddress, out _, out var avatarState))
            {
                return(states);
            }
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Cancel Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            if (!avatarState.worldInformation.TryGetUnlockedWorldByStageClearedBlockIndex(
                    out var world))
            {
                return(states);
            }

            if (world.StageClearedId < GameConfig.RequireClearedStageLevel.ActionsInShop)
            {
                // 스테이지 클리어 부족 에러.
                return(states);
            }

            if (!states.TryGetState(ShopState.Address, out Bencodex.Types.Dictionary shopStateDict))
            {
                return(states);
            }
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Cancel Get ShopState: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            // 상점에서 아이템을 빼온다.
            Dictionary products = (Dictionary)shopStateDict["products"];

            IKey productIdSerialized = (IKey)productId.Serialize();

            if (!products.ContainsKey(productIdSerialized))
            {
                return(states);
            }

            ShopItem outUnregisteredItem = new ShopItem((Dictionary)products[productIdSerialized]);

            products      = (Dictionary)products.Remove(productIdSerialized);
            shopStateDict = shopStateDict.SetItem("products", products);

            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Cancel Get Unregister Item: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            //9c-beta 브랜치에서는 블록 인덱스도 확인 해야함 (이전 블록 유효성 보장)
            if (outUnregisteredItem.SellerAvatarAddress != sellerAvatarAddress)
            {
                Log.Error("{AddressesHex}Invalid Avatar Address", addressesHex);
                return(states);
            }

            // 메일에 아이템을 넣는다.
            result = new SellCancellation.Result
            {
                shopItem   = outUnregisteredItem,
                itemUsable = outUnregisteredItem.ItemUsable
            };
            var mail = new SellCancelMail(result, ctx.BlockIndex, ctx.Random.GenerateRandomGuid(), ctx.BlockIndex);

            result.id = mail.id;

            avatarState.Update(mail);
            avatarState.UpdateFromAddItem(result.itemUsable, true);
            avatarState.updatedAt  = ctx.BlockIndex;
            avatarState.blockIndex = ctx.BlockIndex;
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Cancel Update AvatarState: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            states = states.SetState(sellerAvatarAddress, avatarState.Serialize());
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Cancel Set AvatarState: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            states = states.SetState(ShopState.Address, shopStateDict);
            sw.Stop();
            var ended = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}Sell Cancel Set ShopState: {Elapsed}", addressesHex, sw.Elapsed);
            Log.Verbose("{AddressesHex}Sell Cancel Total Executed Time: {Elapsed}", addressesHex, ended - started);
            return(states);
        }
Example #55
0
 public void Setup()
 {
     dataBase.DeleteAllItems();
     dataBase.DeleteAllItemTypes();
     dataBase.DeleteAllShops();
     itemType = new ItemType {Name = ItemTypeName};
     Assert.IsTrue(dataBase.InsertItemType(itemType));
     IList<ItemType> itemTypes = dataBase.GetItemTypes();
     const string shopName = "trgovina 1";
     shop = new Shop(shopName)
         {Address = "asdasd", City = "assdf fs", IsCompany = true, Owner = "asdfaf safwefase", PostalCode = 1234};
     Assert.IsTrue(dataBase.InsertShop(shop));
     item = new Item("ID00001", "item 1")
         {
             ItemType = itemTypes[0].Id,
             Notes = "bla bla bal...",
         };
     Assert.IsTrue(dataBase.InsertItem(item));
     price = new Price(1.2, 1.1) {ItemId = item.UniqueId, ShopId = shop.Id};
     Assert.IsTrue(dataBase.InsertPrice(price));
     DateTime dateTime = new DateTime(DateTime.Now.Ticks);
     shopItem = new ShopItem {ItemId = item.UniqueId, ShopId = shop.Id, PriceId = price.Id, DateTime = dateTime};
     shopItem.SetNumberOfItems(5);
     Assert.IsTrue(dataBase.InsertShopItem(shopItem));
     tracker = new Tracker(shopItem) {SoldCount = 2, DateTime = dateTime};
     Assert.IsTrue(dataBase.InsertTracker(tracker));
 }
    public void SetGameItem(ShopItem item, UIShopManager manager)
    {
        uiShopManager = manager;
        shopItem      = item;
        goldPrice     = shopItem.PriceGold;
        silverPrice   = shopItem.PriceSilver;

        lblName.text = GameManager.localization.getItem(item.ItemId).Name;

        _playTween = btnInformation.GetComponent <UIPlayTween>();


        _playTween.tweenTarget = uiShopManager.uiItemReview.gameObject;
        btnInformation.gameObject.SetActive(true);
        IconOfItem.mainTexture = Helper.LoadTextureForSupportItem(item.ItemId);
        IconOfItem.SetDimensions(120, 120);
        if (item.UserLevel > 0)
        {
            lblLevel.text = string.Format(GameManager.localization.GetText("Shop_MinLevel"), item.UserLevel, item.UserLevel + 4);
        }

        _disable = false;

        if (manager.activeTab == UIShopManager.ActiveTab.IOSReCharge)
        {
            itemPriceRoot.SetActive(false);
            vaultRoot.SetActive(true);

            float VNDPrice = 0;

            if (Global.language == Global.Language.VIETNAM)
            {
                VNDPrice = item.PriceVND;
            }
            else
            {
                VNDPrice = item.PriceUSD;
            }

            if (item.PriceGoldSale > 0)
            {
                lblVaultGold.text = string.Format(GameManager.localization.GetText("Shop_GoldFormat"), item.PriceGoldSale);
            }
            else if (item.PriceSilverSale > 0)
            {
                lblVaultGold.text = string.Format(GameManager.localization.GetText("Shop_SilverFormat"), item.PriceSilverSale);
            }

            lblVaultVND.text = string.Format(GameManager.localization.GetText("Shop_VNDFormat"), VNDPrice);

            if (item.Promotion > 0)
            {
                bonusRoot.SetActive(true);
                lblBonus.text = string.Format(GameManager.localization.GetText("Shop_GoldFormat"), item.Promotion);
            }
        }
        else
        {
            itemPriceRoot.SetActive(true);
            vaultRoot.SetActive(false);
        }
    }
Example #57
0
    // Update is called once per frame
    void Update()
    {
        // ----------------------------------------------------
        // TIMER
        timer += Time.deltaTime;
        if ((timer >= waitTime) && !selectorReady)
        {
            selectorReady = true; timer = 0f;
        }
        else
        {
            selectorReady = false;
        }

        if (selectorReady)
        {
            // ----------------------------------------------------
            // SELECT ITEM
            items = GetComponentsInChildren <ShopItem>();
            if (items.Length > 0)
            {
                bool upPressed   = (Input.GetAxis(PlayerInputs._Key_vertical) < 0f);
                bool downPressed = (Input.GetAxis(PlayerInputs._Key_vertical) > 0f);

                if (upPressed)
                {
                    index = (index >= items.Length) ? 0 : (index + 1);
                }
                else if (downPressed)
                {
                    index = (index <= 0) ? (items.Length - 1) : (index - 1);
                }

                if (upPressed || downPressed)

                {
                    // old item
                    selectorReady = false;
                    if (!!selectedItem)
                    {
                        Image button1 = selectedItem.gameObject.GetComponent <Image>();
                        if (!!button1)
                        {
                            button1.color = Color.white;
                        }
                    }

                    // new item
                    try
                    {
                        selectedItem = ((index >= 0) && (items.Length > index)) ?
                                       items[index] : items[0];
                        Image button2 = selectedItem.gameObject.GetComponent <Image>();
                        if (!!button2)
                        {
                            button2.color = Color.red;
                        }
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        print(" SELECTED ITEM OUF OF RANGE : " + index);
                    }
                }

                // ----------------------------------------------------
                // UDPDATE INFO
                if (!!selectedItem)
                {
                    string item_name = selectedItem.item_name;

                    //INFO TEXT
                    Text[] infotexts = GetComponentsInChildren <Text>();
                    foreach (Text t in infotexts)
                    {
                        if (t.name == Constants.shopitem_infotext)
                        {
                            t.text = Constants.shopItems_InfoText[item_name];
                        }
                    }

                    // INFO IMAGE
                    Sprite infoSprite = selectedItem.itemInfoImage;
                    if (!!infoSprite)
                    {
                        //GameObject infoimagetGO = GameObject.FindGameObjectWithTag(Constants.shopitem_infoimage);
                        Image[]    infoimages  = GetComponentsInChildren <Image>();
                        GameObject infoimageGO = null;
                        foreach (Image img in infoimages)
                        {
                            if (img.name == Constants.shopitem_infoimage)
                            {
                                infoimageGO = img.gameObject; break;
                            }
                        }
                        if (!!infoimageGO)
                        {
                            Image infoImage = infoimageGO.GetComponent <Image>();
                            if (!!infoImage)
                            {
                                if (Constants.DEBUG_ENABLED)
                                {
                                    print("UPDATE INFO IMAGE IN SHOP ");
                                }
                                infoImage.sprite = infoSprite;
                            }
                        }
                    }
                }// !updateinfo
                 // ----------------------------------------------------
            }
            // ----------------------------------------------------
            // BUY
            if (Input.GetKey(KeyCode.Space))
            {
                GameObject player = GameObject.Find("Player");
                if (!!player)
                {
                    PlayerBehavior pb = player.GetComponent <PlayerBehavior>();
                    if (!!pb)
                    {
                        int money = pb.getBankAccount();
                        int price = selectedItem.item_price;
                        if (money >= price)
                        {
                            pb.spendMoney(price);
                            string itemName = selectedItem.item_name;
                            pb.unlock(itemName);
                            selectedItem.buy();

                            items = GetComponentsInChildren <ShopItem>();
                            if (items.Length > 0)
                            {
                                index        = 0;
                                selectedItem = items[index];
                            }

                            if (Constants.DEBUG_ENABLED)
                            {
                                bool b = pb.hasUnlock(itemName); print("HAS UNLOCK ITEM ? " + b);
                            }
                        }
                    }
                }
            }
        } //! selectorReady
    }     //!update
Example #58
0
 public static ShopItemViewModel Map(ShopItem shopItem)
 {
     return(AutoMapper.Mapper.Map <ShopItemViewModel>(shopItem));
 }
Example #59
0
 public Classroom(RoomType RoomType, short Number, byte DaysToBuild, short ChairsMax, short DesksMax, short ComputersMax, bool IslandsPossible, Point[] Locations, short[][] TileData)
 {
     this.RoomType = RoomType;
     this.Blackboard = new ShopItem("NoBlackboardName", "NoBlackboardDescription", -1, 0, -10);
     this.Number = Number;
     this.DaysToBuild = DaysToBuild;
     this.ChairsMax = ChairsMax;
     this.Chairs = 0;
     this.DesksMax = DesksMax;
     this.Desks = 0;
     this.ComputersMax = ComputersMax;
     this.Computers = 0;
     this.IslandSize = 4;
     this.IslandsPossible = IslandsPossible;
     this.Locations = Locations;
     this.TileData = TileData;
 }
Example #60
0
        // Anything the user sells goes into faction inventory as well.
        public static bool PostSoldItems(Dictionary <string, ShopDefItem> soldItems, FactionValue faction)
        {
            List <ShopItem> items = new List <ShopItem>();

            foreach (ShopDefItem soldItem in soldItems.Values.ToList <ShopDefItem>())
            {
                SalvageDef salvage = new SalvageDef();
                soldItem.ToSalvageDef(ref salvage);
                if (salvage != null)
                {
                    ShopItem item = new ShopItem();
                    item.ID     = salvage.Description.Id;
                    item.UiName = salvage.Description.UIName;
                    switch (salvage.ComponentType)
                    {
                    case ComponentType.AmmunitionBox:
                    {
                        item.Type = ShopItemType.AmmunitionBox;
                        break;
                    }

                    case ComponentType.HeatSink:
                    {
                        item.Type = ShopItemType.HeatSink;
                        break;
                    }

                    case ComponentType.JumpJet:
                    {
                        item.Type = ShopItemType.JumpJet;
                        break;
                    }

                    case ComponentType.MechPart:
                    {
                        item.Type = ShopItemType.MechPart;
                        break;
                    }

                    case ComponentType.Upgrade:
                    {
                        item.Type = ShopItemType.Upgrade;
                        break;
                    }

                    case ComponentType.Weapon:
                    {
                        item.Type = ShopItemType.Weapon;
                        break;
                    }
                    }
                    item.Count = 1;
                    items.Add(item);
                }
            }
            string          testjson = JsonConvert.SerializeObject(items);
            HttpWebRequest  request  = new RequestBuilder(WarService.PostSoldItems).Faction(faction).PostData(testjson).Build();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader    = new StreamReader(responseStream);
                string       mapstring = reader.ReadToEnd();
                return(true);
            }
        }