示例#1
0
        public static void JavaRequestPurchaseAsync(Purchasable purchasable)
        {
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
            // again, make sure the thread is attached..
            AndroidJNI.AttachCurrentThread();

            AndroidJNI.PushLocalFrame(0);

            try
            {
                Debug.Log(string.Format("JavaRequestPurchaseAsync purchasable: {0}", purchasable.getProductId()));

                using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
                {
                    ajc.CallStatic <String>("requestPurchaseAsync", new object[] { purchasable.getProductId() + "\0" });
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(string.Format("OuyaSDK.JavaRequestPurchaseAsync exception={0}", ex));
            }
            finally
            {
                AndroidJNI.PopLocalFrame(IntPtr.Zero);
            }
#endif
        }
 public ISpecialPurchasable GetSpecialPurchasable(Purchasable purchasable, Business business)
 {
     return(purchasable.Id switch
     {
         29 => new SpecializedTraining(_context, business, _purchasableHelper),
         _ => null,
     });
示例#3
0
        public void Simulation_Iterate_AgentsDie()
        {
            var goodsa = new[] { "Food" }
            .ToDictionary(o => o, o => new Good(o));
            var sa    = new Simulation(goodsa);
            var fa    = goodsa["Food"];
            var needa = new Need(fa, 30000, 0.0, 150.0);
            var aa    = new Agent(new[] { needa }, 100.0);

            sa.AddAgents(new[] { aa });
            var pa = new Purchasable(
                aa.AgentNumber, 4.0, new Stack(fa, 20.0));
            var ma = new Market(new[] { pa });

            sa.AddMarket(ma);

            sa.Iterate(1.0);

            var goodse = new[] { "Food" }
            .ToDictionary(o => o, o => new Good(o));
            var se = new Simulation(goodse);
            var fe = goodse["Food"];
            var me = new Market(Enumerable.Empty <Purchasable>());

            se.AddMarket(me);

            Assert.AreEqual(se, sa);
        }
示例#4
0
        public static void JavaAddGetProduct(Purchasable purchasable)
        {
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
            // again, make sure the thread is attached..
            AndroidJNI.AttachCurrentThread();

            AndroidJNI.PushLocalFrame(0);

            try
            {
                Debug.Log(string.Format("{0} OuyaSDK.JavaAddGetProduct", DateTime.Now));

                using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
                {
                    ajc.CallStatic("addGetProduct", purchasable.getProductId());
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(string.Format("OuyaSDK.JavaAddGetProduct exception={0}", ex));
            }
            finally
            {
                AndroidJNI.PopLocalFrame(IntPtr.Zero);
            }
#endif
        }
示例#5
0
        public static bool EnsurePurchaseIsValid(Purchasable purchase, Business business, int purchaseCount)
        {
            switch (purchase.Type.Id)
            {
            case (int)PurchasableTypeEnum.Employee:
                if (purchase.MaxEmployeeModifier >= 0)
                {
                    if (business.MaxEmployeeAmount >= business.AmountEmployed + purchaseCount)
                    {
                        return(true);
                    }
                }
                if (purchase.MaxEmployeeModifier < 0)
                {
                    if (business.MaxEmployeeAmount - purchase.MaxEmployeeModifier >= business.AmountEmployed + purchaseCount)
                    {
                        return(true);
                    }
                }
                break;

            case (int)PurchasableTypeEnum.Buff:
                if (business.MaxItemAmount + purchase.MaxItemAmountModifier >= (business.AmountOwnedItems + purchaseCount))
                {
                    return(true);
                }
                break;

            case (int)PurchasableTypeEnum.RealEstate:
                return(true);
            }

            return(false);
        }
示例#6
0
        public static Purchasable AdjustPurchasableCostWithSectorBonus(Purchasable purchase, Business business)
        {
            if (business.Sector == null)
            {
                return(purchase);
            }
            switch (business.Sector.Id)
            {
            case (int)SectorType.Tech:
                if (purchase.Type.Id == (int)PurchasableTypeEnum.Buff)
                {
                    purchase.Cost -= (float)(purchase.Cost * .1);
                }
                break;

            case (int)SectorType.Marketing:
                if (purchase.Type.Id == (int)PurchasableTypeEnum.Employee)
                {
                    purchase.Cost -= (float)(purchase.Cost * .1);
                }
                break;

            case (int)SectorType.RealEstate:
                if (purchase.Type.Id == (int)PurchasableTypeEnum.RealEstate)
                {
                    purchase.CashModifier = 0;
                }
                break;
            }

            return(purchase);
        }
示例#7
0
        Simulation SimulationWithSellerWithPurchAndBuyer()
        {
            var food = new Good("food");
            var goods = new[] { food }.ToDictionary(o => o.Name, o => o);
            var simulation = new Simulation(goods);
            var seller     = new Agent(null, 0.0);

            simulation.AddAgents(new[] { seller });
            var purchasable = new Purchasable(
                seller.AgentNumber, 10.0, new Stack(food, 10.0));
            var market = new Market(new[] { purchasable });

            simulation.AddMarket(market);
            var buyer = new Agent(null, 200.0);

            simulation.AddAgents(new[] { buyer });
            simulation.AgentIsPondering += (s, e) =>
            {
                if (e.Agent == buyer)
                {
                    e.EnqueueAction(new BuyAction(
                                        simulation,
                                        market,
                                        purchasable,
                                        buyer,
                                        10.0));
                    e.Handled = true;
                }
            };
            return(simulation);
        }
示例#8
0
        public void Simulation_Purchase_PurchasableDeduced()
        {
            var goods = new[] { "Food" }
            .ToDictionary(o => o, o => new Good(o));
            var simulation = new Simulation(goods);
            var food       = goods["Food"];
            var buyer      = new Agent(Enumerable.Empty <Need>(), 100.0);
            var seller     = new Agent(Enumerable.Empty <Need>(), 100.0);

            simulation.AddAgents(new[] { buyer, seller });
            var purchasable = new Purchasable(
                seller.AgentNumber, 40.0, new Stack(food, 100.0));
            var market = new Market(new[] { purchasable });

            simulation.AddMarket(market);
            simulation.AgentIsPondering += (sender, args) =>
            {
                if (args.Agent != buyer)
                {
                    return;
                }
                args.EnqueueAction(new BuyAction(
                                       simulation, market, purchasable, buyer, 2.0));
                args.Handled = true;
            };

            simulation.Iterate();

            Assert.AreEqual(1, market.Purchasables.Count());
            Assert.AreEqual(98.0, market.Purchasables.First().Stack.Quantity);
        }
示例#9
0
        public void Simulation_Purchase_CreditsDeposited()
        {
            var goods = new[] { "Food" }
            .ToDictionary(o => o, o => new Good(o));
            var s   = new Simulation(goods);
            var f   = goods["Food"];
            var ab  = new Agent(Enumerable.Empty <Need>(), 100.0);
            var @as = new Agent(Enumerable.Empty <Need>(), 100.0);

            s.AddAgents(new[] { ab, @as });
            var p = new Purchasable(
                @as.AgentNumber, 40.0, new Stack(f, 100.0));
            var m = new Market(new[] { p });

            s.AddMarket(m);
            s.AgentIsPondering += (sender, args) =>
            {
                args.EnqueueAction(new BuyAction(s, m, p, ab, 2.0));
                args.Handled = true;
            };

            s.Iterate();

            Assert.AreEqual <double>(180.0, @as.Credits);
        }
示例#10
0
        public static void RequestPurchase(Purchasable purchasable)
        {
            if (null == sInstance)
            {
                Log.Error(TAG, "Activity is null!");
                return;
            }

            if (null == _ouyaFacade)
            {
                Log.Error(TAG, "OuyaFacade is null!");
                return;
            }

            Action action = () => {
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Construct CustomRequestPurchaseListener");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                sRequestPurchaseListener = new Game1.CustomRequestPurchaseListener();

                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Invoke RequestPurchase");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                _ouyaFacade.RequestPurchase(sInstance, purchasable, sRequestPurchaseListener);
            };

            sInstance.RunOnUiThread(action);
        }
示例#11
0
 public void UnlockUpgrades(Purchasable item)
 {
     if (item.quantity >= 5)
     {
         PlayerManager.Inst.unlocked_Upgrades = true;
         Upgradeprefab.GetComponent <UpgradeManager>().index = item.first_upgrade_index;
         Instantiate(Upgradeprefab, UpgradeTab);
     }
 }
    private bool checkIfValidTrade(Purchasable a)
    {
        Property aProperty = a as Property;

        if (aProperty != null)
        {
            return(!a.morgaged && aProperty.numOfHouses == 0 && a.owner != null);
        }
        return(!a.morgaged && a.owner != null);
    }
示例#13
0
 public BuyAction(Simulation simulation,
                  Market market, Purchasable purchasable,
                  Agent buyer, double quantity)
 {
     this.Simulation  = simulation;
     this.Market      = market;
     this.Purchasable = purchasable;
     this.Buyer       = buyer;
     this.Quantity    = quantity;
 }
示例#14
0
        public ActionResult <Purchasable> Get(int id)
        {
            Purchasable found = Menu.Find(i => i.Id == id);

            if (found != null)
            {
                return(found);
            }
            return(BadRequest("{\"error\": \"not found\"}"));
        }
示例#15
0
    public static void requestPurchase(Purchasable purchasable)
    {
        if (!isIAPInitComplete())
        {
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
        OuyaUnityPlugin.requestPurchase(purchasable.productId);
#endif
    }
示例#16
0
        public ActionResult Delete(int id)
        {
            Purchasable OldData = Menu.Find(i => i.Id == id);

            if (OldData == null)
            {
                return(BadRequest());
            }
            Menu.Remove(OldData);
            return(Ok());
        }
示例#17
0
    public void BuyPurchasable(int index)
    {
        Purchasable item = PlayerManager.Inst.purchases[index];

        if (item.Purchase())
        {
            UnlockUpgrades(item);
            UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.GetComponentInChildren <Text>().text =
                "Buy " + item.Name + "\n$" + item.price;
        }
    }
 public void buyProperty(Purchasable property, Player player)
 {
     if (player.money >= property.price)
     {
         buy.SetActive(true);
     }
     notBuy.SetActive(true);
     handler.turnOffDice();
     currentProperty = property;
     currentPlayer   = player;
 }
示例#19
0
        /// <summary>
        /// Requests that the specified Purchasable be purchased on behalf of the current user.
        /// The IAP client service is responsible for identifying the user and requesting credentials as appropriate,
        /// as well as providing all of the UI for the purchase flow. When purchases are successful, a Product object
        /// is returned that describes the product that was purchased.
        /// </summary>
        /// <param name="product">The Purchasable object that describes the item to be purchased.</param>
        /// <returns>Returns true if the purchase was successful.</returns>
        public async Task <bool> RequestPurchaseAsync(Product product)
        {
            if (ReferenceEquals(product, null))
            {
                throw new ArgumentNullException("product");
            }

            var tcs = new TaskCompletionSource <bool>();

            // Create the Purchasable object from the supplied product
            var sr = SecureRandom.GetInstance("SHA1PRNG");

            // This is an ID that allows you to associate a successful purchase with
            // it's original request. The server does nothing with this string except
            // pass it back to you, so it only needs to be unique within this instance
            // of your app to allow you to pair responses with requests.
            var uniqueId = sr.NextLong().ToString("X");

            JSONObject purchaseRequest = new JSONObject();

            purchaseRequest.Put("uuid", uniqueId);
            purchaseRequest.Put("identifier", product.Identifier);
            var purchaseRequestJson = purchaseRequest.ToString();

            byte[] keyBytes = new byte[16];
            sr.NextBytes(keyBytes);
            var key = new SecretKeySpec(keyBytes, "AES");

            byte[] ivBytes = new byte[16];
            sr.NextBytes(ivBytes);
            var iv = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding", "BC");

            cipher.Init(CipherMode.EncryptMode, key, iv);
            var payload = cipher.DoFinal(Encoding.UTF8.GetBytes(purchaseRequestJson));

            cipher = Cipher.GetInstance("RSA/ECB/PKCS1Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, _publicKey);
            var encryptedKey = cipher.DoFinal(keyBytes);

            var purchasable = new Purchasable(
                product.Identifier,
                Convert.ToBase64String(encryptedKey, Base64FormattingOptions.None),
                Convert.ToBase64String(ivBytes, Base64FormattingOptions.None),
                Convert.ToBase64String(payload, Base64FormattingOptions.None));

            var listener = new PurchaseListener(tcs, _publicKey, product, uniqueId);

            RequestPurchase(purchasable, listener);
            // No timeout for purchase as it shows a user dialog
            return(await tcs.Task);
        }
示例#20
0
        public ActionResult <Purchasable> Put(int id, [FromBody] Purchasable newData)
        {
            Purchasable OldData = Menu.Find(i => i.Id == id);

            if (OldData == null)
            {
                return(BadRequest());
            }
            Menu.Remove(OldData);
            Menu.Add(newData);
            return(newData);
        }
 private void trade(Purchasable property)
 {
     if (checkIfValidTrade(property))
     {
         Player p = property.owner;
         property.owner        = propertyToTrade.owner;
         propertyToTrade.owner = p;
         checkForChanges(property, p);
         checkForChanges(propertyToTrade, property.owner);
     }
     cancel();
 }
    /// <summary>
    ///
    /// </summary>
    private void JsonDataDatabase(List <Purchasable> purchasable,
                                  List <GameObject> item,
                                  string location,
                                  JsonData data,
                                  Transform Parent,
                                  SlotType slotType)
    {
        try
        {
            string app_Path = Application.dataPath + "/StreamingAssets/" + location + FileType;
            data = JsonMapper.ToObject(File.ReadAllText(app_Path));

            List <Purchasable> items = new List <Purchasable>();

            for (int i = 0; i < data.Count; i++)
            {
                purchasable.Add(new Purchasable(
                                    i,
                                    (string)data[i]["Name"],
                                    float.Parse(data[i]["BaseCost"].ToString()),
                                    Item_Images[Function.FindImageID(Item_Images, (string)data[i]["SpriteName"])],
                                    float.Parse(data[i]["Coefficent"].ToString()),
                                    (int)data[i]["Count"],
                                    float.Parse(data[i]["ResourceRate"].ToString()),
                                    (string)data[i]["ItemID"],
                                    float.Parse(data[i]["TimeToCompleteTask"].ToString())));

                GameObject purchasablePrefab = Instantiate(Purchasable_Prefab);
                purchasablePrefab.transform.SetParent(Parent);
                purchasablePrefab.transform.localScale = new Vector3(1, 1, 1);
                purchasablePrefab.transform.position   = Parent.position;

                Purchasable purchasable_data = purchasablePrefab.GetComponent <PurchasableData>().Purchasable;
                purchasable_data.ID                    = purchasable[i].ID;
                purchasable_data.Item_Name             = purchasable[i].Item_Name;
                purchasable_data.Base_Cost             = purchasable[i].Base_Cost;
                purchasable_data.Cost                  = purchasable[i].Cost;
                purchasable_data.Coefficent            = purchasable[i].Coefficent;
                purchasable_data.Count                 = purchasable[i].Count;
                purchasable_data.Resource_Rate         = purchasable[i].Resource_Rate;
                purchasable_data.Item_ID               = purchasable[i].Item_ID;
                purchasable_data.Time_To_Complete_Task = purchasable[i].Time_To_Complete_Task;
                purchasable_data.Image                 = purchasable[i].Image;

                item.Add(purchasablePrefab);
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message + location);
        }
    }
示例#23
0
        public static Purchasable SwapPurchaseForUpgradeIfAlreadyBought(Purchasable purchase, Business business)
        {
            if (purchase.PurchasableUpgrade == null)
            {
                return(purchase);
            }
            if (business.BusinessPurchases.Any(s => s.PurchaseId == purchase.Id))
            {
                return(SwapPurchaseForUpgradeIfAlreadyBought(purchase.PurchasableUpgrade, business));
            }

            return(purchase);
        }
示例#24
0
        public async Task <PurchasableJsonReturn> PerformSpecialOnPurchaseActions(Purchasable purchasable, Business business)
        {
            var repo    = new SpecialPurchasableRepo(_context, this);
            var special = repo.GetSpecialPurchasable(purchasable, business);

            if (special == null)
            {
                return(null);
            }
            await special.OnPurchaseEffect();

            return(special.PurchaseResponse);
        }
示例#25
0
    void CreatePurchaseButton(Purchasable upgrade)
    {
        // Create button GameObject
        var purchaseButton = GameObject.Instantiate(buttonPrefab, Vector3.zero, Quaternion.identity, buttonGroup);

        purchaseButton.GetComponent <PurchaseButton>().upgrade = upgrade;

        // Setup OnClick listener so the panel is hidden after purchase
        purchaseButton.GetComponent <Button>().onClick.AddListener(uc.ToggleUpgradesPanel);

        // Set the GameObject name
        purchaseButton.name = $"{upgrade.label} Button";
    }
示例#26
0
    public void PurchaseTrophy(Purchasable p)
    {
        if (!p.canAfford)
        {
            GetComponent <AudioSource>().Play();
            return;
        }
        p.MakePurchase();
        p.button.interactable = false;

        gameObject.SetActive(false);
        GameManager.Instance.FinishGame.SetActive(true);
        Timer.Instance.pauseTime = true;
    }
示例#27
0
        public async Task <Business> ApplyItemStatsToBussiness(Purchasable purchasable, Business business, int purchaseCount)
        {
            var existingBusinessPurchasesCount = (await _context.BusinessPurchases
                                                  .Include(s => s.Purchase)
                                                  .SingleOrDefaultAsync(s => s.BusinessId == business.Id && s.PurchaseId == purchasable.Id))?.AmountOfPurchases ?? 0;

            var currentAdjustedPrice = (double)(purchasable.Cost * Math.Pow((1 + purchasable.PerOwnedModifier), existingBusinessPurchasesCount));
            var purchasesApplied     = 0;

            for (int i = 0; i < purchaseCount; ++i)
            {
                if (currentAdjustedPrice > business.Cash)
                {
                    break;
                }
                business.Cash        -= currentAdjustedPrice;
                currentAdjustedPrice += (currentAdjustedPrice * purchasable.PerOwnedModifier);
                ++purchasesApplied;
                business.CashPerSecond     += purchasable.CashModifier;
                business.EspionageChance   += purchasable.EspionageModifier;
                business.MaxEmployeeAmount += purchasable.MaxEmployeeModifier;
                business.MaxItemAmount     += purchasable.MaxItemAmountModifier;
                business.EspionageDefense  += purchasable.EspionageDefenseModifier;
            }

            var businessPurchase = business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id);

            if (businessPurchase != null)
            {
                businessPurchase.AmountOfPurchases += purchasesApplied;
            }
            else
            {
                business.BusinessPurchases.Add(new BusinessPurchase()
                {
                    BusinessId = business.Id, PurchaseId = purchasable.Id, AmountOfPurchases = purchaseCount
                });
            }

            if (purchasable.Type.Id == (int)PurchasableTypeEnum.Employee)
            {
                business.AmountEmployed += purchasesApplied;
            }
            if (purchasable.Type.Id == (int)PurchasableTypeEnum.Buff)
            {
                business.AmountOwnedItems += purchasesApplied;
            }

            return(business);
        }
    public void OnClick()
    {
        Purchasable productToPurchase = Purchaser.instance.purchaseItems [productToPurchaseIndex];

        if (productToPurchase.productType == UnityEngine.Purchasing.ProductType.NonConsumable)
        {
            Purchaser.instance.BuyNonConsumable(productToPurchase.generalProductID);
        }

        if (productToPurchase.productType == UnityEngine.Purchasing.ProductType.Consumable)
        {
            Purchaser.instance.BuyConsumable(productToPurchase.generalProductID);
        }
    }
    /// <summary>
    ///
    /// </summary>
    public float GetRewardRate()
    {
        float value = 0;

        for (int i = 0; i < SaveLoad.Instance.Meat_Item.Count; i++)
        {
            Purchasable purchasable = SaveLoad.Instance.Meat_Item[i].GetComponent <PurchasableData>().Purchasable;
            if (purchasable.Unlocked == true)
            {
                value += (purchasable.Resource_Rate * purchasable.Count) / purchasable.Time_To_Complete_Task;
            }
        }

        return(value);
    }
示例#30
0
    public void PurchasePlaqueSet(Purchasable p)
    {
        if (!p.canAfford)
        {
            GetComponent <AudioSource>().Play();
            return;
        }
        p.MakePurchase();
        p.button.interactable = false;

        fishBehavior.scoreModifier = 2;
        //Select resume button
        GameObject.Find("ShopResume").GetComponent <Button>().Select();
        GameManager.Instance.UpdateScore();
    }
示例#31
0
 public static void requestPurchase(Purchasable purchasable)
 {
     if (!m_iapInitComplete)
     {
         return;
     }
     #if UNITY_ANDROID && !UNITY_EDITOR
     OuyaUnityPlugin.requestPurchase(purchasable.productId);
     #endif
 }
示例#32
0
 public Task<string> RequestPurchase(Purchasable purchasable)
 {
     var tcs = new TaskCompletionSource<string>();
     RequestPurchase(purchasable, new StringListener(tcs));
     return tcs.Task;
 }
示例#33
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //Log.Info(TAG, string.Format("BUTTON_O is {0}", OuyaInput.GetButton(OuyaController.BUTTON_O)));

            if (OuyaInput.GetButtonUp(0, OuyaController.BUTTON_A))
            {
                Exit();
            }

            // TODO: Add your update logic here
            m_focusManager.UpdateFocus();

            foreach (ButtonSprite button in m_buttons)
            {
                // button is active if the selected button is true
                button.m_isActive = (button == m_focusManager.SelectedButton);
            }

            if (OuyaInput.GetButtonUp (OuyaController.BUTTON_MENU)) {
                m_debugText = "Pause button detected.";
                m_focusManager.SelectedButton = BtnPause;
            }

            if (OuyaInput.GetButtonUp (OuyaController.BUTTON_O)) {
                if (m_focusManager.SelectedButton == BtnRequestProducts) {
                    s_productIndex = 0;
                    s_products.Clear ();
                    m_debugText = "Requesting products...";
                    Activity1.RequestProducts ();
                } else if (m_focusManager.SelectedButton == BtnRequestPurchase) {
                    if (s_productIndex < s_products.Count) {
                        Purchasable purchasable = new Purchasable (s_products [s_productIndex].Identifier);
                        m_debugText = "Requesting purchase...";
                        Activity1.RequestPurchase (purchasable);
                    } else {
                        m_debugText = "Be sure to request products to select a purchase...";
                    }
                } else if (m_focusManager.SelectedButton == BtnRequestReceipts) {
                    m_debugText = "Requesting receipts...";
                    Activity1.RequestReceipts ();
                } else if (m_focusManager.SelectedButton == BtnRequestGamerInfo) {
                    m_debugText = "Requesting GamerInfo...";
                    Activity1.RequestGamerInfo ();
                } else if (m_focusManager.SelectedButton == BtnExit) {
                    m_debugText = "Exiting...";
                    Activity1.Quit ();
                } else if (m_focusManager.SelectedButton == BtnPause) {
                    m_debugText = "Pause button detected...";
                    m_focusManager.SelectedButton = BtnPause;
                }
            }

            if (m_focusManager.SelectedButton == BtnRequestProducts ||
                m_focusManager.SelectedButton == BtnRequestPurchase) {
                if (OuyaInput.GetButtonUp (OuyaController.BUTTON_DPAD_UP)) {
                    if (s_productIndex > 0) {
                        --s_productIndex;
                    }
                }
                if (OuyaInput.GetButtonUp (OuyaController.BUTTON_DPAD_DOWN)) {
                    if ((s_productIndex+1) < s_products.Count) {
                        ++s_productIndex;
                    }
                }
            }

            base.Update(gameTime);

            OuyaInput.ClearButtonStates();
        }
示例#34
0
 public static void requestPurchase(Purchasable purchasable)
 {
     OuyaUnityPlugin.requestPurchaseAsync(purchasable.productId);
 }
示例#35
0
        public static void RequestPurchase(Purchasable purchasable)
        {
            if (null == sInstance) {
                Log.Error (TAG, "Activity is null!");
                return;
            }

            if (null == _ouyaFacade) {
                Log.Error (TAG, "OuyaFacade is null!");
                return;
            }

            Action action = () => {
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Construct CustomRequestPurchaseListener");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                sRequestPurchaseListener = new Game1.CustomRequestPurchaseListener();

                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Invoke RequestPurchase");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                _ouyaFacade.RequestPurchase(sInstance, purchasable, sRequestPurchaseListener);
            };
            sInstance.RunOnUiThread (action);
        }
示例#36
0
        public static void RequestProducts()
        {
            if (null == sInstance) {
                Log.Error (TAG, "Activity is null!");
                return;
            }

            if (null == _ouyaFacade) {
                Log.Error (TAG, "OuyaFacade is null!");
                return;
            }

            Action action = () => {
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Construct CustomRequestProductsListener");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                sRequestProductsListener = new Game1.CustomRequestProductsListener();

                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "Invoke RequestProducts");
                Log.Info(TAG, "****************");
                Log.Info(TAG, "****************");
                List<Purchasable> products = new List<Purchasable>();
                foreach (string id in Game1.PURCHASABLES)
                {
                    Purchasable purchasable = new Purchasable(id);
                    products.Add(purchasable);
                }
                _ouyaFacade.RequestProductList(sInstance, products, sRequestProductsListener);
            };
            sInstance.RunOnUiThread (action);
        }
示例#37
0
	void onPurchasing( SuppliesUIObject item, GameObject tag )
	{
		if( tag.tag == "BuyButton" )
		{
			Type t = item.GetType();
			
			AmmoUIObject a;
			HealthUIObject h;
			GunUIObject g;
			
			if( tag.name == "Button Background" )
			{
				tweenIn();

				if( t == typeof(AmmoUIObject) )
				{
					a = (AmmoUIObject)item;
					itemInQuestion.spriteName = a.ammo.spriteName;
					itemDescription.text = a.ammo.ammoName;
					s = a;
					p = a.ammo;
				}
				if( t == typeof(GunUIObject) )
				{
					g= (GunUIObject)item;
					itemInQuestion.spriteName = g.gunObj.model + "_Icon";
					itemDescription.text = g.gunObj.model;
					s = g;
					p = g.gunObj;
				}
				if( t == typeof(HealthUIObject) )
				{
					h = (HealthUIObject)item;
					itemInQuestion.spriteName = "HealthIcon";
					itemDescription.text = h.hPack.model;
					s = h;
					p = h.hPack;
				}
			}
			if( tag.name == "Label OK" )
			{
				if( p.GetType() == typeof(Ammo) )
				{
					Ammo a2 = (Ammo)p;
					
					if( DBAccess.instance.userPrefs.Gold >= a2.price )
					{
						DBAccess.instance.userPrefs.findAmmoAndSetAsPurchased(a2);
						DBAccess.instance.userPrefs.Gold -= a2.price;
					}
				}
				if( p.GetType() == typeof(Gun) )
				{
					Gun g2 = (Gun)p;
					
					if( DBAccess.instance.userPrefs.Gold >= g2.price )
					{
						DBAccess.instance.userPrefs.findGunAndSetAsPurchased((Gun)p);
						DBAccess.instance.userPrefs.Gold -= g2.price;
					}
				}
				if( p.GetType() == typeof(HealthPack) )
				{
					HealthPack h2 = (HealthPack)p;
					
					if( DBAccess.instance.userPrefs.Gold >= h2.price )
					{
						DBAccess.instance.userPrefs.findHealthPackAndSetAsPurchased((HealthPack)p);
						DBAccess.instance.userPrefs.Gold -= h2.price;
					}
				}
				
				if( onPurchased != null )
				{
					Debug.Log("onPurchased");
					onPurchased(s);
				}
				
				tweenOut();
			}
			if( tag.name == "Label Back" )
			{
				tweenOut();
			}
		}
	}
示例#38
0
        /// <summary>
        /// Requests that the specified Purchasable be purchased on behalf of the current user.
        /// The IAP client service is responsible for identifying the user and requesting credentials as appropriate,
        /// as well as providing all of the UI for the purchase flow. When purchases are successful, a Product object
        /// is returned that describes the product that was purchased.
        /// </summary>
        /// <param name="product">The Purchasable object that describes the item to be purchased.</param>
        /// <returns>Returns true if the purchase was successful.</returns>
        public async Task<bool> RequestPurchaseAsync(Product product)
        {
            if (ReferenceEquals(product, null))
                throw new ArgumentNullException("product");

            var tcs = new TaskCompletionSource<bool>();

            // Create the Purchasable object from the supplied product
            var sr = SecureRandom.GetInstance("SHA1PRNG");

            // This is an ID that allows you to associate a successful purchase with
            // it's original request. The server does nothing with this string except
            // pass it back to you, so it only needs to be unique within this instance
            // of your app to allow you to pair responses with requests.
            var uniqueId = sr.NextLong().ToString("X");

            JSONObject purchaseRequest = new JSONObject();
            purchaseRequest.Put("uuid", uniqueId);
            purchaseRequest.Put("identifier", product.Identifier);
            var purchaseRequestJson = purchaseRequest.ToString();

            byte[] keyBytes = new byte[16];
            sr.NextBytes(keyBytes);
            var key = new SecretKeySpec(keyBytes, "AES");

            byte[] ivBytes = new byte[16];
            sr.NextBytes(ivBytes);
            var iv = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, key, iv);
            var payload = cipher.DoFinal(Encoding.UTF8.GetBytes(purchaseRequestJson));

            cipher = Cipher.GetInstance("RSA/ECB/PKCS1Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, _publicKey);
            var encryptedKey = cipher.DoFinal(keyBytes);

            var purchasable = new Purchasable(
                        product.Identifier,
                        Convert.ToBase64String(encryptedKey, Base64FormattingOptions.None),
                        Convert.ToBase64String(ivBytes, Base64FormattingOptions.None),
                        Convert.ToBase64String(payload, Base64FormattingOptions.None));

            var listener = new PurchaseListener(tcs, _publicKey, product, uniqueId);
            RequestPurchase(purchasable, listener);
            // No timeout for purchase as it shows a user dialog
            return await tcs.Task;
        }
示例#39
0
 public static void requestPurchase(Purchasable purchasable)
 {
     #if UNITY_ANDROID && !UNITY_EDITOR
     OuyaUnityPlugin.requestPurchaseAsync(purchasable.productId);
     #endif
 }