Exemple #1
0
 public PlayingReward(string playerName, string playerGroup, CurrencyDefinition currency)
 {
     PlayerName   = playerName;
     PlayerGroup  = playerGroup;
     RewardReason = RewardReason.Playing;
     Currency     = currency;
 }
Exemple #2
0
        internal static void FillCurrencyCombo(ComboBox combo)
        {
            combo.SuspendLayout();

            combo.Items.Clear();
            combo.DropDownStyle = ComboBoxStyle.DropDownList;
            combo.DisplayMember = "Description";
            combo.ValueMember   = "CurrencyId";

            var rs = APIEngine.DSOCache.CurrencyProvider.GetCurrencyActiveRS();

            while (!rs.EOF)
            {
                CurrencyDefinition currency = new CurrencyDefinition()
                {
                    CurrencyID  = (string)rs.Fields["CurrencyId"].Value,
                    Description = (string)rs.Fields["Description"].Value
                };
                combo.Items.Add(currency);
                rs.MoveNext();
            }
            rs.Close();
            rs = null;

            combo.ResumeLayout();
        }
        /// <summary>
        /// Updates all properties based on the price string. If the price string can not be parsed, the PriceInfo enters the invalid state,
        /// and all properties are set to default values.
        /// </summary>
        /// <param name="priceString">A string containing a price in value-quadrant format.</param>
        /// <param name="foldPrice">If true, the Price string will be processed further, and reformatted to use the largest quadrants possible.</param>
        /// <returns>True if succeeded, false if the PriceInfo is invalid.</returns>
        public bool SetPrice(string priceString, bool foldPrice = true)
        {
            if (!BankingPlugin.Instance.Bank.CurrencyManager.TryFindCurrencyFromString(priceString, out var currency))
            {
                Reset();
                return(false);
            }

            if (!currency.GetCurrencyConverter().TryParse(priceString, out var value))
            {
                Reset();
                return(false);
            }

            if (foldPrice)
            {
                Price = currency.GetCurrencyConverter().ToString(value);
            }
            else
            {
                Price = priceString;
            }

            Value    = value;
            Currency = currency;

            return(true);
        }
        /// <summary>
        /// Attempts to send the rewarded value as a combat text. This combat text may get concatenated with other rewards, or ignored altogether.
        /// </summary>
        /// <param name="playerName"></param>
        /// <param name="currency"></param>
        /// <param name="value"></param>
        private void trySendCombatText(string playerName, CurrencyDefinition currency, ref decimal value)
        {
            if (!currency.SendCombatText)
            {
                return;
            }

#if !DEBUG
            //dont send text for fractional values.
            if (Math.Abs(value) < 1.0m)
            {
                return;
            }
#endif

            var player = TShockAPI.Utils.Instance.FindPlayer(playerName).FirstOrDefault();

            if (player != null)
            {
                var notification = new PlayerRewardNotification()
                {
                    Player             = player,
                    Value              = value,
                    CurrencyDefinition = currency
                };

                BankingPlugin.Instance.PlayerRewardNotificationDistributor.Add(notification);
            }
        }
        /// <summary>
        /// Actions taken after a reward has been evaluted on a player.
        /// </summary>
        private void PostEvaluateReward(Reward reward, ref decimal rewardValue, CurrencyDefinition currency, string playerName)
        {
            currency.FirePreRewardEvents(reward, ref rewardValue, playerName);

            ScriptHookOnPreReward(playerName, reward, currency, ref rewardValue);

            if (TryUpdateBankAccount(playerName, currency.InternalName, ref rewardValue))
            {
                trySendCombatText(playerName, currency, ref rewardValue);
            }
        }
        /// <summary>
        /// Creates a Dictionary of the current ValueOverrides for fast access, stored in the Map property.
        /// </summary>
        public void Initialize(CurrencyDefinition currency)
        {
            var map = new Dictionary <TKey, ValueOverride <TKey> >(Count);

            foreach (var vo in this)
            {
                vo.Initialize(currency);
                map[vo.Key] = vo;
            }

            this.map = map;
        }
Exemple #7
0
        protected internal override decimal OnEvaluate(CurrencyDefinition currency)        //, IRewardModifier rewardModifier = null)
        {
            if (currency != Currency)
            {
                return(0m);
            }

            var value = currency.GetBasePlayingValue(PlayerGroup);

            value *= (decimal)currency.Multiplier;

            return(value);
        }
Exemple #8
0
        public static bool TryParseMoney(this string input, out decimal value)
        {
            CurrencyDefinition currency = null;

            if (BankingPlugin.Instance.TryGetCurrency(Config.Instance.CurrencyType, out currency))
            {
                var converter = currency.GetCurrencyConverter();
                return(converter.TryParse(input, out value));
            }

            value = 0m;
            return(false);
        }
Exemple #9
0
        public static string ToMoneyString(this decimal value)
        {
            CurrencyDefinition currency = null;

            if (BankingPlugin.Instance.TryGetCurrency(Config.Instance.CurrencyType, out currency))
            {
                var converter = currency.GetCurrencyConverter();
                return(converter.ToString(value));
            }
            else
            {
                return(value.ToString());
            }
        }
 private void ScriptHookOnPreReward(string playerName, Reward reward, CurrencyDefinition currency, ref decimal value)
 {
     try
     {
         var scriptHookOnPreReward = BankingPlugin.Instance.Bank.ScriptOnPreReward;
         if (scriptHookOnPreReward != null)
         {
             var result = scriptHookOnPreReward(playerName, reward, currency, value);
             value = result;
         }
     }
     catch (Exception ex)
     {
         BankingPlugin.Instance.LogPrint(ex.ToString(), TraceLevel.Error);
     }
 }
Exemple #11
0
        /// <summary> Called when the nfo[] edit fields should be rendered </summary>
        public override void NfoField(plyDataObject data, EditorWindow ed)
        {
            // nfo[0] = 0:Currency, 1:Item
            // nfo[1] = the identifier of the attribute or item.(not used with currency selected)
            // nfo[2] = cached name of selected attribute or item

            EditorGUI.BeginChangeCheck();
            _selected = EditorGUILayout.Popup("Reward Type", _selected, _options);
            if (EditorGUI.EndChangeCheck())
            {
                data.nfo[0] = _selected.ToString();
                data.nfo[1] = "-1";
                data.nfo[2] = "";
            }

            if (_selected == 0)
            {
                ObjectPickerUtility.RenderObjectPickerForType <CurrencyDefinition>("Currency", _selectedCurrency, (val) =>
                {
                    _selectedCurrency = val;
                });

                data.nfo[0] = "0";
                data.nfo[1] = _selectedCurrency.ToString();
                data.nfo[2] = _selectedCurrency != null ? _selectedCurrency.singleName : " (NOT FOUND)";
            }
            else if (_selected == 1)
            {
                if (GUILayout.Button("Select item"))
                {
                    //itemPicker = InventoryItemPicker.Get();
                    ObjectPickerUtility.GetObjectPickerForType <InventoryItemBase>(item =>
                    {
                        data.nfo[0]       = "1";
                        data.nfo[1]       = item.ID.ToString();
                        data.nfo[2]       = item.name;
                        _selectedCurrency = null;
                        //data.nfo[2] = item.currentStackSize.ToString();

                        ed.Repaint();
                        GUI.changed = true;
                    });
                }
            }
        }
 private void SetPriceColor(float finalPrice, CurrencyDefinition currencyDefinition)
 {
     if (action == ItemBuySellDialogAction.Buying || action == ItemBuySellDialogAction.BuyingBack)
     {
         if (InventoryManager.CanRemoveCurrency(currencyDefinition, finalPrice, true))
         {
             price.color = affordableColor;
         }
         else
         {
             price.color = unAffordableColor;
         }
     }
     else
     {
         price.color = affordableColor;
     }
 }
Exemple #13
0
        // public CurrencyDefinitionDao(IConfiguration configuration)
        // {
        //     _connectionString = configuration.GetConnectionString("defaultConnection");
        //     _connectionString = CONNECTION_STRING_POSTGRESQL;
        // }

        public List <CurrencyDefinition> getCurrencyDefinitionList()
        {
            Console.WriteLine("here");
            try
            {
                var sqls     = "Mysql";
                var response = new List <CurrencyDefinition>();
                if (sqls == "postgresql")
                {
                    var cs = CONNECTION_STRING_POSTGRESQL;
                    using var con = new NpgsqlConnection(cs);
                    con.Open();
                    var xmlquery = "SELECT * FROM currencyDefinition";
                    using var cmd   = new NpgsqlCommand();
                    cmd.Connection  = con;
                    cmd.CommandText = xmlquery;
                    NpgsqlDataReader   reader = cmd.ExecuteReader();
                    CurrencyDefinition user   = new CurrencyDefinition();
                    while (reader.Read())
                    {
                        response.Add(MapCurrencyDefValue(reader));
                        // CurrencyDefinition userViewModel = _mapper.Map<CurrencyDefinition>(reader);
                        // List<CurrencyDefinition> customers = reader.AutoMap<CurrencyDefinition>().ToList();
                    }
                    con.Close();
                }
                else
                {
                    string          MyConnection2 = ServiceNameConstants.CONNECTION_STRING_MYSQL;
                    string          Query         = "DELETE FROM testtable WHERE ID='1';";
                    MySqlConnection MyConn2       = new MySqlConnection(MyConnection2);
                    MySqlCommand    MyCommand2    = new MySqlCommand(Query, MyConn2);
                    MySqlDataReader MyReader2;
                    MyConn2.Open();
                    MyReader2 = MyCommand2.ExecuteReader();
                }
                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #14
0
        protected internal override decimal OnEvaluate(CurrencyDefinition currency)        //, IRewardModifier rewardEvaluator = null)
        {
            decimal value;

            if (RewardReason == RewardReason.Mining)
            {
                value = currency.GetBaseMiningValue(TileOrWallId, TileSubTarget, PlayerGroup);
            }
            else
            {
                value = currency.GetBasePlacingValue(TileOrWallId, TileSubTarget, PlayerGroup);
            }

            //if(rewardEvaluator!=null)
            //{
            //	value = rewardEvaluator.ModifyBaseRewardValue(RewardReason, PlayerName, currency.InternalName, Tile.type.ToString(), value);
            //}

            value *= (decimal)currency.Multiplier;

            return(value);
        }
Exemple #15
0
        /// <summary>
        /// Performs necessary initialization in order to use this ValueOverride. The base implementation attempts to parse the ValueString
        /// into a generic unit Value from the Currency. If this fails, it tries to parse a raw decimal value from the string. If this also fails,
        /// Value is left  untouched.
        /// </summary>
        /// <param name="currency">Currency this override belongs to.</param>
        public virtual void Initialize(CurrencyDefinition currency)
        {
            Debug.Assert(currency != null, "CurrencyDefinition must not be null.");

            if (string.IsNullOrWhiteSpace(ValueString))
            {
                return;
            }

            var converter = currency.GetCurrencyConverter();

            if (converter.TryParse(ValueString, out var newValue))
            {
                Value = newValue;
                return;
            }

            if (decimal.TryParse(ValueString, out newValue))
            {
                Value = newValue;
                return;
            }
        }
        protected internal override IEnumerable <Tuple <string, decimal> > OnEvaluateMultiple(CurrencyDefinition currency)    //, IRewardModifier rewardModifier = null)
        {
            if (NpcSpawnedFromStatue && !currency.EnableStatueNpcRewards)
            {
                yield break;
            }

            var npcBaseValue = currency.GetKillingValueOverride(NpcGivenOrTypeName) ?? npcHp;

            foreach (var kvp in StrikeInfo)
            {
                var playerName            = kvp.Key;
                var weaponName            = kvp.Value.WeaponName;
                var damagePercent         = kvp.Value.Damage / totalDamage;
                var damageDefendedPercent = totalDamageDefended > 0 ? kvp.Value.DamageDefended / totalDamageDefended : 0;                //avoid divide by 0

                //allow external code a chance to modify the npc's value ( ie, leveling's NpcNameToExp tables... )
                //var value = (float)rewardModifier.ModifyBaseRewardValue(RewardReason.Killing, playerName, currency.InternalName, NpcGivenOrTypeName, (decimal)NpcValue);
                //var value = NpcValue;

                var value        = npcBaseValue;
                var defenseBonus = value * (decimal)(damageDefendedPercent * currency.DefenseBonusMultiplier);

                Debug.Print($"DefenseBonus: {defenseBonus}");

                value *= (decimal)damagePercent;

                //Weapons are implicitly at 1.0, unless modifier is found.
                float weaponMultiplier = 0;
                if (weaponName != null && currency.WeaponMultipliers?.TryGetValue(weaponName, out weaponMultiplier) == true)
                {
                    value *= (decimal)weaponMultiplier;
                }

                value += defenseBonus;
                value *= (decimal)currency.Multiplier;

                yield return(new Tuple <string, decimal>(playerName, value));
            }
        }
Exemple #17
0
 protected internal override decimal OnEvaluate(CurrencyDefinition currency)        //, IRewardModifier rewardEvaluator = null)
 {
     throw new NotImplementedException();
 }
Exemple #18
0
 /// <summary>
 /// Computes a decimal value, representing the value of this reward for the given Currency. The value is in generic units, and maybe positive or negative.
 /// </summary>
 /// <param name="currency"></param>
 /// <returns>Computed value, in generic units.</returns>
 /// <remarks>Implementations do not need to use the rewardModifier, but if they do, they should guard against null values.</remarks>
 protected internal abstract decimal OnEvaluate(CurrencyDefinition currency);
 /// <summary>
 /// Resets all properties to default values, and marks the PriceInfo as invalid.
 /// </summary>
 public void Reset()
 {
     Price    = "";
     Value    = 0m;
     Currency = null;
 }
Exemple #20
0
 /// <summary>
 /// Computes an IEnumerable of Tuple's containing the player name, and reward amount, in generic units.
 /// </summary>
 /// <param name="currency"></param>
 /// <returns></returns>
 protected internal abstract IEnumerable <Tuple <string, decimal> > OnEvaluateMultiple(CurrencyDefinition currency);     //, IRewardModifier rewardModifier = null);
Exemple #21
0
        //we cant easily use bankAccount.TransferTo() here, hence why we've gone with an iterator
        protected internal override IEnumerable <Tuple <string, decimal> > OnEvaluateMultiple(CurrencyDefinition currency)    //, IRewardModifier rewardModifier = null)
        {
            var rewardAccount = BankingPlugin.Instance.Bank.GetBankAccount(PlayerName, currency.InternalName);

            if (RewardReason == RewardReason.Death)
            {
                var factor = 1.0m;                 // ( session.Class.DeathPenaltyMultiplierOverride ?? 1.0 );

                decimal loss = Math.Round(Math.Max((decimal)currency.DeathPenaltyMultiplier * factor * rewardAccount.Balance,
                                                   (decimal)currency.DeathPenaltyMinimum), 2);
                if (loss == 0.0m)
                {
                    yield break;
                }

                loss = -loss;                //this will cause a withdrawal
                yield return(new Tuple <string, decimal>(PlayerName, loss));
            }
            else             //RewardReason.DeathPvP:
            {
                //decimal value = evaluator.GetRewardValue(playerName, currency.InternalName, itemName, (decimal)defaultValue);//<---not sure how or if to slot this in.
                //decimal loss = Math.Round(Math.Max((decimal)currency.DeathPenaltyPvPMultiplier * rewardAccount.Balance, (decimal)currency.DeathPenaltyMinimum));
                decimal lossPvP = Math.Round(Math.Max((decimal)currency.DeathPenaltyPvPMultiplier * rewardAccount.Balance, (decimal)currency.DeathPenaltyMinimum), 2);

                if (lossPvP == 0.0m)
                {
                    yield break;
                }

                if (string.IsNullOrWhiteSpace(OtherPlayerName)) //no info on other guy(?)
                {
                    lossPvP = -lossPvP;                         //withdrawal
                    yield return(new Tuple <string, decimal>(PlayerName, lossPvP));
                }
                else
                {
                    //we cant easily use bankAccount.TransferTo() here, hence why we've gone with an iterator

                    lossPvP = -lossPvP;                    //withdraw from dead player's account.
                    yield return(new Tuple <string, decimal>(PlayerName, lossPvP));

                    lossPvP = -lossPvP;                    //deposit into winning player's account.
                    yield return(new Tuple <string, decimal>(OtherPlayerName, lossPvP));
                }
            }
        }
 protected internal override decimal OnEvaluate(CurrencyDefinition currency) //, IRewardModifier rewardModifier = null)
 {
     return(currency.GetBaseFishingValue(ItemId, Prefix));                   // StackSize wont work-- it will be the sum of the previous slot + new items.
 }
        private void GetTransactionInfo(int amount, out string formattedText, out float finalPrice, out CurrencyDefinition finalCurrency)
        {
            if (action == ItemBuySellDialogAction.Buying)
            {
                formattedText = inventoryItem.buyPrice.ToString(amount * vendor.buyPriceFactor);
                finalPrice    = vendor.GetBuyPrice(inventoryItem, (uint)amount);
                finalCurrency = inventoryItem.buyPrice.currency;
                return;
            }

            if (action == ItemBuySellDialogAction.Selling)
            {
                formattedText = inventoryItem.sellPrice.ToString(amount * vendor.sellPriceFactor);
                finalPrice    = vendor.GetSellPrice(inventoryItem, (uint)amount);
                finalCurrency = inventoryItem.sellPrice.currency;
                return;
            }

            if (action == ItemBuySellDialogAction.BuyingBack)
            {
                formattedText = inventoryItem.sellPrice.ToString(amount * vendor.buyBackPriceFactor);
                finalPrice    = vendor.GetBuyBackPrice(inventoryItem, (uint)amount);
                finalCurrency = inventoryItem.sellPrice.currency;
                return;
            }

            formattedText = "";
            finalPrice    = 0f;
            finalCurrency = null;
        }
Exemple #24
0
        internal static async Task <Dictionary <string, Currency> > GetCurrencies(string APIKey)
        {
            Dictionary <string, Currency> updatedList = new Dictionary <string, Currency>();

            string             WEBSERVICE_URL = string.Format("http://api.currencylayer.com/list?access_key={0}", APIKey);
            string             jsonResponse   = "";
            CurrencyDefinition cd             = new CurrencyDefinition();

            try
            {
                var webRequest = WebRequest.Create(WEBSERVICE_URL);
                if (webRequest != null)
                {
                    webRequest.Method      = "GET";
                    webRequest.Timeout     = 12000;
                    webRequest.ContentType = "application/json";


                    using (Stream s = webRequest.GetResponse().GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(s))
                        {
                            jsonResponse = sr.ReadToEnd();
                            cd           = JsonConvert.DeserializeObject <CurrencyDefinition>(jsonResponse);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}");

                await LogWriter.WriteLogFile($"{ex.StackTrace}");

                Console.WriteLine($"Exception: {ex.Message}");
            }

            WEBSERVICE_URL = string.Format("http://api.currencylayer.com/live?access_key={0}&source={1}", APIKey, "USD");
            CurrencyConversionList ccl = new CurrencyConversionList();

            try
            {
                var webRequest = WebRequest.Create(WEBSERVICE_URL);
                if (webRequest != null)
                {
                    webRequest.Method      = "GET";
                    webRequest.Timeout     = 12000;
                    webRequest.ContentType = "application/json";


                    using (Stream s = webRequest.GetResponse().GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(s))
                        {
                            jsonResponse = sr.ReadToEnd();
                            ccl          = JsonConvert.DeserializeObject <CurrencyConversionList>(jsonResponse);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}");

                await LogWriter.WriteLogFile($"{ex.StackTrace}");

                Console.WriteLine($"Exception: {ex.Message}");
            }

            foreach (string s in cd.Currencies.Keys)
            {
                updatedList.Add(s, new Currency()
                {
                    FullName = cd.Currencies[s], ValueInUSD = 0d
                });
            }

            foreach (string s in ccl.Quotes.Keys)
            {
                updatedList[s.Substring(3, 3)].ValueInUSD = ccl.Quotes[s];
            }

            return(updatedList);
        }