Get() public static method

public static Get ( GameObject localizeObject, string key ) : string
localizeObject GameObject
key string
return string
Example #1
0
    /// <summary>
    /// This function is called by the Localization manager via a broadcast SendMessage.
    /// </summary>
    void OnLocalize(Localization loc)
    {
        if (mLanguage != loc.currentLanguage)
        {
            UIWidget w = GetComponent<UIWidget>();
            UILabel lbl = w as UILabel;
            UISprite sp = w as UISprite;

            // If no localization key has been specified, use the label's text as the key
            if (string.IsNullOrEmpty(mLanguage) && string.IsNullOrEmpty(key) && lbl != null) key = lbl.text;

            // If we still don't have a key, use the widget's name
            string val = string.IsNullOrEmpty(key) ? loc.Get(w.name) : loc.Get(key);

            if (lbl != null)
            {
                lbl.text = val;
            }
            else if (sp != null)
            {
                sp.spriteName = val;
                sp.MakePixelPerfect();
            }
            mLanguage = loc.currentLanguage;
        }
    }
Example #2
0
 private void OnLocalize(Localization loc)
 {
     if (this.mLanguage != loc.currentLanguage)
     {
         UIWidget component = base.GetComponent<UIWidget>();
         UILabel uILabel = component as UILabel;
         UISprite uISprite = component as UISprite;
         if (string.IsNullOrEmpty(this.mLanguage) && string.IsNullOrEmpty(this.key) && uILabel != null)
         {
             this.key = uILabel.text;
         }
         string str = (!string.IsNullOrEmpty(this.key) ? loc.Get(this.key) : loc.Get(component.name));
         if (uILabel != null)
         {
             uILabel.text = str;
         }
         else if (uISprite != null)
         {
             uISprite.spriteName = str;
             uISprite.MakePixelPerfect();
         }
         this.mLanguage = loc.currentLanguage;
     }
 }
Example #3
0
 void OnLocalize()
 {
     this.val = Localization.Get(key);
 }
Example #4
0
    void RefreshFullEnergyAlarm()
    {
        if (!ConfigData.Instance.UseEnergyFullChargeAlarm)
        {
            return;
        }

        int not_enough_full = Network.PlayerInfo.energy_max - Network.PlayerInfo.GetEnergy();

        if (not_enough_full <= 0)
        {
            return;
        }

        UM_NotificationController.Instance.CancelLocalNotification(ConfigData.Instance.EnergyFullChargePushKey);

        int second = (GameConfig.Get <int>("energy_regen_time") * not_enough_full) - (int)(Network.Instance.ServerTime - Network.PlayerInfo.energy_time).TotalSeconds % GameConfig.Get <int>("energy_regen_time");

        ConfigData.Instance.EnergyFullChargePushKey = AddLocalNotificationBySeconds(Application.productName, Localization.Get("PushFullEnergy"), second);
    }
Example #5
0
 private void OnNotify(GameObject go)
 {
     Toast.Instance.Show(Localization.Get(10053));
 }
Example #6
0
        /// <summary>
        /// Applies random fountain effect to creature.
        /// </summary>
        /// <param name="creature"></param>
        protected virtual void Touch(Creature creature)
        {
            var rnd = RandomProvider.Get();

            // All notices are unofficial

            switch (rnd.Next(15))
            {
            case 0:                     // Full Life
            {
                creature.FullLifeHeal();
                Send.Notice(creature, Localization.Get("Full Life"));
                break;
            }

            case 1:                     // 0 Injuries
            {
                creature.Injuries = 0;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("No Injuries"));
                break;
            }

            case 2:                     // Full Stamina
            {
                creature.Stamina = creature.StaminaMax;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("Full Stamina"));
                break;
            }

            case 3:                     // Full Mana
            {
                creature.Mana = creature.ManaMax;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("Full Mana"));
                break;
            }

            case 4:                     // No Hunger
            {
                creature.Hunger = 0;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("No Hunger"));
                break;
            }

            case 5:                     // Gold
            {
                creature.GiveItem(Item.CreateGold(rnd.Next(100, 200 + 1)));
                Send.Notice(creature, Localization.Get("Gold"));
                break;
            }

            case 6:                     // Exp
            {
                creature.GiveExp(1000);
                Send.Notice(creature, Localization.Get("Exp"));
                break;
            }

            case 7:                     // Bless All
            {
                foreach (var item in creature.Inventory.GetEquipment(a => a.Info.Pocket != Pocket.Magazine1 && a.Info.Pocket != Pocket.Magazine2))
                {
                    item.OptionInfo.Flags |= ItemFlags.Blessed;
                    Send.ItemBlessed(creature, item);
                }
                Send.Notice(creature, Localization.Get("Blessed All"));
                break;
            }

            case 8:                     // Bless One
            {
                var equip = creature.Inventory.GetEquipment(a => !a.IsBlessed && a.Info.Pocket != Pocket.Magazine1 && a.Info.Pocket != Pocket.Magazine2);
                var count = equip.Count();

                if (count == 0)
                {
                    break;
                }

                var item = equip.ElementAt(rnd.Next(count));
                item.OptionInfo.Flags |= ItemFlags.Blessed;
                Send.ItemBlessed(creature, item);

                Send.Notice(creature, Localization.Get("Blessed {0}"), item.Data.Name);
                break;
            }

            case 9:                     // Repair One
            {
                var equip = creature.Inventory.GetEquipment(a => a.OptionInfo.Durability != a.OptionInfo.DurabilityMax);
                var count = equip.Count();

                if (count == 0)
                {
                    break;
                }

                var item = equip.ElementAt(rnd.Next(count));
                item.OptionInfo.Durability = item.OptionInfo.DurabilityMax;
                Send.ItemDurabilityUpdate(creature, item);

                Send.Notice(creature, Localization.Get("Repaired {0}"), item.Data.Name);
                break;
            }

            case 10:                     // No Stamina and Hungry
            {
                creature.Stamina = 0;
                creature.Hunger  = creature.StaminaMax;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("No Stamina and Hungry"));
                break;
            }

            case 11:                     // Lose one blessing
            {
                var equip = creature.Inventory.GetEquipment(a => a.IsBlessed);
                var count = equip.Count();

                if (count == 0)
                {
                    break;
                }

                var item = equip.ElementAt(rnd.Next(count));
                item.OptionInfo.Flags &= ~ItemFlags.Blessed;
                Send.ItemBlessed(creature, item);

                Send.Notice(creature, Localization.Get("Lost blessing on {0}"), item.Data.Name);
                break;
            }

            case 12:                     // No Stamina
            {
                creature.Stamina = 0;
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("No Stamina"));
                break;
            }

            case 13:                     // Random Injuries
            {
                creature.Injuries = rnd.Next((int)(creature.Life * 0.9f) + 1);
                Send.StatUpdateDefault(creature);
                Send.Notice(creature, Localization.Get("Random Injuries"));
                break;
            }

            case 14:                     // Lose one durability on random equip
            {
                var equip = creature.Inventory.GetEquipment(a => a.OptionInfo.Durability >= 1000);
                var count = equip.Count();

                if (count == 0)
                {
                    break;
                }

                var item = equip.Random();
                creature.Inventory.ReduceDurability(item, 1000);

                Send.Notice(creature, Localization.Get("Repaired {0}"), item.Data.Name);
                break;
            }
            }
        }
Example #7
0
    public override void Init()
    {
        if (!build.ads || user.revenue > 0f || ads.interstitialFrequency < 0)
        {
            adFree.SetActive(false);
        }
        else
        {
            adFree.SetActive(true);
            iTween.RotateAdd(adFree, iTween.Hash("z", 10f, "easeType", "easeInOutQuad", "loopType", "pingPong", "time", 2f));
        }

        catboxPremium.gameObject.SetActive(user.isCanGetPremiumBox && user.collection.Count > 0);
        catboxSimple.gameObject.SetActive(!user.isCanGetPremiumBox && user.isCanGetSimpleBox && user.collection.Count > 0);
        goldfishes.gameObject.SetActive(Missions.isGoldfishes);
        sausages.gameObject.SetActive(Missions.isLuckyWheel);
        hats?.gameObject.SetActive(Events.newYear.isActive && !Events.newYear.isHaveGift);
        hearts?.gameObject.SetActive(Events.stValentin.isActive && !Events.stValentin.isHaveGift);
        bats?.gameObject.SetActive(Events.halloween.isActive && !Events.halloween.isHaveGift);

        byte n = 0;

        if (catboxPremium.gameObject.activeSelf)
        {
            ++n;
        }
        if (catboxSimple.gameObject.activeSelf)
        {
            ++n;
        }
        if (goldfishes.gameObject.activeSelf)
        {
            ++n;
        }
        if (sausages.gameObject.activeSelf)
        {
            ++n;
        }
        if (hats && hats.gameObject.activeSelf)
        {
            ++n;
        }
        if (hearts && hearts.gameObject.activeSelf)
        {
            ++n;
        }
        if (bats && bats.gameObject.activeSelf)
        {
            ++n;
        }
        window.sizeDelta = new Vector2(window.sizeDelta.x, windowBaseHeight + itemHeight * n);

        catboxPremium.descriptionText.text = Localization.Get("buyCatboxPremiumDescription");
        catboxSimple.descriptionText.text  = Localization.Get("buyCatboxSimpleDescription");
        goldfishes.descriptionText.text    = Localization.Get("buyGoldfishesDescription", aquarium.SpaceFormat());
        sausages.descriptionText.text      = Localization.Get("buySausagesDescription", balance.shop.sausages);
        if (hats)
        {
            hats.descriptionText.text = Localization.Get("buyHatsDescription", balance.events.hatsPurchase);
        }
        if (hearts)
        {
            hearts.descriptionText.text = Localization.Get("buyValentinesDescription", balance.events.heartsPurchase);
        }
        if (bats)
        {
            bats.descriptionText.text = Localization.Get("buyBatsDescription", balance.events.batsPurchase);
        }

        if (!iapManager.isInitialized)
        {
            sausages.price.SetActive(false);
            goldfishes.price.SetActive(false);
            catboxPremium.price.SetActive(false);
            catboxSimple.price.SetActive(false);
            hats?.price.SetActive(false);
            hearts?.price.SetActive(false);
            bats?.price.SetActive(false);

            error.SetActive(true);
            errorText.text = Localization.Get("shopUnavalible");
            return;
        }

        sausages.priceText.text      = iapManager.sausages.priceLocalized;
        goldfishes.priceText.text    = iapManager.goldfishes.priceLocalized;
        catboxPremium.priceText.text = iapManager.catboxPremium.priceLocalized;
        catboxSimple.priceText.text  = iapManager.catboxSimple.priceLocalized;
        if (hats)
        {
            hats.priceText.text = iapManager.hats.priceLocalized;
        }
        if (hearts)
        {
            hearts.priceText.text = iapManager.valentines.priceLocalized;
        }
        if (bats)
        {
            bats.priceText.text = iapManager.bats.priceLocalized;
        }

        sausages.price.SetActive(true);
        goldfishes.price.SetActive(true);
        catboxPremium.price.SetActive(true);
        catboxSimple.price.SetActive(true);
        hats?.price.SetActive(true);
        hearts?.price.SetActive(true);
        bats?.price.SetActive(true);

        error.SetActive(false);

        catboxPremium.sale.SetActive(false);
        sausages.sale.SetActive(false);
        goldfishes.sale.SetActive(false);

        if (Events.sale.isActive)
        {
            StartCoroutine("SaleTimer");

            foreach (Dictionary <string, object> saleItem in Events.sale.data)
            {
                if (IAP.FromName((string)saleItem["iap"]) == iapManager.catboxPremium)
                {
                    catboxPremium.sale.SetActive(true);
                    catboxPremium.saleText.text = iapManager.catboxPremiumSale.priceLocalized;
                }
                else if (IAP.FromName((string)saleItem["iap"]) == iapManager.sausages)
                {
                    sausages.sale.SetActive(true);
                    sausages.saleText.text = (balance.shop.sausages * xSausages).SpaceFormat();
                }
                else if (IAP.FromName((string)saleItem["iap"]) == iapManager.goldfishes)
                {
                    goldfishes.sale.SetActive(true);
                    goldfishes.saleText.text = (aquarium * xGoldfishes).SpaceFormat();
                }
            }
        }
    }
Example #8
0
        public Radio()
        {
            this.Visible        = false;
            this.DoubleBuffered = true;

            stationPanel = new StationPanel();
            this.Panel2.Controls.Add(stationPanel);
            stationPanel.AllowDrop = true;

            instance              = this;
            scrollBar             = new QScrollBar(false);
            scrollBar.Width       = SCROLL_BAR_WIDTH;
            scrollBar.UserScroll += new QScrollBar.ScrollDelegate(scroll);
            stationPanel.Controls.Add(scrollBar);

            txtURL = new QTextBoxFocusOnClick();
            stationPanel.Controls.Add(txtURL);
            txtURL.EnableWatermark(stationPanel, Localization.Get(UI_Key.Radio_URL_Watermark), String.Empty);
            txtURL.MaxLength = 2048;
            txtURL.Enter    += (s, e) => { keyPreviewChange(); };
            txtURL.Leave    += (s, e) => { keyPreviewChange(); };
            txtURL.KeyPress += (s, e) =>
            {
                switch (e.KeyChar)
                {
                case '\r':
                    if (txtURL.Text.Length > 0)
                    {
                        go(btnGo);
                    }
                    e.Handled = true;
                    break;
                }
            };

            txtFilter = new QTextBox();
            stationPanel.Controls.Add(txtFilter);
            txtFilter.EnableWatermark(stationPanel, Localization.Get(UI_Key.Radio_Filter_Watermark), String.Empty);
            txtFilter.Enter       += (s, e) => { keyPreviewChange(); };
            txtFilter.Leave       += (s, e) => { keyPreviewChange(); };
            txtFilter.TextChanged += (s, e) => { populateStations(); };

            btnClear = new QButton("X", false, true);
            btnClear.ButtonPressed += new QButton.ButtonDelegate(clear);
            btnClear.BackColor      = stationPanel.BackColor;
            stationPanel.Controls.Add(btnClear);

            btnGo = new QButton(Localization.Get(UI_Key.Radio_Add_And_Play), false, true);
            btnGo.ButtonPressed += new QButton.ButtonDelegate(go);
            btnGo.BackColor      = stationPanel.BackColor;
            stationPanel.Controls.Add(btnGo);

            genrePanel            = new RadioGenreSelectPanel();
            genrePanel.Location   = Point.Empty;
            genrePanel.HeaderText = Localization.Get(UI_Key.Radio_Genres);
            this.Panel1.Controls.Add(genrePanel);

            cells = new List <Cell>();
            setupCells();

            this.Panel1.Resize += (s, e) => { arrangeSelectPanel(); };
            this.Panel2.Resize += (s, e) => { arrangeStationPanel(); };

            stationPanel.MouseMove        += new MouseEventHandler(stationPanelMouseMove);
            stationPanel.MouseDown        += new MouseEventHandler(stationPanelMouseDown);
            stationPanel.MouseUp          += new MouseEventHandler(stationPanelMouseUp);
            stationPanel.Paint            += new PaintEventHandler(stationPanelPaint);
            stationPanel.MouseDoubleClick += new MouseEventHandler(stationPanelDoubleClick);
            stationPanel.MouseWheel       += new MouseEventHandler(stationPanelMouseWheel);
            stationPanel.MouseEnter       += (s, e) => { if (!txtURL.Focused && !txtFilter.Focused)
                                                         {
                                                             stationPanel.Focus();
                                                         }
            };
            stationPanel.MouseLeave += (s, e) => { hoverCell = null; };
            stationPanel.Resize     += (s, e) => { setupCells(); };
            stationPanel.GotFocus   += (s, e) => { stationPanel.Active = true; keyPreviewChange(); };
            stationPanel.LostFocus  += (s, e) => { stationPanel.Active = false; };
            stationPanel.DragEnter  += (s, e) => { onDragEnter(e); };
            stationPanel.DragDrop   += (s, e) => { onDragDrop(e, true); };

            txtURL.DragEnter += (s, e) => { onDragEnter(e); };
            txtURL.DragDrop  += (s, e) => { onDragDrop(e, false); };
            txtURL.AllowDrop  = true;

            txtURL.Watermark.DragEnter += (s, e) => { onDragEnter(e); };
            txtURL.Watermark.DragDrop  += (s, e) => { onDragDrop(e, false); };
            txtURL.Watermark.AllowDrop  = true;

            genrePanel.AllowDrop             = true;
            genrePanel.SelectedIndexChanged += () => { populateStations(); };
            genrePanel.ValueChanged         += new QSelectPanel.ValueEditDelegate(selectPanel_ValueChanged);
            genrePanel.DragEnter            += (s, e) =>
            {
                onDragEnter(e);
            };
            genrePanel.DragDrop         += (s, e) => { onDragDropGenre(e); };
            this.genrePanel.MouseEnter  += (s, e) => { genrePanel.Focus(); };
            this.genrePanel.GotFocus    += (s, e) => { genrePanel.Active = true; };
            this.genrePanel.LostFocus   += (s, e) => { genrePanel.Active = false; };
            this.genrePanel.DoubleClick += (s, e) => { genreDoubleClick(); };

            int tabIndex = 0;

            txtFilter.TabIndex = tabIndex++;
            btnClear.TabIndex  = tabIndex++;
            txtURL.TabIndex    = tabIndex++;
            btnGo.TabIndex     = tabIndex++;
        }
Example #9
0
        /// <summary>
        /// Starts rest skill.
        /// </summary>
        /// <param name="creature"></param>
        /// <param name="skill"></param>
        /// <param name="dict"></param>
        /// <returns></returns>
        public override StartStopResult Start(Creature creature, Skill skill, MabiDictionary dict)
        {
            creature.StopMove();

            creature.IsInBattleStance = false;
            creature.AttemptingAttack = false;

            var chairItemEntityId = dict.GetLong("ITEMID");

            if (chairItemEntityId != 0)
            {
                this.SetUpChair(creature, chairItemEntityId);
            }
            else
            {
                // Find all nearby sittable props and sit on closest one
                var crpos = creature.GetPosition();
                var props = creature.Region.GetProps(prop => prop.HasTag("/sittable/") &&
                                                     (!prop.HasXml || prop.Xml.Attribute("SITCHAR") == null || prop.Xml.Attribute("SITCHAR").Value == "0") &&
                                                     prop.GetPosition().GetDistance(crpos) < 125);
                if (props.Count > 0)
                {
                    int nearest = 0;
                    int minDist = 125;
                    for (int i = 0; i < props.Count; i++)
                    {
                        var dist = crpos.GetDistance(props[i].GetPosition());
                        if (dist < minDist)
                        {
                            nearest = i;
                            minDist = dist;
                        }
                    }
                    this.SitOnProp(creature, props[nearest]);
                }
            }

            creature.Activate(CreatureStates.SitDown);
            if (skill.Info.Rank >= SkillRank.R9)
            {
                creature.Activate(CreatureStatesEx.RestR9);
            }

            Send.SitDown(creature);

            // Get base bonuses
            var bonusLife    = ((skill.RankData.Var1 - 100) / 100);
            var bonusStamina = ((skill.RankData.Var2 - 100) / 100);
            var bonusInjury  = skill.RankData.Var3;

            // Add bonus from campfire
            // TODO: Check for disappearing of campfire? (OnDisappears+Recheck)
            var campfires = creature.Region.GetProps(a => a.Info.Id == 203 && a.GetPosition().InRange(creature.GetPosition(), 500));

            if (campfires.Count > 0)
            {
                // Add bonus if no chair?
                if (chairItemEntityId == 0)
                {
                    // TODO: Select nearest? Random?
                    var campfire = campfires[0];

                    var multi = (campfire.Temp.CampfireSkillRank != null ? campfire.Temp.CampfireSkillRank.Var1 / 100f : 1);

                    // Add bonus for better wood.
                    // Amounts unofficial.
                    if (campfire.Temp.CampfireFirewood != null)
                    {
                        if (campfire.Temp.CampfireFirewood.HasTag("/firewood01/"))
                        {
                            multi += 0.1f;
                        }
                        else if (campfire.Temp.CampfireFirewood.HasTag("/firewood02/"))
                        {
                            multi += 0.2f;
                        }
                        else if (campfire.Temp.CampfireFirewood.HasTag("/firewood03/"))
                        {
                            multi += 0.3f;
                        }
                    }

                    // Apply multiplicator
                    bonusLife    *= multi;
                    bonusStamina *= multi;
                    bonusInjury  *= multi;
                }

                Send.Notice(creature, Localization.Get("The fire feels very warm"));
            }

            creature.Regens.Add("Rest", Stat.Life, (0.12f * bonusLife), creature.LifeMax);
            creature.Regens.Add("Rest", Stat.Stamina, (0.4f * bonusStamina), creature.StaminaMax);
            creature.Regens.Add("Rest", Stat.LifeInjured, bonusInjury, creature.LifeMax);             // TODO: Test if LifeInjured = Injuries

            if (skill.Info.Rank == SkillRank.Novice)
            {
                skill.Train(1);                                                  // Use Rest.
            }
            return(StartStopResult.Okay);
        }
Example #10
0
        /*
         * LEAGUE
         *
         *  input
         *      - list of teams (ids)
         *      - start date
         *      - weekdays available
         *          - with range of hours
         *      - days forbidden
         *      - list of play fields
         *          - with their availability
         *      - game duration (minutes)
         *      - is preview?
         *
         *  output:
         *      - a collection of days, each containing:
         *          - date
         *          - list of matches, each containing:
         *              - teams
         *              - hour
         *              - play field
         *              - status: scheduled
         *
         *  Notes:
         *      - First create a list of matches per day, then spread it in the available slots.
         *      - From the number of teams, the algorithm can predict how many slots are needed in each day
         *          (it's the same as the number of teams). This should be used in the UI to set up the
         *          calendar parameters.
         *      - To create the list of matches per day, start with the list of teams.
         *          - In the UI, allow the organizer to order them any way the want (display a message for this).
         *          - Then do every possible combination. If odd number of teams, one will be left out each round, in order.
         *      - To spread the matches in slots, randomize the list and assign to slots.
         *      - Have to consider the "home" setting of each team. Only one team should play at home, but then,
         *          what if two have then same home? no matter what, they will have to play, and their home won't
         *          change.
         *
         *  Should this be implemented in the server instead? Having this not validated on the client implies an
         *  organizer can mess the calendar. Is it possible that it can ultimately generate payments to users?
         *  In the server this could be implemented as a simple API call that calculates the preview. An argument
         *  can decide whether the generated result is just a preview or has to be commited to the DB.
         *  Since the game field availability is a lot of data that has to be queried to the database, it's
         *  benefitial to do it on the server side.
         *
         *  Test environment for this.
         */

        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="fields">List of fields, including matches already scheduled to consider in the plan</param>
        /// <returns></returns>
        public static CalendarResult Calculate(CalendarGenInput input, IList <Field> fields, string locale, TeamLocationPreferenceProviderDelegate preferenceProvider, TeamNameProvider nameProvider)
        {
            //-First create a list of matches per round, then spread it in the available slots.

            //      - From the number of teams, the algorithm can predict how many slots are needed in each round
            //          (it's the same as the number of teams). This should be used in the UI to set up the
            //            calendar parameters.
            //        -To create the list of matches per round, start with the list of teams.
            //            - In the UI, allow the organizer to order them any way the want(display a message for this).
            //            - Then apply the round robin algorithm, preserving the first entry in the list.
            //     - To spread the matches in slots, randomize each round list and assign to slots in sequence.
            //     - Have to consider the "home" setting of each team. Only one team should play at home, but then,
            //       what if two have the same home? no matter what, they will have to play, and their home won't
            //          change.

            Assert.IsNotNull(input);
            Assert.IsNotNull(input.TeamIds);
            Assert.IsNotNull(input.WeekdaySlots);
            Assert.IsNotNull(input.FieldIds);

            var result = new CalendarResult();

            if (input.TeamIds.Length <= 2)
            {
                throw new PlannerException("Error.Calendar.NotEnoughTeams");
            }

            var teams = input.TeamIds;

            var oddNumTeams = teams.Length % 2 == 1;

            if (oddNumTeams)
            {
                // Add a "free day" team (id = -1)
                Array.Resize(ref teams, teams.Length + 1);
                teams[teams.Length - 1] = -1;
            }

            var numSlotsNeededPerRound = teams.Length / 2;
            //var numFields = input.FieldIds.Length;
            //var availableTimeSlots = PlannerScheduler.GetTimeSlots(input.WeekdaySlots, input.GameDuration);
            //var availableSlots = availableTimeSlots * numFields;
            //if (availableSlots < numSlotsNeededPerRound) throw new PlannerException("Error.Calendar.NotEnoughHours");

            var matchRounds = CreateRoundRobinMatches(teams, input.NumRounds);

            string roundNameCallback(int index) => Localization.Get("Jornada {0}", locale, index);

            var locationPreferences = preferenceProvider?.Invoke(input.TeamIds);

            // Now assign matches to days. Consider field availability.
            PlannerScheduler.SpreadMatchesInCalendar(
                result,
                matchRounds,
                input.WeekdaySlots,
                input.StartDate,
                input.FieldIds,
                numSlotsNeededPerRound,
                input.GameDuration,
                input.RandomizeFields,
                input.Group,
                input.ForbiddenDays,
                locationPreferences,
                roundNameCallback);

            return(result);
        }
Example #11
0
    void RefreshFreeEnergyAlarm()
    {
        if (!ConfigData.Instance.UseFreeEnergyAlarm)
        {
            return;
        }

        //if (string.IsNullOrEmpty(ConfigData.Instance.FreeEnergyPushKey) == false)
        //{
        //    foreach (var pushkey in ConfigData.Instance.FreeEnergyPushKey.Split('|'))
        //        UM_NotificationController.Instance.CancelLocalNotification(int.Parse(pushkey));
        //    ConfigData.Instance.FreeEnergyPushKey = string.Empty;
        //}

        foreach (var info in QuestManager.Instance.Data.Where(v => v.Info.ID.Contains("BonusEnergy")))
        {
            int hour = (info.Info.Condition as QuestConditionTime).time_begin.Hours;

            int add_seconds = DateTime.Now.Hour >= hour ? (int)(DateTime.Today.AddDays(1).AddHours(hour) - DateTime.Now).TotalSeconds : (int)(DateTime.Today.AddHours(hour) - DateTime.Now).TotalSeconds;
            add_seconds += 1;

            ConfigData.Instance.FreeEnergyPushKey = ConfigData.Instance.FreeEnergyPushKey + "|" + AddLocalNotificationBySeconds(string.Format(Application.productName), string.Format(Localization.Get("PushFreeEnergy"), hour), add_seconds).ToString();
        }
    }
Example #12
0
        public static void makeSettings(UIHelperBase helper)
        {
            // tabbing code is borrowed from RushHour mod
            // https://github.com/PropaneDragon/RushHour/blob/release/RushHour/Options/OptionHandler.cs
            LoadSetting();
            UIHelper    actualHelper = helper as UIHelper;
            UIComponent container    = actualHelper.self as UIComponent;

            UITabstrip tabStrip = container.AddUIComponent <UITabstrip>();

            tabStrip.relativePosition = new Vector3(0, 0);
            tabStrip.size             = new Vector2(container.width - 20, 40);

            UITabContainer tabContainer = container.AddUIComponent <UITabContainer>();

            tabContainer.relativePosition = new Vector3(0, 40);
            tabContainer.size             = new Vector2(container.width - 20, container.height - tabStrip.height - 20);
            tabStrip.tabPages             = tabContainer;

            int tabIndex = 0;

            // Lane_ShortCut

            AddOptionTab(tabStrip, Localization.Get("Lane_ShortCut"));
            tabStrip.selectedIndex = tabIndex;

            UIPanel currentPanel = tabStrip.tabContainer.components[tabIndex] as UIPanel;

            currentPanel.autoLayout              = true;
            currentPanel.autoLayoutDirection     = LayoutDirection.Vertical;
            currentPanel.autoLayoutPadding.top   = 5;
            currentPanel.autoLayoutPadding.left  = 10;
            currentPanel.autoLayoutPadding.right = 10;

            UIHelper panelHelper = new UIHelper(currentPanel);

            var generalGroup = panelHelper.AddGroup(Localization.Get("Lane_Button_ShortCut")) as UIHelper;
            var panel        = generalGroup.self as UIPanel;

            panel.gameObject.AddComponent <OptionsKeymappingLane>();

            var generalGroup1 = panelHelper.AddGroup(Localization.Get("ShortCuts_Control")) as UIHelper;

            generalGroup1.AddCheckbox(Localization.Get("ShortCuts_Control_TIPS"), isShortCutsToPanel, (index) => isShortCutsToPanelEnable(index));

            // Function_ShortCut
            ++tabIndex;

            AddOptionTab(tabStrip, Localization.Get("Function_ShortCut"));
            tabStrip.selectedIndex = tabIndex;

            currentPanel                         = tabStrip.tabContainer.components[tabIndex] as UIPanel;
            currentPanel.autoLayout              = true;
            currentPanel.autoLayoutDirection     = LayoutDirection.Vertical;
            currentPanel.autoLayoutPadding.top   = 5;
            currentPanel.autoLayoutPadding.left  = 10;
            currentPanel.autoLayoutPadding.right = 10;

            panelHelper = new UIHelper(currentPanel);

            generalGroup = panelHelper.AddGroup(Localization.Get("Function_Button_ShortCut")) as UIHelper;
            panel        = generalGroup.self as UIPanel;

            panel.gameObject.AddComponent <OptionsKeymappingFunction>();

            ++tabIndex;

            AddOptionTab(tabStrip, Localization.Get("Experimental_Function"));
            tabStrip.selectedIndex = tabIndex;

            currentPanel                         = tabStrip.tabContainer.components[tabIndex] as UIPanel;
            currentPanel.autoLayout              = true;
            currentPanel.autoLayoutDirection     = LayoutDirection.Vertical;
            currentPanel.autoLayoutPadding.top   = 5;
            currentPanel.autoLayoutPadding.left  = 10;
            currentPanel.autoLayoutPadding.right = 10;

            panelHelper = new UIHelper(currentPanel);
            var generalGroup2 = panelHelper.AddGroup(Localization.Get("Experimental_Function")) as UIHelper;

            generalGroup2.AddCheckbox(Localization.Get("Debug_Mode"), isDebug, (index0) => isDebugEnable(index0));
            generalGroup2.AddCheckbox(Localization.Get("DisableZone"), disableZone, (index1) => isDisableZoneEnable(index1));
            generalGroup2.AddCheckbox(Localization.Get("UpdateZone"), disableZoneUpdateAll, (index2) => isDisableZoneUpdateAllEnable(index2));
            generalGroup2.AddCheckbox(Localization.Get("EnablePillar"), enablePillar, (index3) => isEnablePillarEnable(index3));
            generalGroup2.AddDropdown(Localization.Get("Lane_Smooth_Level"), new string[] { Localization.Get("Low"), Localization.Get("Medium"), Localization.Get("High") }, smoothLevel, (index4) => GetSmoothLevel(index4));
            SaveSetting();
        }
Example #13
0
    void RefreshGoodsAlarm()
    {
        if (!ConfigData.Instance.UseGoodsRefreshAlarm)
        {
            return;
        }

        //if (string.IsNullOrEmpty(ConfigData.Instance.GoodsRefreshPushKey) == false)
        //{
        //    foreach (var pushkey in ConfigData.Instance.GoodsRefreshPushKey.Split('|'))
        //        UM_NotificationController.Instance.CancelLocalNotification(int.Parse(pushkey));
        //    ConfigData.Instance.GoodsRefreshPushKey = string.Empty;
        //}

        List <short> used_hour = new List <short>();

        foreach (var store_item in StoreInfoManager.Instance.Values.Where(i => i.m_RefreshTimes != null))
        {
            foreach (var hour in store_item.m_RefreshTimes)
            {
                if (used_hour.Contains(hour) == true)
                {
                    continue;
                }
                used_hour.Add(hour);
                int add_seconds = DateTime.Now.Hour >= hour ? (int)(DateTime.Today.AddDays(1).AddHours(hour) - DateTime.Now).TotalSeconds : (int)(DateTime.Today.AddHours(hour) - DateTime.Now).TotalSeconds;
                add_seconds += 1;

                var push = AddLocalNotificationBySeconds(string.Format(Application.productName), string.Format(Localization.Get("PushGoodsRefresh"), hour), add_seconds);
                //ConfigData.Instance.GoodsRefreshPushKey = ConfigData.Instance.GoodsRefreshPushKey + "|" + push.ToString();
            }
        }
    }
Example #14
0
        /// <summary>
        /// Prepares skill, fails if no Bandage is found.
        /// </summary>
        /// <param name="creature"></param>
        /// <param name="skill"></param>
        /// <param name="packet"></param>
        /// <returns></returns>
        public bool Prepare(Creature creature, Skill skill, Packet packet)
        {
            var itemEntityId = 0L;

            if (packet.Peek() == PacketElementType.String)
            {
                itemEntityId = MabiDictionary.Fetch <long>("ITEMID", packet.GetString());
            }

            Item bandage = null;

            // Get given bandage item or select one from the inventory
            if (itemEntityId != 0)
            {
                bandage = creature.Inventory.GetItem(itemEntityId);

                if (bandage == null || !bandage.HasTag("/bandage/"))
                {
                    Log.Warning("FirstAid.Prepare: Creature '{0:X16}' tried to use invalid bandage.", creature.EntityId);
                    return(false);
                }
            }
            else
            {
                // Get all bandages in inventory
                var items = creature.Inventory.GetItems(a => a.HasTag("/bandage/"), StartAt.BottomRight);

                // Cancel if there are none
                if (items.Count == 0)
                {
                    Send.Notice(creature, Localization.Get("You need more than one Bandage."));
                    return(false);
                }

                var best = 0;

                // Select the bandage with the highest quality,
                // starting from the bottom right
                foreach (var item in items)
                {
                    var quality = 0;
                    if (item.HasTag("/common_grade/"))
                    {
                        quality = 1;
                    }
                    else if (item.HasTag("/high_grade/"))
                    {
                        quality = 2;
                    }
                    else if (item.HasTag("/highest_grade/"))
                    {
                        quality = 3;
                    }

                    // Select this item, if the quality is *better* than the
                    // previously selected one, we don't want to switch to a
                    // bandage of equal quality, since we want to get the one
                    // closest to the bottom right.
                    if (bandage == null || quality > best)
                    {
                        best    = quality;
                        bandage = item;
                    }
                }

                // Sanity check, shouldn't happen. Ever.
                if (bandage == null)
                {
                    Log.Warning("FirstAid.Prepare: The impossible sanity check failed.");
                    return(false);
                }
            }

            creature.Temp.SkillItem1 = bandage;

            Send.SkillInitEffect(creature, null);
            Send.SkillPrepare(creature, skill.Info.Id, skill.GetCastTime());

            return(true);
        }
Example #15
0
        /// <summary>
        /// Completes skill, healing the target.
        /// </summary>
        /// <param name="creature"></param>
        /// <param name="skill"></param>
        /// <param name="packet"></param>
        public void Complete(Creature creature, Skill skill, Packet packet)
        {
            var entityId = packet.GetLong();
            var unkInt1  = packet.GetInt();
            var unkInt2  = packet.GetInt();

            // Get target
            var target = ChannelServer.Instance.World.GetCreature(entityId);

            if (target == null)
            {
                Send.Notice(creature, Localization.Get("Invalid target."));
                goto L_End;
            }

            // Check range
            if (!creature.GetPosition().InRange(target.GetPosition(), Range))
            {
                Send.Notice(creature, Localization.Get("Out of range."));
                goto L_End;
            }

            // Check bandage, make sure he still has the item and that
            // it wasn't switched with something else somehow.
            if (creature.Temp.SkillItem1 == null || !creature.Temp.SkillItem1.HasTag("/bandage/") || !creature.Inventory.Has(creature.Temp.SkillItem1))
            {
                Log.Warning("FirstAid.Complete: Creature '{0:X16}' apparently switched the skill item somehow, between Ready and Complete.", creature.EntityId);
                Send.Notice(creature, Localization.Get("Invalid bandage."));
                goto L_End;
            }

            // Remove bandage
            if (!creature.Inventory.Decrement(creature.Temp.SkillItem1))
            {
                Log.Error("FirstAid.Complete: Decrementing the skill item failed somehow.");
                Send.Notice(creature, Localization.Get("Unknown error."));
                goto L_End;
            }

            // Fails if target is moving.
            if (target.IsMoving)
            {
                // Unofficial
                Send.Notice(creature, Localization.Get("Failed because target was moving."));
                // Fail motion?
                goto L_End;
            }

            // Heal injuries
            var rnd  = RandomProvider.Get();
            var heal = rnd.Next((int)skill.RankData.Var1, (int)skill.RankData.Var2 + 1);

            // Add bonus from higher grade bandages
            if (creature.Temp.SkillItem1.HasTag("/common_grade/"))
            {
                heal += 3;
            }
            else if (creature.Temp.SkillItem1.HasTag("/high_grade/"))
            {
                heal += 6;
            }
            else if (creature.Temp.SkillItem1.HasTag("/highest_grade/"))
            {
                heal += 10;
            }

            // 50% efficiency if target isn't resting
            if (!target.Has(CreatureStates.SitDown))
            {
                heal /= 2;
            }

            target.Injuries -= heal;
            Send.StatUpdateDefault(target);

            // Skill training
            if (skill.Info.Rank == SkillRank.Novice)
            {
                skill.Train(1);                 // Use First Aid.
            }
            // First Aid animation
            Send.Effect(creature, Effect.UseMagic, "healing_firstaid", entityId);

L_End:
            Send.SkillComplete(creature, skill.Info.Id, entityId, unkInt1, unkInt2);
        }
Example #16
0
 /// <summary>
 /// Sends combat message (special Chat) to creature's client.
 /// </summary>
 /// <param name="creature"></param>
 /// <param name="format"></param>
 /// <param name="args"></param>
 public static void CombatMessage(Creature creature, string format, params object[] args)
 {
     SystemMessage(creature, Localization.Get("<COMBAT>"), format, args);
 }
Example #17
0
 /// <summary>
 /// Sends server message (special Chat) to creature's client.
 /// </summary>
 /// <param name="creature"></param>
 /// <param name="format"></param>
 /// <param name="args"></param>
 public static void ServerMessage(Creature creature, string format, params object[] args)
 {
     SystemMessage(creature, Localization.Get("<SERVER>"), format, args);
 }
Example #18
0
    public static string getNationNameLong(Nationals nation)
    {
        switch (nation)
        {
        case Nationals.ALGERIA:
            return(Localization.Get("ALGERIA"));

        case Nationals.ARGENTINA:
            return(Localization.Get("ARGENTINA"));

        case Nationals.AUSTRALIA:
            return(Localization.Get("AUSTRALIA"));

        case Nationals.BELGIUM:
            return(Localization.Get("BELGIUM"));

        case Nationals.BOSNIA_AND_HERZEGOVINA:
            return(Localization.Get("BOSNIA"));

        case Nationals.BRAZIL:
            return(Localization.Get("BRAZIL"));

        case Nationals.CAMEROON:
            return(Localization.Get("CAMEROON"));

        case Nationals.CHILE:
            return(Localization.Get("CHILE"));

        case Nationals.CHINA:
            return(Localization.Get("CHINA"));

        case Nationals.COLOMBIA:
            return(Localization.Get("COLOMBIA"));

        case Nationals.COSTA_RICA:
            return(Localization.Get("COSTA RICA"));

        case Nationals.COTE_D_IVOIRE:
            return(Localization.Get("COTEDIVOIRE"));

        case Nationals.CROATIA:
            return(Localization.Get("CROATIA"));

        case Nationals.ECUADOR:
            return(Localization.Get("ECUADOR"));

        case Nationals.ENGLAND:
            return(Localization.Get("ENGLAND"));

        case Nationals.FRANCE:
            return(Localization.Get("FRANCE"));

        case Nationals.GERMANY:
            return(Localization.Get("GERMANY"));

        case Nationals.GHANA:
            return(Localization.Get("GHANA"));

        case Nationals.GREECE:
            return(Localization.Get("GREECE"));

        case Nationals.HONDURAS:
            return(Localization.Get("HONDURAS"));

        case Nationals.IRAN:
            return(Localization.Get("IRAN"));

        case Nationals.ITALY:
            return(Localization.Get("ITALY"));

        case Nationals.JAPAN:
            return(Localization.Get("JAPAN"));

        case Nationals.KOREA_REPUBLIC:
            return(Localization.Get("KOREA REPUBLIC"));

        case Nationals.MEXICO:
            return(Localization.Get("MEXICO"));

        case Nationals.MOLDOVA:
            return(Localization.Get("MOLDOVA"));

        case Nationals.NETHERLANDS:
            return(Localization.Get("NETHERLANDS"));

        case Nationals.NIGERIA:
            return(Localization.Get("NIGERIA"));

        case Nationals.PORTUGAL:
            return(Localization.Get("PORTUGAL"));

        case Nationals.RUSSIA:
            return(Localization.Get("RUSSIA"));

        case Nationals.SPAIN:
            return(Localization.Get("SPAIN"));

        case Nationals.SWEDEN:
            return(Localization.Get("SWEDEN"));

        case Nationals.SWITERLAND:
            return(Localization.Get("SWITERLAND"));

        case Nationals.TURKEY:
            return(Localization.Get("TURKEY"));

        case Nationals.URUGUAY:
            return(Localization.Get("URUGUAY"));

        case Nationals.USA:
            return(Localization.Get("USA"));

        default:
            return("ERRRROr");                                    // should never happen
        }
    }
Example #19
0
        private IEnumerator MedicineUseCoroutine()
        {
            int index = 0;

            int[] addExps = GlobalData.GetGlobalData().expSolutions;
            int   addExp  = itemId == (int)ITEM_ID.bigExpMedicine ? addExps[0] : itemId == (int)ITEM_ID.midExpMedicine ? addExps[1] : itemId == (int)ITEM_ID.smallExpMedicine ? addExps[2]:0;

            while (true)
            {
                if (_isPressUp)
                {
                    break;
                }
                _useTotalNum++;
                _itemInfo.count--;
                RefreshCount();
                if (!AutoAddExp(addExp))
                {
                    CommonAutoDestroyTipsView.Open(Localization.Get("ui.goodsJumpPathView.levelMax"));
                    break;
                }
                if (_itemInfo.count <= 0)
                {
                    CommonAutoDestroyTipsView.Open(string.Format(Localization.Get("ui.goodsJumpPathView.notEnough"), Localization.Get(_itemInfo.itemData.name)));
                    break;
                }
                if (index == 0)
                {
                    yield return(new WaitForSeconds(0.5f));
                }
                else
                {
                    yield return(new WaitForSeconds(0.15f));
                }
                index++;
            }
        }
Example #20
0
 public void AddMessage(OutputLineType type, string msg, params object[] args)
 {
     Messages.Add(new OutputLine(type, Localization.Get(msg, null, args)));
 }
Example #21
0
 public void OnPointerDown(PointerEventData data)
 {
     if (_itemInfo.count == 0)
     {
         CommonAutoDestroyTipsView.Open(string.Format(Localization.Get("ui.goodsJumpPathView.notEnough"), Localization.Get(_itemInfo.itemData.name)));
         return;
     }
     if (!AutoAddExp(0))
     {
         CommonAutoDestroyTipsView.Open(Localization.Get("ui.goodsJumpPathView.levelMax"));
         return;
     }
     _isPressUp   = false;
     _useTotalNum = 0;
     StartCoroutine(MedicineUseCoroutine());
     Debug.Log("medicine down itemid:" + itemId);
 }
Example #22
0
        void Start()
        {
            instance = this;
            Settings.Load();
            //Mods.Load(FilePaths.mods);

            List <string> localizationPaths = new List <string>();

            localizationPaths.Add(FilePaths.language);

            //foreach(Mod mod in Mods.list)
            //{
            //    localizationPaths.Add(FilePaths.mods + "/" + mod.Identifier + "/Language/{0}.ini");

            //}

            foreach (string path in localizationPaths)
            {
                Localization.Load(string.Format(path, Settings.GetString("language")));
            }


            player = GameObject.FindGameObjectWithTag("Player").GetComponent <Player>();

            confirmSelectionTextDisplay = confirmSelectionPanel.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            confirmSelectionDefaultText = Localization.Get("confirmSelectionText");
            confirmSelectionPanel.SetActive(false);

            infoTextDisplay = infoPanel.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            infoDefaultText = infoTextDisplay.text;
            infoPanel.SetActive(true);

            eventTitleDisplay      = eventPanel.transform.Find("Title").GetComponent <TextMeshProUGUI>();
            eventDefaultTitle      = eventTitleDisplay.text;
            eventTextDisplay       = eventPanel.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            eventDefaultText       = eventTextDisplay.text;
            eventButtonText        = eventPanel.transform.Find("Button").transform.Find("Text").GetComponent <TextMeshProUGUI>();
            eventButtonDefaultText = eventButtonText.text;

            creationPanelTitle        = creationPanel.transform.Find("Title").GetComponent <TextMeshProUGUI>();
            creationPanelDefaultTitle = Localization.Get("creationPanelTitle");
            creationPanelText         = creationPanel.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            creationPanelDefaultText  = Localization.Get("creationPanelText");
            creationPanelStartButton  = creationPanel.transform.Find("StartButton").GetComponent <Button>();

            // News Info Area
            newsInfoArea        = creationPanel.transform.Find("NewsInfoArea").gameObject;
            newsInfoText        = newsInfoArea.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            newsInfoDefaultText = Localization.Get("newsInfoDefaultText");

            newsNameInput = newsInfoArea.transform.Find("NewsNameInput").GetComponent <TMP_InputField>();
            newsNameInput.transform.Find("TextArea").Find("Placeholder").GetComponent <TextMeshProUGUI>().text = Localization.Get("newsFieldName");
            newsNameInputText        = newsNameInput.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            newsNameInputDefaultText = Localization.Get("newsNameInputText");

            newsAdjectiveInput = newsInfoArea.transform.Find("NewsAdjectiveInput").GetComponent <TMP_InputField>();
            newsAdjectiveInput.transform.Find("TextArea").Find("Placeholder").GetComponent <TextMeshProUGUI>().text = Localization.Get("newsFieldAdjective");
            newsAdjectiveInputText        = newsAdjectiveInput.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            newsAdjectiveInputDefaultText = Localization.Get("newsAdjectiveInputText");

            newsBeliverInput = newsInfoArea.transform.Find("NewsBeliverInput").GetComponent <TMP_InputField>();
            newsBeliverInput.transform.Find("TextArea").Find("Placeholder").GetComponent <TextMeshProUGUI>().text = Localization.Get("newsFieldBeliver");
            newsBeliverInputText        = newsBeliverInput.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            newsBeliverInputDefaultText = Localization.Get("newsBeliverInputText");

            newsDisbeliverInput = newsInfoArea.transform.Find("NewsDisbeliverInput").GetComponent <TMP_InputField>();
            newsDisbeliverInput.transform.Find("TextArea").Find("Placeholder").GetComponent <TextMeshProUGUI>().text = Localization.Get("newsFieldDisbeliver");
            newsDisbeliverInputText        = newsDisbeliverInput.transform.Find("Text").GetComponent <TextMeshProUGUI>();
            newsDisbeliverInputDefaultText = Localization.Get("newsDisbeliverInputText");

            // News Type Area
            newsTypeArea     = creationPanel.transform.Find("NewsTypeArea").gameObject;
            newsTypeText     = newsTypeArea.transform.Find("NewsTypeText").GetComponent <TextMeshProUGUI>();
            newsTypeDropdown = newsTypeArea.transform.Find("NewsTypeDropdown").GetComponent <TMP_Dropdown>();
        }
Example #23
0
    //     public List<ISkillTarget> GetTargets(bool is_team, bool ignore_distance)
    //     {
    //         return GetTargets(null, is_team, ignore_distance);
    //     }

    SkillTargetContainer GetTargets(BattleCreature self, bool is_team, bool ignore_distance, eMoveTarget move_target)
    {
        SkillTargetContainer skill_target = new SkillTargetContainer();

        skill_target.targets = new List <ISkillTarget>();

        try
        {
            switch (Info.TargetType)
            {
            case eTargetType.self:
                if (self == null)
                {
                    Debug.LogError("self is null");
                }
                skill_target.targets.Add(new SkillTarget(skill_target, this, self, 0));
                break;

            case eTargetType.position:
            case eTargetType.position_reverse:
            case eTargetType.all:
            case eTargetType.all_reverse:
            case eTargetType.all_center:
            case eTargetType.position_next:
            {
                List <ICreature> target_list = GetTargetList(is_team, Info.EnemyType);

                switch (Info.TargetType)
                {
                case eTargetType.position_reverse:
                case eTargetType.all_reverse:
                    target_list = target_list.Reverse <ICreature>().ToList();
                    break;

                case eTargetType.position_next:
                    skill_target.target_creatures = target_list;
                    break;
                }

                var main_action = Info.Actions[0];

                int selected_target_index = -1, first_target_index = -1;

                // provoke
                if (main_action.IsMultiTarget == false)
                {
                    for (int target_index = 0; target_index < target_list.Count; ++target_index)
                    {
                        var  creature = target_list[target_index] as BattleCreature;
                        Buff provoke  = creature.GetProvoke();
                        if (provoke != null)
                        {
                            int value = provoke.Value - (Level - provoke.Skill.Level) * GameConfig.Get <int>("stun_level_decrease");
                            if (BattleBase.Instance.Rand.NextRange(1, 10000) > value)
                            {
                                continue;
                            }

                            TextManager.Instance.PushMessage(creature, Localization.Get("Aggro"), eBuffColorType.Aggro, eTextPushType.Normal);
                            selected_target_index = target_index;
                            break;
                        }
                    }
                }

                if (selected_target_index == -1)
                {
                    for (int target_index = 0; target_index < target_list.Count; ++target_index)
                    {
                        BattleCreature target = target_list[target_index] as BattleCreature;
                        if (target == null || target.CanTarget() == false)
                        {
                            continue;
                        }

                        if (first_target_index == -1)
                        {
                            first_target_index = target_index;
                        }
                        if (Info.TargetType != eTargetType.all_center && Info.TargetType != eTargetType.all && Info.TargetType != eTargetType.all_reverse && main_action.CanDistance(self.Character.GetAction(Info.ActionName).Effect.GetFirstActionTime(), target) == false)
                        {
                            continue;
                        }

                        selected_target_index = target_index;
                        break;
                    }
                    if (selected_target_index == -1)
                    {
                        if (ignore_distance == true)
                        {
                            selected_target_index = first_target_index;
                        }

                        if (selected_target_index == -1)
                        {
                            return(null);
                        }
                    }
                }

                skill_target.targets.Add(new SkillTarget(skill_target, this, target_list[selected_target_index], 0));
                var value_percent = Info.Actions[0].action_value;
                for (int value_index = 1, target_index = 1; value_index < value_percent.value_percent.Length; value_index++, target_index++)
                {
                    if (value_percent.value_percent[value_index] > 0)
                    {
                        if (main_action.loop_target == true || selected_target_index + target_index < target_list.Count)
                        {
                            var target = target_list[(selected_target_index + target_index) % target_list.Count] as BattleCreature;
                            if (target == null || target.CanTarget() == false)
                            {
                                if (main_action.skip_dead)
                                {
                                    --value_index;
                                    continue;
                                }
                                skill_target.targets.Add(null);
                            }
                            else
                            {
                                skill_target.targets.Add(new SkillTarget(skill_target, this, target, value_index));
                            }
                        }
                        else
                        {
                            skill_target.targets.Add(null);
                        }
                        skill_target.targets.Add(null);
                    }
                }

                //                     if (Info.TargetType != eTargetType.all && main_action.check_distance == true && !targets.Any(t => t != null && t.Character.Creature.IsDead == false && (t.Character.transform.localPosition == Vector3.zero || ignore_distance == true)))
                //                         return null;
            }
            break;

            case eTargetType.hp_min:
            {
                List <ICreature> target_list = GetTargetList(is_team, Info.EnemyType);

                BattleCreature selected_target = null;
                foreach (BattleCreature creature in target_list)
                {
                    if (creature != null && creature.CanTarget() == true && (selected_target == null || creature.Stat.HP < selected_target.Stat.HP))
                    {
                        selected_target = creature;
                    }
                }
                skill_target.targets.Add(new SkillTarget(skill_target, this, selected_target, 0));
            }
            break;

            case eTargetType.hp_min_percent:
            {
                List <ICreature> target_list = GetTargetList(is_team, Info.EnemyType);

                BattleCreature selected_target = null;
                foreach (BattleCreature creature in target_list)
                {
                    if (creature != null && creature.CanTarget() == true && (selected_target == null || creature.Stat.HPPercent < selected_target.Stat.HPPercent))
                    {
                        selected_target = creature;
                    }
                }
                skill_target.targets.Add(new SkillTarget(skill_target, this, selected_target, 0));
            }
            break;

            case eTargetType.attack_max:
            {
                List <ICreature> target_list = GetTargetList(is_team, Info.EnemyType);

                BattleCreature selected_target = null;
                foreach (BattleCreature creature in target_list)
                {
                    if (creature != null && creature.CanTarget() == true && (selected_target == null || creature.GetDamageValue() > selected_target.GetDamageValue()))
                    {
                        selected_target = creature;
                    }
                }
                skill_target.targets.Add(new SkillTarget(skill_target, this, selected_target, 0));
            }
            break;
            }
        }
        catch (System.Exception ex)
        {
            throw new System.Exception(string.Format("[{0}] {1}", Info.ID, ex.Message), ex);
        }

        if (skill_target.main_target == null && Info.TargetType != eTargetType.position_next)
        {
            if (Info.TargetType == eTargetType.all_center)
            {
                skill_target.main_target = GetCenter(!is_team);
            }
            else
            {
                if (move_target == eMoveTarget.Character)
                {
                    skill_target.main_target = skill_target.targets[0].Character.transform;
                }
                else
                {
                    skill_target.main_target = skill_target.targets[0].Character.transform.parent;
                }
            }
        }

        return(skill_target);
    }
Example #24
0
        private void renderStation(Graphics g, Cell Cell, RadioStation Station)
        {
            if (Station != null)
            {
                string name = Station.Name;

                if (name.Length == 0)
                {
                    name = Localization.Get(UI_Key.Radio_Blank_Name);
                }

                Color c = (Station.Equals(playingStation)) ? Styles.Playing : Styles.LightText;

                if (htpcMode == HTPCMode.HTPC)
                {
                    TextRenderer.DrawText(g, name, Styles.FontHTPC, Cell.MainRectangle, c, tff);
                }
                else
                {
                    TextRenderer.DrawText(g, name, Styles.FontBold, Cell.FirstRow, c, tff);
                }

                if (this.HTPCMode == HTPCMode.Normal)
                {
                    TextRenderer.DrawText(g, Station.Genre, Styles.Font, Cell.FirstRow, Styles.LightText, tffr);

                    if (Cell.Equals(hoverCell))
                    {
                        TextRenderer.DrawText(g, Station.URL, Styles.FontItalic, Cell.SecondRow, Styles.LightText, tff);
                        if (object.Equals(Cell.Station, SelectedStation))
                        {
                            if (removeHover)
                            {
                                TextRenderer.DrawText(g, "Remove", Styles.FontUnderline, Cell.SecondRow, Styles.LightText, tffr);
                            }
                            else
                            {
                                TextRenderer.DrawText(g, "Remove", Styles.Font, Cell.SecondRow, Styles.LightText, tffr);
                            }
                        }
                        else
                        if (removeHover)
                        {
                            TextRenderer.DrawText(g, "Remove", Styles.FontUnderline, Cell.SecondRow, Styles.VeryLight, tffr);
                        }
                        else
                        {
                            TextRenderer.DrawText(g, "Remove", Styles.Font, Cell.SecondRow, Styles.Light, tffr);
                        }
                    }
                    else
                    {
                        TextRenderer.DrawText(g, Station.URL, Styles.FontItalic, Cell.SecondRow, Styles.Light, tff);
                        if (Station.BitRate > 0)
                        {
                            if (Cell.Equals(hoverCell))
                            {
                                TextRenderer.DrawText(g, Station.BitRateString, Styles.Font, Cell.SecondRow, Styles.Medium, tffr);
                            }
                            else
                            {
                                TextRenderer.DrawText(g, Station.BitRateString, Styles.Font, Cell.SecondRow, Styles.LightText, tffr);
                            }
                        }
                    }
                }
            }
        }
Example #25
0
        /// <summary>
        /// Stops Mana Deflector.
        /// </summary>
        /// <param name="creature"></param>
        /// <param name="skill"></param>
        /// <param name="dict"></param>
        /// <returns></returns>
        public override StartStopResult Stop(Creature creature, Skill skill, MabiDictionary dict)
        {
            Send.Notice(creature, Localization.Get("Mana Deflector deactivated."));

            return(StartStopResult.Okay);
        }
Example #26
0
    /// <summary>
    /// Show the popup list dialog.
    /// </summary>

    public virtual void Show()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && isValid && items.Count > 0)
        {
            mLabelList.Clear();
            StopCoroutine("CloseIfUnselected");

            // Ensure the popup's source has the selection
            UICamera.selectedObject = (UICamera.hoveredObject != null ? UICamera.hoveredObject : gameObject);
            mSelection = UICamera.selectedObject;
            source     = mSelection;

            if (source == null)
            {
                Debug.LogError("Popup list needs a source object...");
                return;
            }

            mOpenFrame = Time.frameCount;

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform);
                if (mPanel == null)
                {
                    return;
                }
            }

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Vector3 min;
            Vector3 max;

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;

            if (separatePanel)
            {
                if (GetComponent <Collider>() != null)
                {
                    Rigidbody rb = mChild.AddComponent <Rigidbody>();
                    rb.isKinematic = true;
                }
                else if (GetComponent <Collider2D>() != null)
                {
                    Rigidbody2D rb = mChild.AddComponent <Rigidbody2D>();
                    rb.isKinematic = true;
                }

                var panel = mChild.AddComponent <UIPanel>();
                panel.depth        = 1000000;
                panel.sortingOrder = mPanel.sortingOrder;
            }

            current = this;

            var       pTrans = mPanel.cachedTransform;
            Transform t      = mChild.transform;
            t.parent = pTrans;
            Transform rootTrans = pTrans;

            if (separatePanel)
            {
                var root = mPanel.GetComponentInParent <UIRoot>();
                if (root == null && UIRoot.list.Count != 0)
                {
                    root = UIRoot.list[0];
                }
                if (root != null)
                {
                    rootTrans = root.transform;
                }
            }

            // Manually triggered popup list on some other game object
            if (openOn == OpenOn.Manual && mSelection != gameObject)
            {
                startingPosition = UICamera.lastEventPosition;
                min              = pTrans.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(startingPosition));
                max              = min;
                t.localPosition  = min;
                startingPosition = t.position;
            }
            else
            {
                Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(pTrans, transform, false, false);
                min              = bounds.min;
                max              = bounds.max;
                t.localPosition  = min;
                startingPosition = t.position;
            }

            StartCoroutine("CloseIfUnselected");

            var f = fitScale;
            t.localRotation = Quaternion.identity;
            t.localScale    = new Vector3(f, f, f);

            int depth = separatePanel ? 0 : NGUITools.CalculateNextDepth(mPanel.gameObject);

            // Add a sprite for the background
            if (background2DSprite != null)
            {
                UI2DSprite sp2 = mChild.AddWidget <UI2DSprite>(depth);
                sp2.sprite2D = background2DSprite;
                mBackground  = sp2;
            }
            else if (atlas != null)
            {
                mBackground = NGUITools.AddSprite(mChild, atlas as INGUIAtlas, backgroundSprite, depth);
            }
            else
            {
                return;
            }

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer(mSelection.layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(startingPosition);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;
            mBackground.cachedTransform.localPosition = new Vector3(0f, placeAbove ? bgPadding.y * 2f - overlap : overlap, 0f);

            // Add a sprite used for the selection
            if (highlight2DSprite != null)
            {
                UI2DSprite sp2 = mChild.AddWidget <UI2DSprite>(++depth);
                sp2.sprite2D = highlight2DSprite;
                mHighlight   = sp2;
            }
            else if (atlas != null)
            {
                mHighlight = NGUITools.AddSprite(mChild, atlas as INGUIAtlas, highlightSprite, ++depth);
            }
            else
            {
                return;
            }

            float hlspHeight = 0f, hlspLeft = 0f;

            if (mHighlight.hasBorder)
            {
                hlspHeight = mHighlight.border.w;
                hlspLeft   = mHighlight.border.x;
            }

            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            float          labelHeight = activeFontSize * activeFontScale;
            float          lineHeight = labelHeight + padding.y;
            float          x = 0f, y = placeAbove ? bgPadding.y - padding.y - overlap : -padding.y - bgPadding.y + overlap;
            float          contentHeight = bgPadding.y * 2f + padding.y;
            List <UILabel> labels        = new List <UILabel>();

            // Clear the selection if it's no longer present
            if (!items.Contains(mSelectedItem))
            {
                mSelectedItem = null;
            }

            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s = items[i];

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild, mBackground.depth + 2);
                lbl.name         = i.ToString();
                lbl.pivot        = UIWidget.Pivot.TopLeft;
                lbl.font         = bitmapFont as INGUIFont;
                lbl.trueTypeFont = trueTypeFont;
                lbl.fontSize     = fontSize;
                lbl.fontStyle    = fontStyle;
                lbl.text         = isLocalized ? Localization.Get(s) : s;
                lbl.modifier     = textModifier;
                lbl.color        = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x - lbl.pivotOffset.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
                lbl.alignment      = alignment;
                lbl.symbolStyle    = NGUIText.SymbolStyle.Normal;
                labels.Add(lbl);

                contentHeight += lineHeight;

                y -= lineHeight;
                x  = Mathf.Max(x, lbl.printedSize.x);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover   = OnItemHover;
                listener.onPress   = OnItemPress;
                listener.onClick   = OnItemClick;
                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                {
                    Highlight(lbl, true);
                }

                // Add this label to the list
                mLabelList.Add(lbl);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, (max.x - min.x) - (bgPadding.x + padding.x) * 2f);

            float   cx       = x;
            Vector3 bcCenter = new Vector3(cx * 0.5f, -labelHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(cx, (labelHeight + padding.y), 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                NGUITools.AddWidgetCollider(lbl.gameObject);
                lbl.autoResizeBoxCollider = false;
                BoxCollider bc = lbl.GetComponent <BoxCollider>();

                if (bc != null)
                {
                    bcCenter.z = bc.center.z;
                    bc.center  = bcCenter;
                    bc.size    = bcSize;
                }
                else
                {
                    BoxCollider2D b2d = lbl.GetComponent <BoxCollider2D>();
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
                    b2d.center = bcCenter;
#else
                    b2d.offset = bcCenter;
#endif
                    b2d.size = bcSize;
                }
            }

            int lblWidth = Mathf.RoundToInt(x);
            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(contentHeight);

            // Set the label width to make alignment work
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                lbl.overflowMethod = UILabel.Overflow.ShrinkContent;
                lbl.width          = lblWidth;
            }

            // Scale the highlight sprite to envelop a single item

            float scaleFactor = 2f;
            var   atl         = atlas as INGUIAtlas;
            if (atl != null)
            {
                scaleFactor *= atl.pixelSize;
            }

            float w = x - (bgPadding.x + padding.x) * 2f + hlspLeft * scaleFactor;
            float h = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                AnimateColor(mBackground);

                if (Time.timeScale == 0f || Time.timeScale >= 0.1f)
                {
                    float bottom = y + labelHeight;
                    Animate(mHighlight, placeAbove, bottom);
                    for (int i = 0, imax = labels.Count; i < imax; ++i)
                    {
                        Animate(labels[i], placeAbove, bottom);
                    }
                    AnimateScale(mBackground, placeAbove, bottom);
                }
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                var bgY = bgPadding.y * f;
                min.y           = max.y - bgPadding.y * f;
                max.y           = min.y + (mBackground.height - bgPadding.y * 2f) * f;
                max.x           = min.x + mBackground.width * f;
                t.localPosition = new Vector3(min.x, max.y - bgY, min.z);
            }
            else
            {
                max.y = min.y + bgPadding.y * f;
                min.y = max.y - mBackground.height * f;
                max.x = min.x + mBackground.width * f;
            }

            var absoluteParent = mPanel;            // UIRoot.list[0].GetComponent<UIPanel>();

            for (;;)
            {
                var p = absoluteParent.parent;
                if (p == null)
                {
                    break;
                }
                var pp = p.GetComponentInParent <UIPanel>();
                if (pp == null)
                {
                    break;
                }
                absoluteParent = pp;
            }

            if (pTrans != null)
            {
                min = pTrans.TransformPoint(min);
                max = pTrans.TransformPoint(max);
                min = absoluteParent.cachedTransform.InverseTransformPoint(min);
                max = absoluteParent.cachedTransform.InverseTransformPoint(max);
                var adj = UIRoot.GetPixelSizeAdjustment(gameObject);
                min /= adj;
                max /= adj;
            }

            // Ensure that everything fits into the panel's visible range
            var offset = absoluteParent.CalculateConstrainOffset(min, max);
            var pos    = t.localPosition + offset;
            pos.x           = Mathf.Round(pos.x);
            pos.y           = Mathf.Round(pos.y);
            t.localPosition = pos;
            t.parent        = rootTrans;
        }
        else
        {
            OnSelect(false);
        }
    }
Example #27
0
 public void SetCurrentSelection()
 {
     if (UIPopupList.current != null)
     {
         this.text = ((!UIPopupList.current.isLocalized) ? UIPopupList.current.value : Localization.Get(UIPopupList.current.value));
     }
 }
Example #28
0
        /// <summary>
        /// Handles attack.
        /// </summary>
        /// <param name="attacker">The creature attacking.</param>
        /// <param name="skill">The skill being used.</param>
        /// <param name="targetEntityId">The entity id of the target.</param>
        /// <returns></returns>
        public CombatSkillResult Use(Creature attacker, Skill skill, long targetEntityId)
        {
            if (attacker.IsStunned)
            {
                return(CombatSkillResult.Okay);
            }

            var mainTarget = attacker.Region.GetCreature(targetEntityId);

            if (mainTarget == null)
            {
                return(CombatSkillResult.Okay);
            }

            if (!attacker.GetPosition().InRange(mainTarget.GetPosition(), attacker.AttackRangeFor(mainTarget)))
            {
                return(CombatSkillResult.OutOfRange);
            }

            attacker.StopMove();

            // Get targets, incl. splash.
            var targets = new HashSet <Creature>()
            {
                mainTarget
            };

            targets.UnionWith(attacker.GetTargetableCreaturesInCone(mainTarget.GetPosition(), attacker.GetTotalSplashRadius(), attacker.GetTotalSplashAngle()));

            // Counter
            if (Counterattack.Handle(targets, attacker))
            {
                return(CombatSkillResult.Okay);
            }

            var rightWeapon = attacker.Inventory.RightHand;
            var leftWeapon  = attacker.Inventory.LeftHand;
            var magazine    = attacker.Inventory.Magazine;
            var maxHits     = (byte)(attacker.IsDualWielding ? 2 : 1);
            int prevId      = 0;

            for (byte i = 1; i <= maxHits; ++i)
            {
                var weapon          = (i == 1 ? rightWeapon : leftWeapon);
                var weaponIsKnuckle = (weapon != null && weapon.Data.HasTag("/knuckle/"));

                var aAction = new AttackerAction(CombatActionType.Attacker, attacker, targetEntityId);
                aAction.Set(AttackerOptions.Result);

                if (attacker.IsDualWielding)
                {
                    aAction.Set(AttackerOptions.DualWield);
                    aAction.WeaponParameterType = (byte)(i == 1 ? 2 : 1);
                }

                var cap = new CombatActionPack(attacker, skill.Info.Id, aAction);
                cap.Hit    = i;
                cap.Type   = (attacker.IsDualWielding ? CombatActionPackType.TwinSwordAttack : CombatActionPackType.NormalAttack);
                cap.PrevId = prevId;
                prevId     = cap.Id;

                var mainDamage = (i == 1 ? attacker.GetRndRightHandDamage() : attacker.GetRndLeftHandDamage());

                foreach (var target in targets)
                {
                    if (target.IsDead)
                    {
                        continue;
                    }

                    target.StopMove();

                    var tAction = new TargetAction(CombatActionType.TakeHit, target, attacker, skill.Info.Id);
                    tAction.Set(TargetOptions.Result);
                    cap.Add(tAction);

                    // Base damage
                    var damage = mainDamage;

                    // Elementals
                    damage *= attacker.CalculateElementalDamageMultiplier(target);

                    // Splash modifier
                    if (target != mainTarget)
                    {
                        damage *= attacker.GetSplashDamage(weapon);
                    }

                    // Critical Hit
                    var critChance = (i == 1 ? attacker.GetRightCritChance(target.Protection) : attacker.GetLeftCritChance(target.Protection));
                    CriticalHit.Handle(attacker, critChance, ref damage, tAction);

                    // Subtract target def/prot
                    SkillHelper.HandleDefenseProtection(target, ref damage);

                    // Conditions
                    SkillHelper.HandleConditions(attacker, target, ref damage);

                    // Defense
                    Defense.Handle(aAction, tAction, ref damage);

                    // Mana Shield
                    ManaShield.Handle(target, ref damage, tAction);

                    // Heavy Stander
                    // Can only happen on the first hit
                    var pinged = (cap.Hit == 1 && HeavyStander.Handle(attacker, target, ref damage, tAction));

                    // Deal with it!
                    if (damage > 0)
                    {
                        target.TakeDamage(tAction.Damage = damage, attacker);
                        SkillHelper.HandleInjury(attacker, target, damage);
                    }

                    // Knock down on deadly
                    if (target.Conditions.Has(ConditionsA.Deadly))
                    {
                        tAction.Set(TargetOptions.KnockDown);
                        tAction.Stun = GetTargetStun(attacker, weapon, tAction.IsKnockBack);
                    }

                    // Aggro
                    if (target == mainTarget)
                    {
                        target.Aggro(attacker);
                    }

                    // Evaluate caused damage
                    if (!target.IsDead)
                    {
                        if (tAction.SkillId != SkillId.Defense)
                        {
                            target.Stability -= this.GetStabilityReduction(attacker, weapon) / maxHits;

                            // React normal for CombatMastery, knock down if
                            // FH and not dual wield, don't knock at all if dual.
                            if (skill.Info.Id != SkillId.FinalHit)
                            {
                                // Originally we thought you knock enemies back, unless it's a critical
                                // hit, but apparently you knock *down* under normal circumstances.
                                // More research to be done.
                                if (target.IsUnstable && target.Is(RaceStands.KnockBackable))
                                {
                                    //tAction.Set(tAction.Has(TargetOptions.Critical) ? TargetOptions.KnockDown : TargetOptions.KnockBack);
                                    tAction.Set(TargetOptions.KnockDown);
                                }
                            }
                            else if (!attacker.IsDualWielding && !weaponIsKnuckle && target.Is(RaceStands.KnockBackable))
                            {
                                target.Stability = Creature.MinStability;
                                tAction.Set(TargetOptions.KnockDown);
                            }
                        }
                    }
                    else
                    {
                        tAction.Set(TargetOptions.FinishingKnockDown);
                    }

                    // React to knock back
                    if (tAction.IsKnockBack)
                    {
                        attacker.Shove(target, KnockBackDistance);
                        if (target == mainTarget)
                        {
                            aAction.Set(AttackerOptions.KnockBackHit2);
                        }
                    }

                    // Set stun time if not defended, Defense handles the stun
                    // in case the target used it.
                    if (tAction.SkillId != SkillId.Defense)
                    {
                        if (target == mainTarget)
                        {
                            aAction.Stun = GetAttackerStun(attacker, weapon, tAction.IsKnockBack && skill.Info.Id != SkillId.FinalHit);
                        }
                        tAction.Stun = GetTargetStun(attacker, weapon, tAction.IsKnockBack);
                    }

                    if (target == mainTarget)
                    {
                        // Set increased stun if target pinged
                        if (pinged)
                        {
                            aAction.Stun = GetAttackerStun(attacker, weapon, true);
                        }

                        // Second hit doubles stun time for normal hits
                        if (cap.Hit == 2 && !tAction.IsKnockBack && !pinged)
                        {
                            aAction.Stun *= 2;
                        }

                        // Update current weapon
                        SkillHelper.UpdateWeapon(attacker, target, ProficiencyGainType.Melee, weapon);

                        // Consume stamina for weapon
                        var staminaUsage = (weapon != null ? weapon.Data.StaminaUsage : Creature.BareHandStaminaUsage);
                        if (attacker.Stamina < staminaUsage)
                        {
                            Send.Notice(attacker, Localization.Get("Your stamina is too low to fight properly!"));
                        }
                        attacker.Stamina -= staminaUsage;

                        // No second hit if defended, pinged, or knocked back
                        if (tAction.IsKnockBack || tAction.SkillId == SkillId.Defense || pinged)
                        {
                            // Set to 1 to prevent second run
                            maxHits = 1;

                            // Remove dual wield option if last hit doesn't come from
                            // the second weapon. If this isn't done, the client shows
                            // the second hit.
                            if (cap.Hit != 2)
                            {
                                aAction.Options &= ~AttackerOptions.DualWield;
                            }
                        }
                    }
                }

                // Handle
                cap.Handle();
            }

            return(CombatSkillResult.Okay);
        }
Example #29
0
        public void NpcShopBuyItem(ChannelClient client, Packet packet)
        {
            var entityId     = packet.GetLong();
            var targetPocket = packet.GetByte();    // 0:cursor, 1:inv
            var unk          = packet.GetByte();    // storage gold?

            var creature = client.GetCreatureSafe(packet.Id);

            // Check session
            // Not compatible with remote shop access, unless we bind it to NPCs.
            //client.NpcSession.EnsureValid();

            // Check open shop
            if (creature.Temp.CurrentShop == null)
            {
                throw new ModerateViolation("Tried to buy an item with a null shop.");
            }

            // Get item
            // In theory someone could buy an item without it being visible
            // to him, but he would need the current entity id that
            // changes on each restart. It's unlikely to ever be a problem.
            var item = creature.Temp.CurrentShop.GetItem(entityId);

            if (item == null)
            {
                Log.Warning("NpcShopBuyItem: Item '{0}' doesn't exist in shop.", entityId.ToString("X16"));
                goto L_Fail;
            }

            // The client expects the price for a full stack to be sent
            // in the ItemOptionInfo, so we have to calculate the actual price here.
            var price = item.OptionInfo.Price;

            if (item.Data.StackType == StackType.Stackable)
            {
                price = (int)(price / (float)item.Data.StackMax * item.Amount);
            }

            // Check gold
            if (creature.Inventory.Gold < price)
            {
                Send.MsgBox(creature, Localization.Get("Insufficient amount of gold."));
                goto L_Fail;
            }

            // Buy, adding item, and removing gold
            var success = false;

            // Cursor
            if (targetPocket == 0)
            {
                success = creature.Inventory.Add(item, Pocket.Cursor);
            }
            // Inventory
            else if (targetPocket == 1)
            {
                success = creature.Inventory.Add(item, false);
            }

            if (success)
            {
                creature.Inventory.RemoveGold(price);
                ChannelServer.Instance.Events.OnPlayerReceivesItem(creature, item.Info.Id, item.Info.Amount);
            }

            // Response
            Send.NpcShopBuyItemR(creature, success);
            return;

L_Fail:
            Send.NpcShopBuyItemR(creature, false);
        }
Example #30
0
    /// <summary>
    /// Show the popup list dialog.
    /// </summary>

    public void Show()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
        {
            mLabelList.Clear();

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform);
                if (mPanel == null)
                {
                    return;
                }
            }

            // Disable the navigation script
            handleEvents = true;

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Transform myTrans = transform;

            Vector3 min;
            Vector3 max;

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;

            Transform t = mChild.transform;
            t.parent = myTrans.parent;
            Vector3 pos;

            StopCoroutine("CloseIfUnselected");

            if (UICamera.selectedObject == null)
            {
                mSelection = gameObject;
                UICamera.selectedObject = mSelection;
            }
            else
            {
                mSelection = UICamera.selectedObject;
            }

            // Manually triggered popup list on some other game object
            if (openOn == OpenOn.Manual && mSelection != gameObject)
            {
                min             = t.parent.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(UICamera.lastTouchPosition));
                max             = min;
                t.localPosition = min;
                pos             = t.position;
            }
            else
            {
                Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans, false, false);
                min             = bounds.min;
                max             = bounds.max;
                t.localPosition = min;
                pos             = myTrans.position;
            }

            StartCoroutine("CloseIfUnselected");

            t.localRotation = Quaternion.identity;
            t.localScale    = Vector3.one;

            // Add a sprite for the background
            mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;
            mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);

            // Add a sprite used for the selection
            mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            UISpriteData hlsp = mHighlight.GetAtlasSprite();
            if (hlsp == null)
            {
                return;
            }

            float          hlspHeight = hlsp.borderTop;
            float          fontHeight = activeFontSize;
            float          dynScale = activeFontScale;
            float          labelHeight = fontHeight * dynScale;
            float          x = 0f, y = -padding.y;
            List <UILabel> labels = new List <UILabel>();

            // Clear the selection if it's no longer present
            if (!items.Contains(mSelectedItem))
            {
                mSelectedItem = null;
            }

            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s = items[i];

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild);
                lbl.name         = i.ToString();
                lbl.pivot        = UIWidget.Pivot.TopLeft;
                lbl.bitmapFont   = bitmapFont;
                lbl.trueTypeFont = trueTypeFont;
                lbl.fontSize     = fontSize;
                lbl.fontStyle    = fontStyle;
                lbl.text         = isLocalized ? Localization.Get(s) : s;
                lbl.color        = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x - lbl.pivotOffset.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
                lbl.alignment      = alignment;
                labels.Add(lbl);

                y -= labelHeight;
                y -= padding.y;
                x  = Mathf.Max(x, lbl.printedSize.x);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover   = OnItemHover;
                listener.onPress   = OnItemPress;
                listener.onClick   = OnItemClick;
                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                {
                    Highlight(lbl, true);
                }

                // Add this label to the list
                mLabelList.Add(lbl);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, (max.x - min.x) * dynScale - (bgPadding.x + padding.x) * 2f);

            float   cx       = x;
            Vector3 bcCenter = new Vector3(cx * 0.5f, -labelHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(cx, (labelHeight + padding.y), 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                NGUITools.AddWidgetCollider(lbl.gameObject);
                lbl.autoResizeBoxCollider = false;
                BoxCollider bc = lbl.GetComponent <BoxCollider>();

                if (bc != null)
                {
                    bcCenter.z = bc.center.z;
                    bc.center  = bcCenter;
                    bc.size    = bcSize;
                }
                else
                {
                    BoxCollider2D b2d = lbl.GetComponent <BoxCollider2D>();
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
                    b2d.center = bcCenter;
#else
                    b2d.offset = bcCenter;
#endif
                    b2d.size = bcSize;
                }
            }

            int lblWidth = Mathf.RoundToInt(x);
            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);

            // Set the label width to make alignment work
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                lbl.overflowMethod = UILabel.Overflow.ShrinkContent;
                lbl.width          = lblWidth;
            }

            // Scale the highlight sprite to envelop a single item
            float scaleFactor = 2f * atlas.pixelSize;
            float w           = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
            float h           = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer(mSelection.layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(pos);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                float bottom = y + labelHeight;
                Animate(mHighlight, placeAbove, bottom);
                for (int i = 0, imax = labels.Count; i < imax; ++i)
                {
                    Animate(labels[i], placeAbove, bottom);
                }
                AnimateColor(mBackground);
                AnimateScale(mBackground, placeAbove, bottom);
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                t.localPosition = new Vector3(min.x, max.y - y - bgPadding.y, min.z);
            }

            min   = t.localPosition;
            max.x = min.x + mBackground.width;
            max.y = min.y - mBackground.height;
            max.z = min.z;
            Vector3 offset = mPanel.CalculateConstrainOffset(min, max);

            pos             = t.localPosition + offset;
            pos.x           = Mathf.Round(pos.x);
            pos.y           = Mathf.Round(pos.y);
            t.localPosition = pos;
        }
        else
        {
            OnSelect(false);
        }
    }
Example #31
0
        public void NpcTalkStart(ChannelClient client, Packet packet)
        {
            var npcEntityId = packet.GetLong();

            // Check creature
            var creature = client.GetCreatureSafe(packet.Id);

            // Check lock
            if (!creature.Can(Locks.TalkToNpc))
            {
                Log.Debug("TalkToNpc locked for '{0}'.", creature.Name);
                Send.NpcTalkStartR_Fail(creature);
                return;
            }

            // Check NPC
            var target = ChannelServer.Instance.World.GetNpc(npcEntityId);

            if (target == null)
            {
                throw new ModerateViolation("Tried to talk to non-existant NPC 0x{0:X}", npcEntityId);
            }

            // Special NPC requirements
            // The Soulstream version of Nao and Tin are only available
            // in the Soulstream, and in there we can't check range.
            var bypassDistanceCheck = false;
            var disallow            = false;

            if (npcEntityId == MabiId.Nao || npcEntityId == MabiId.Tin)
            {
                bypassDistanceCheck = creature.Temp.InSoulStream;
                disallow            = !creature.Temp.InSoulStream;
            }

            // Some special NPCs require special permission.
            if (disallow)
            {
                throw new ModerateViolation("Tried to talk to NPC 0x{0:X} ({1}) without permission.", npcEntityId, target.Name);
            }

            // Check script
            if (target.ScriptType == null)
            {
                Send.NpcTalkStartR_Fail(creature);

                Log.Warning("NpcTalkStart: Creature '{0}' tried to talk to NPC '{1}', that doesn't have a script.", creature.Name, target.Name);
                return;
            }

            // Check distance
            if (!bypassDistanceCheck && (creature.RegionId != target.RegionId || target.GetPosition().GetDistance(creature.GetPosition()) > 1000))
            {
                Send.MsgBox(creature, Localization.Get("You're too far away."));
                Send.NpcTalkStartR_Fail(creature);

                Log.Warning("NpcTalkStart: Creature '{0}' tried to talk to NPC '{1}' out of range.", creature.Name, target.Name);
                return;
            }

            // Respond
            Send.NpcTalkStartR(creature, npcEntityId);

            // Start NPC dialog
            client.NpcSession.StartTalk(target, creature);
        }
Example #32
0
 /// <summary>
 /// Localize the text label.
 /// </summary>
 void OnLocalize(Localization loc)
 {
     if (isLocalized && textLabel != null && !string.IsNullOrEmpty(mSelectedItem))
     {
         textLabel.text = loc.Get(mSelectedItem);
     }
 }
Example #33
0
        public void NpcTalkEgo(ChannelClient client, Packet packet)
        {
            var egoRace = (EgoRace)packet.GetInt();

            var creature = client.GetCreatureSafe(packet.Id);

            // Stop if race is somehow invalid
            if (egoRace <= EgoRace.None || egoRace > EgoRace.CylinderF)
            {
                Log.Warning("NpcTalkEgo: Invalid ego race '{0}'.", egoRace);
                Send.ServerMessage(creature, Localization.Get("Invalid ego race."));
                Send.NpcTalkEgoR(creature, false, 0, null, null);
                return;
            }

            // Check multi-ego
            // TODO: We can implement multi-ego for the same ego race
            //   once we know how the client selects them.
            //   *Should* we implement that without proper support though?
            if (creature.Inventory.Items.Count(item => item.EgoInfo.Race == egoRace) > 1)
            {
                Send.ServerMessage(creature, Localization.Get("Multiple egos of the same type are currently not supported."));
                Send.NpcTalkEgoR(creature, false, 0, null, null);
                return;
            }

            // Get weapon by race
            var weapon = creature.Inventory.Items.FirstOrDefault(item => item.EgoInfo.Race == egoRace);

            if (weapon == null)
            {
                throw new SevereViolation("Player tried to talk to an ego he doesn't have ({0})", egoRace);
            }

            // Save reference for the NPC
            creature.Vars.Temp["ego"] = weapon;

            // Get NPC name by race
            var npcName = "ego_eiry";

            switch (egoRace)
            {
            case EgoRace.SwordM: npcName = "ego_male_sword"; break;

            case EgoRace.SwordF: npcName = "ego_female_sword"; break;

            case EgoRace.BluntM: npcName = "ego_male_blunt"; break;

            case EgoRace.BluntF: npcName = "ego_female_blunt"; break;

            case EgoRace.WandM: npcName = "ego_male_wand"; break;

            case EgoRace.WandF: npcName = "ego_female_wand"; break;

            case EgoRace.BowM: npcName = "ego_male_bow"; break;

            case EgoRace.BowF: npcName = "ego_female_bow"; break;

            case EgoRace.CylinderM: npcName = "ego_male_cylinder"; break;

            case EgoRace.CylinderF: npcName = "ego_female_cylinder"; break;
            }

            // Get display name
            var displayName = "Eiry";

            if (egoRace < EgoRace.EirySword || egoRace > EgoRace.EiryWind)
            {
                displayName = string.Format(Localization.Get("{0} of {1}"), weapon.EgoInfo.Name, creature.Name);
            }

            // Get NPC for dialog
            var npc = ChannelServer.Instance.World.GetNpc("_" + npcName);

            if (npc == null)
            {
                Log.Error("NpcTalkEgo: Ego NPC not found ({0})", npcName);
                Send.NpcTalkEgoR(creature, false, 0, null, null);
                return;
            }

            // Success
            Send.NpcTalkEgoR(creature, true, npc.EntityId, npcName, displayName);

            // Start dialog
            client.NpcSession.StartTalk(npc, creature);
        }
Example #34
0
 /// <summary>
 /// Localize the text label.
 /// </summary>
 void OnLocalize(Localization loc)
 {
     if (isLocalized && textLabel != null)
     {
         textLabel.text = loc.Get(mSelectedItem);
     }
 }
Example #35
0
 private void OnLocalize(Localization loc)
 {
     if (this.isLocalized && this.textLabel != null)
     {
         this.textLabel.text = loc.Get(this.mSelectedItem);
     }
 }