Пример #1
0
 /// <summary>
 /// Create new Commercial frame
 /// </summary>
 /// <param name="Flags">Flags of frame</param>
 /// <param name="Description">Description for current frame</param>
 /// <param name="TextEncoding">TextEncoding use for texts</param>
 /// <param name="Price">Price that payed for song</param>
 /// <param name="ValidUntil">Validation date</param>
 /// <param name="ContactURL">Contact URL to seller</param>
 /// <param name="RecievedAs">RecievedAd type</param>
 /// <param name="SellerName">SellerName</param>
 /// <param name="MIMEType">MimeType for seller Logo</param>
 /// <param name="Logo">Data Contain Seller Logo</param>
 public CommercialFrame(FrameFlags Flags, string Description,
     TextEncodings TextEncoding, Price Price , SDate ValidUntil, string ContactURL,
     RecievedAsEnum RecievedAs, string SellerName, string MIMEType, MemoryStream Logo)
     : base("COMR", Flags, Description, MIMEType, TextEncoding, Logo)
 {
     _ValidUntil = ValidUntil;
     this.ContactUrl = ContactURL;
     this.SellerName = SellerName;
     this.RecievedAs = RecievedAs;
     _Price = Price;
 }
Пример #2
0
        /// <summary>The method called after a new day starts.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void DayStarted(object sender, DayStartedEventArgs e)
        {
            // Add mod data to save file if needed
            foreach (var token in tokens)
            {
                if (!Game1.player.modData.ContainsKey($"{this.ModManifest.UniqueID}.{token}"))
                {
                    Game1.player.modData.Add($"{this.ModManifest.UniqueID}.{token}", "");
                    this.Monitor.Log($"Added save data {this.ModManifest.UniqueID}.{token}");
                }
            }

            string[] QuestsComplete = Game1.player.modData[$"{this.ModManifest.UniqueID}.QuestsCompleted"].Split('/');

            // Add recorded completed quests from mod data in save file to player data
            foreach (string questid in QuestsComplete)
            {
                if (questid != "" && ModEntry.perScreen.Value.QuestsCompleted.Contains(int.Parse(questid)) == false)
                {
                    ModEntry.perScreen.Value.QuestsCompleted.Add(int.Parse(questid));
                }
            }

            ModEntry.perScreen.Value.DeepestMineLevel  = Game1.player.deepestMineLevel;
            ModEntry.perScreen.Value.DeathCountMarried = Game1.player.modData[$"{this.ModManifest.UniqueID}.DeathCountMarried"] != ""
                ? int.Parse(Game1.player.modData[$"{this.ModManifest.UniqueID}.DeathCountMarried"])
                : 0;
            ModEntry.perScreen.Value.PassOutCount = Game1.player.modData[$"{this.ModManifest.UniqueID}.PassOutCount"] != ""
                ? int.Parse(Game1.player.modData[$"{this.ModManifest.UniqueID}.PassOutCount"])
                : 0;

            // Reset booleans for new day
            DeathAndExhaustionTokens.updatepassout = true;
            DeathAndExhaustionTokens.updatedeath   = true;
            this.Monitor.Log($"Trackers set to update");

            // Get days married
            int   DaysMarried = Game1.player.GetDaysMarried();
            float Years       = DaysMarried / 112;
            // Get years married
            double YearsMarried = Math.Floor(Years);
            // Get Anniversary date
            var anniversary = SDate.Now().AddDays(-(DaysMarried - 1));

            // Set tokens for the start of the day
            ModEntry.perScreen.Value.CurrentYearsMarried = Game1.player.isMarried() == true ? YearsMarried : 0;

            ModEntry.perScreen.Value.AnniversarySeason = Game1.player.isMarried() == true ? anniversary.Season : "No season";

            ModEntry.perScreen.Value.AnniversaryDay = Game1.player.isMarried() == true ? anniversary.Day : 0;

            // Test if player is married
            if (Game1.player.isMarried() is false)
            {
                // No, relevant trackers will use their default values

                this.Monitor.Log($"{Game1.player.Name} is not married");

                if (config.ResetDeathCountMarriedWhenDivorced == true && ModEntry.perScreen.Value.DeathCountMarried != 0)
                {
                    // Reset tracker if player is no longer married
                    ModEntry.perScreen.Value.DeathCountMarried = 0;
                }
            }

            // Yes, tokens exist
            else
            {
                this.Monitor.Log($"{Game1.player.Name} has been married for {YearsMarried} year(s)");

                this.Monitor.Log($"Anniversary is the {anniversary.Day} of {anniversary.Season}");
            }
        }
Пример #3
0
 public static void SetDayParticipatedContest(this Character character, SDate value)
 {
     SetKey(character, DayParticipatedContestKey, value);
 }
Пример #4
0
 public void Constructor_RejectsInvalidValues(int day, string season, int year)
 {
     // act & assert
     Assert.Throws <ArgumentException>(() => _ = new SDate(day, season, year), "Constructing the invalid date didn't throw the expected exception.");
 }
Пример #5
0
 private static int GetEventId(SDate date)
 {
     return(Convert.ToInt32($"6572{date.Year:00}{Utility.getSeasonNumber(date.Season)}{date.Day:00}"));
 }
Пример #6
0
 ["Seasons"] = (valueToCheck, _) => valueToCheck.ToLower().Split(' ').Any(s => s == SDate.Now().Season),
Пример #7
0
        private void SetPage(int newPage) //This creates new pages or sends you to a page
        {
            if (!this.diaryData.ContainsKey(currentDate.ToString()) && currentDate == SDate.Now())
            {
                this.diaryData.Add(currentDate.ToString(), new List <string> {
                    "",
                });
            }
            // set page number
            this.currentPage = Math.Max(0, newPage);

            // get current page
            while (!this.diaryData.ContainsKey(currentDate.ToString()))
            {
                if (dateDown == true)
                {
                    currentDate = this.currentDate.AddDays(-1);
                }
                if (dateUp == true)
                {
                    currentDate = this.currentDate.AddDays(1);
                }
            }

            if (this.diaryData.ContainsKey(currentDate.ToString()))
            {
                dateDown = false;
                dateUp   = false;
            }
            List <string> pages = this.diaryData[currentDate.ToString()];

            if (this.currentPage >= pages.Count)
            {
                pages.Add("");
            }
            string pageText = pages[this.currentPage];

            // update display text
            this.displayedText.Text = pageText;
        }
Пример #8
0
        /// <summary>Get the data to display for this subject.</summary>
        /// <param name="metadata">Provides metadata that's not available from the game data directly.</param>
        public override IEnumerable <ICustomField> GetData(Metadata metadata)
        {
            // get data
            Item    item       = this.Target;
            SObject obj        = item as SObject;
            bool    isObject   = obj != null;
            bool    isCrop     = this.FromCrop != null;
            bool    isSeed     = this.SeedForCrop != null;
            bool    isDeadCrop = this.FromCrop?.dead.Value == true;
            bool    canSell    = obj?.canBeShipped() == true || metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category));

            // get overrides
            bool showInventoryFields = true;

            {
                ObjectData objData = metadata.GetObject(item, this.Context);
                if (objData != null)
                {
                    this.Name = objData.NameKey != null?this.Translate(objData.NameKey) : this.Name;

                    this.Description = objData.DescriptionKey != null?this.Translate(objData.DescriptionKey) : this.Description;

                    this.Type = objData.TypeKey != null?this.Translate(objData.TypeKey) : this.Type;

                    showInventoryFields = objData.ShowInventoryFields ?? true;
                }
            }

            // don't show data for dead crop
            if (isDeadCrop)
            {
                yield return(new GenericField(this.Translate(L10n.Crop.Summary), this.Translate(L10n.Crop.SummaryDead)));

                yield break;
            }

            // crop fields
            if (isCrop || isSeed)
            {
                // get crop
                Crop crop = this.FromCrop ?? this.SeedForCrop;

                // get harvest schedule
                int  harvestablePhase   = crop.phaseDays.Count - 1;
                bool canHarvestNow      = (crop.currentPhase.Value >= harvestablePhase) && (!crop.fullyGrown.Value || crop.dayOfCurrentPhase.Value <= 0);
                int  daysToFirstHarvest = crop.phaseDays.Take(crop.phaseDays.Count - 1).Sum(); // ignore harvestable phase

                // add next-harvest field
                if (isCrop)
                {
                    // calculate next harvest
                    int   daysToNextHarvest = 0;
                    SDate dayOfNextHarvest  = null;
                    if (!canHarvestNow)
                    {
                        // calculate days until next harvest
                        int daysUntilLastPhase = daysToFirstHarvest - crop.dayOfCurrentPhase.Value - crop.phaseDays.Take(crop.currentPhase.Value).Sum();
                        {
                            // growing: days until next harvest
                            if (!crop.fullyGrown.Value)
                            {
                                daysToNextHarvest = daysUntilLastPhase;
                            }

                            // regrowable crop harvested today
                            else if (crop.dayOfCurrentPhase.Value >= crop.regrowAfterHarvest.Value)
                            {
                                daysToNextHarvest = crop.regrowAfterHarvest.Value;
                            }

                            // regrowable crop
                            else
                            {
                                daysToNextHarvest = crop.dayOfCurrentPhase.Value; // dayOfCurrentPhase decreases to 0 when fully grown, where <=0 is harvestable
                            }
                        }
                        dayOfNextHarvest = SDate.Now().AddDays(daysToNextHarvest);
                    }

                    // generate field
                    string summary;
                    if (canHarvestNow)
                    {
                        summary = this.Translate(L10n.Crop.HarvestNow);
                    }
                    else if (Game1.currentLocation.Name != Constant.LocationNames.Greenhouse && !crop.seasonsToGrowIn.Contains(dayOfNextHarvest.Season))
                    {
                        summary = this.Translate(L10n.Crop.HarvestTooLate, new { date = this.Stringify(dayOfNextHarvest) });
                    }
                    else
                    {
                        summary = $"{this.Stringify(dayOfNextHarvest)} ({this.Text.GetPlural(daysToNextHarvest, L10n.Generic.Tomorrow, L10n.Generic.InXDays).Tokens(new { count = daysToNextHarvest })})";
                    }

                    yield return(new GenericField(this.Translate(L10n.Crop.Harvest), summary));
                }

                // crop summary
                {
                    List <string> summary = new List <string>();

                    // harvest
                    summary.Add(crop.regrowAfterHarvest.Value == -1
                        ? this.Translate(L10n.Crop.SummaryHarvestOnce, new { daysToFirstHarvest = daysToFirstHarvest })
                        : this.Translate(L10n.Crop.SummaryHarvestMulti, new { daysToFirstHarvest = daysToFirstHarvest, daysToNextHarvests = crop.regrowAfterHarvest })
                                );

                    // seasons
                    summary.Add(this.Translate(L10n.Crop.SummarySeasons, new { seasons = string.Join(", ", this.Text.GetSeasonNames(crop.seasonsToGrowIn)) }));

                    // drops
                    if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0)
                    {
                        summary.Add(this.Translate(L10n.Crop.SummaryDropsXToY, new { min = crop.minHarvest, max = crop.maxHarvest, percent = Math.Round(crop.chanceForExtraCrops.Value * 100, 2) }));
                    }
                    else if (crop.minHarvest.Value > 1)
                    {
                        summary.Add(this.Translate(L10n.Crop.SummaryDropsX, new { count = crop.minHarvest }));
                    }

                    // crop sale price
                    Item drop = GameHelper.GetObjectBySpriteIndex(crop.indexOfHarvest.Value);
                    summary.Add(this.Translate(L10n.Crop.SummarySellsFor, new { price = GenericField.GetSaleValueString(this.GetSaleValue(drop, false, metadata), 1, this.Text) }));

                    // generate field
                    yield return(new GenericField(this.Translate(L10n.Crop.Summary), "-" + string.Join($"{Environment.NewLine}-", summary)));
                }
            }

            // crafting
            if (obj?.heldObject?.Value != null)
            {
                if (obj is Cask cask)
                {
                    // get cask data
                    SObject     agingObj       = cask.heldObject.Value;
                    ItemQuality curQuality     = (ItemQuality)agingObj.Quality;
                    string      curQualityName = this.Translate(L10n.For(curQuality));

                    // calculate aging schedule
                    float effectiveAge = metadata.Constants.CaskAgeSchedule.Values.Max() - cask.daysToMature.Value;
                    var   schedule     =
                        (
                            from entry in metadata.Constants.CaskAgeSchedule
                            let quality = entry.Key
                                          let baseDays = entry.Value
                                                         where baseDays > effectiveAge
                                                         orderby baseDays ascending
                                                         let daysLeft = (int)Math.Ceiling((baseDays - effectiveAge) / cask.agingRate.Value)
                                                                        select new
                    {
                        Quality = quality,
                        DaysLeft = daysLeft,
                        HarvestDate = SDate.Now().AddDays(daysLeft)
                    }
                        )
                        .ToArray();

                    // display fields
                    yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value));

                    if (cask.MinutesUntilReady <= 0 || !schedule.Any())
                    {
                        yield return(new GenericField(this.Translate(L10n.Item.CaskSchedule), this.Translate(L10n.Item.CaskScheduleNow, new { quality = curQualityName })));
                    }
                    else
                    {
                        string scheduleStr = string.Join(Environment.NewLine, (
                                                             from entry in schedule
                                                             let tokens = new { quality = this.Translate(L10n.For(entry.Quality)), count = entry.DaysLeft, date = entry.HarvestDate }
                                                             let str = this.Text.GetPlural(entry.DaysLeft, L10n.Item.CaskScheduleTomorrow, L10n.Item.CaskScheduleInXDays).Tokens(tokens)
                                                                       select $"-{str}"
                                                             ));
                        yield return(new GenericField(this.Translate(L10n.Item.CaskSchedule), this.Translate(L10n.Item.CaskSchedulePartial, new { quality = curQualityName }) + Environment.NewLine + scheduleStr));
                    }
                }
                else if (obj is Furniture)
                {
                    string summary = this.Translate(L10n.Item.ContentsPlaced, new { name = obj.heldObject.Value.DisplayName });
                    yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value, summary));
                }
                else if (obj.ParentSheetIndex == Constant.ObjectIndexes.AutoGrabber)
                {
                    string readyText = this.Text.Stringify(obj.heldObject.Value is Chest output && output.items.Any());
                    yield return(new GenericField(this.Translate(L10n.Item.Contents), readyText));
                }
                else
                {
                    string summary = obj.MinutesUntilReady <= 0
                        ? this.Translate(L10n.Item.ContentsReady, new { name = obj.heldObject.Value.DisplayName })
                        : this.Translate(L10n.Item.ContentsPartial, new { name = obj.heldObject.Value.DisplayName, time = this.Stringify(TimeSpan.FromMinutes(obj.MinutesUntilReady)) });
                    yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value, summary));
                }
            }

            // item
            if (showInventoryFields)
            {
                // needed for
                {
                    List <string> neededFor = new List <string>();

                    // bundles
                    if (isObject)
                    {
                        string[] bundles = (
                            from bundle in this.GetUnfinishedBundles(obj)
                            orderby bundle.Area, bundle.DisplayName
                            let countNeeded = this.GetIngredientCountNeeded(bundle, obj)
                                              select countNeeded > 1
                                ? $"{this.GetTranslatedBundleArea(bundle)}: {bundle.DisplayName} x {countNeeded}"
                                : $"{this.GetTranslatedBundleArea(bundle)}: {bundle.DisplayName}"
                            ).ToArray();
                        if (bundles.Any())
                        {
                            neededFor.Add(this.Translate(L10n.Item.NeededForCommunityCenter, new { bundles = string.Join(", ", bundles) }));
                        }
                    }

                    // polyculture achievement
                    if (isObject && metadata.Constants.PolycultureCrops.Contains(obj.ParentSheetIndex))
                    {
                        int needed = metadata.Constants.PolycultureCount - GameHelper.GetShipped(obj.ParentSheetIndex);
                        if (needed > 0)
                        {
                            neededFor.Add(this.Translate(L10n.Item.NeededForPolyculture, new { count = needed }));
                        }
                    }

                    // full shipment achievement
                    if (isObject && GameHelper.GetFullShipmentAchievementItems().Any(p => p.Key == obj.ParentSheetIndex && !p.Value))
                    {
                        neededFor.Add(this.Translate(L10n.Item.NeededForFullShipment));
                    }

                    // a full collection achievement
                    LibraryMuseum museum = Game1.locations.OfType <LibraryMuseum>().FirstOrDefault();
                    if (museum != null && museum.isItemSuitableForDonation(obj))
                    {
                        neededFor.Add(this.Translate(L10n.Item.NeededForFullCollection));
                    }

                    // yield
                    if (neededFor.Any())
                    {
                        yield return(new GenericField(this.Translate(L10n.Item.NeededFor), string.Join(", ", neededFor)));
                    }
                }

                // sale data
                if (canSell && !isCrop)
                {
                    // sale price
                    string saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality, metadata), item.Stack, this.Text);
                    yield return(new GenericField(this.Translate(L10n.Item.SellsFor), saleValueSummary));

                    // sell to
                    List <string> buyers = new List <string>();
                    if (obj?.canBeShipped() == true)
                    {
                        buyers.Add(this.Translate(L10n.Item.SellsToShippingBox));
                    }
                    buyers.AddRange(
                        from shop in metadata.Shops
                        where shop.BuysCategories.Contains(item.Category)
                        let name = this.Translate(shop.DisplayKey).ToString()
                                   orderby name
                                   select name
                        );
                    yield return(new GenericField(this.Translate(L10n.Item.SellsTo), string.Join(", ", buyers)));
                }

                // gift tastes
                var giftTastes = this.GetGiftTastes(item, metadata);
                yield return(new ItemGiftTastesField(this.Translate(L10n.Item.LovesThis), giftTastes, GiftTaste.Love));

                yield return(new ItemGiftTastesField(this.Translate(L10n.Item.LikesThis), giftTastes, GiftTaste.Like));
            }

            // fence
            if (item is Fence fence)
            {
                string healthLabel = this.Translate(L10n.Item.FenceHealth);

                // health
                if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock))
                {
                    yield return(new GenericField(healthLabel, this.Translate(L10n.Item.FenceHealthGoldClock)));
                }
                else
                {
                    float  maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value;
                    float  health    = fence.health.Value / maxHealth;
                    double daysLeft  = Math.Round(fence.health.Value * metadata.Constants.FenceDecayRate / 60 / 24);
                    double percent   = Math.Round(health * 100);
                    yield return(new PercentageBarField(healthLabel, (int)fence.health.Value, (int)maxHealth, Color.Green, Color.Red, this.Translate(L10n.Item.FenceHealthSummary, new { percent = percent, count = daysLeft })));
                }
            }

            // recipes
            if (item.GetSpriteType() == ItemSpriteType.Object)
            {
                RecipeModel[] recipes = GameHelper.GetRecipesForIngredient(this.DisplayItem).ToArray();
                if (recipes.Any())
                {
                    yield return(new RecipesForIngredientField(this.Translate(L10n.Item.Recipes), item, recipes, this.Text));
                }
            }

            // owned
            if (showInventoryFields && !isCrop && !(item is Tool))
            {
                yield return(new GenericField(this.Translate(L10n.Item.Owned), this.Translate(L10n.Item.OwnedSummary, new { count = GameHelper.CountOwnedItems(item) })));
            }

            // see also crop
            bool seeAlsoCrop =
                isSeed &&
                item.ParentSheetIndex != this.SeedForCrop.indexOfHarvest.Value && // skip seeds which produce themselves (e.g. coffee beans)
                !(item.ParentSheetIndex >= 495 && item.ParentSheetIndex <= 497) && // skip random seasonal seeds
                item.ParentSheetIndex != 770;    // skip mixed seeds

            if (seeAlsoCrop)
            {
                Item drop = GameHelper.GetObjectBySpriteIndex(this.SeedForCrop.indexOfHarvest.Value);
                yield return(new LinkField(this.Translate(L10n.Item.SeeAlso), drop.DisplayName, () => new ItemSubject(this.Text, drop, ObjectContext.Inventory, false, this.SeedForCrop)));
            }
        }
Пример #9
0
        internal string GenerateMenuPopup(WeatherConditions Current, string MoonPhase = "", string NightTime = "")
        {
            string text;

            if (SDate.Now().Season == "spring" && SDate.Now().Day == 1)
            {
                text = Translator.Get("weather-menu.openingS1D1", new { descDay = Translator.Get($"date{UpperSeason(SDate.Now().Season)}{SDate.Now().Day}") }) + Environment.NewLine + Environment.NewLine;
            }
            else if (SDate.Now().Season == "winter" && SDate.Now().Day == 28)
            {
                text = Translator.Get("weather-menu.openingS4D28", new { descDay = Translator.Get($"date{UpperSeason(SDate.Now().Season)}{SDate.Now().Day}") }) + Environment.NewLine + Environment.NewLine;
            }
            else
            {
                text = Translator.Get("weather-menu.opening", new { descDay = Translator.Get($"date{UpperSeason(SDate.Now().Season)}{SDate.Now().Day}") }) + Environment.NewLine + Environment.NewLine;
            }

            if (Current.ContainsCondition(CurrentWeather.Sandstorm))
            {
                text += Translator.Get("weather-menu.condition.sandstorm") + Environment.NewLine;
            }

            if (Current.ContainsCondition(CurrentWeather.Heatwave))
            {
                text += Translator.Get("weather-menu.condition.heatwave") + Environment.NewLine;
            }

            if (Current.ContainsCondition(CurrentWeather.Frost))
            {
                text += Translator.Get("weather-menu.condition.frost") + Environment.NewLine;
            }

            if (Current.ContainsCondition(CurrentWeather.WhiteOut))
            {
                text += Translator.Get("weather-menu.condition.whiteOut") + Environment.NewLine;
            }

            if (Current.ContainsCondition(CurrentWeather.ThunderFrenzy))
            {
                text += Translator.Get("weather-menu.condition.thunderFrenzy") + Environment.NewLine;
            }

            if (Current.IsVariableRain)
            {
                switch (WeatherUtilities.GetRainCategory(Current.AmtOfRainDrops))
                {
                case RainLevels.Severe:
                    text += Translator.Get("weather-condition.vrain.severe_sw") + Environment.NewLine;
                    break;

                case RainLevels.Torrential:
                    text += Translator.Get("weather-condition.vrain.torrential_sw") + Environment.NewLine;
                    break;

                case RainLevels.Typhoon:
                    text += Translator.Get("weather-condition.vrain.typhoon_sw") + Environment.NewLine;
                    break;

                case RainLevels.NoahsFlood:
                    text += Translator.Get("weather-condition.vrain.godswrath_sw") + Environment.NewLine;
                    break;

                default:
                    break;
                }
            }

            if (MoonPhase == "Blood Moon")
            {
                text += Translator.Get("weather-menu.condition.bloodmoon") + Environment.NewLine;
            }

            if (ClimatesOfFerngill.UseLunarDisturbancesApi && ClimatesOfFerngill.MoonAPI.IsSolarEclipse())
            {
                text += Translator.Get("weather-menu.condition.solareclipse") + Environment.NewLine;
            }

            ISDVWeather CurrentFog = Current.GetWeatherMatchingType("Fog").First();
            string      fogString  = "";

            //  If the fog is visible, we don't need to display fog information. However, if it's in the morning,
            //    and we know evening fog is likely, we should display the message it's expected
            // That said, if it's not, we need to pull the fog information down, assuming it's been reset. This checks that the fog end
            //    time is *before* now. To avoid nested trinary statements..
            if (SDVTime.CurrentTime < CurrentFog.WeatherExpirationTime && Current.GenerateEveningFog && CurrentFog.WeatherBeginTime < new SDVTime(1200))
            {
                fogString = Translator.Get("weather-menu.expectedFog");
            }
            if (CurrentFog.WeatherBeginTime > SDVTime.CurrentTime && Current.GenerateEveningFog)
            {
                fogString = Translator.Get("weather-menu.fogFuture",
                                           new
                {
                    fogTime = CurrentFog.WeatherBeginTime.ToString(),
                    endFog  = CurrentFog.WeatherExpirationTime.ToString()
                });
            }

            //Current Conditions.
            string currentMenu;

            if (Current.HasWeather(CurrentWeather.Rain) && Current.IsVariableRain)
            {
                currentMenu = "weather-menu.currentRainfall";
            }
            else
            {
                currentMenu = "weather-menu.current";
            }

            text += Translator.Get(currentMenu, new
            {
                todayCondition = Current.HasWeather(CurrentWeather.Fog)
                                        ? Translator.Get("weather-menu.fog", new { condition = GetBasicWeather(Current), fogTime = CurrentFog.IsWeatherVisible
                                                ? CurrentFog.WeatherExpirationTime.ToString()
                                                : "" })
                                        : GetBasicWeather(Current),
                tempString      = GetTemperatureString(Current.GetCurrentTemperature(Game1.timeOfDay)),
                todayHigh       = GetTemperatureString(Current.TodayHigh),
                todayLow        = GetTemperatureString(Current.TodayLow),
                currentRainfall = WeatherUtilities.GetRainfallAmt(Current.AmtOfRainDrops).ToString("N2"),
                fogString
            }) + Environment.NewLine;

            //Tomorrow weather
            text += Translator.Get("weather-menu.tomorrow",
                                   new {
                tomorrowCondition = GetBasicWeather(Game1.weatherForTomorrow),
                tomorrowLow       = GetTemperatureString(Current.TomorrowLow),
                tomorrowHigh      = GetTemperatureString(Current.TomorrowHigh)
            }) + Environment.NewLine;

            //now, night time
            if (!String.IsNullOrEmpty(NightTime))
            {
                text += NightTime + Environment.NewLine;
            }

            if (ClimatesOfFerngill.UseLunarDisturbancesApi)
            {
                if (ClimatesOfFerngill.MoonAPI.IsMoonUp(Game1.timeOfDay))
                {
                    text += Translator.Get("weather-menu.desc-moonNotUp", new { moonPhase = ClimatesOfFerngill.MoonAPI.GetCurrentMoonPhase(), moonRise = ClimatesOfFerngill.MoonAPI.GetMoonRise(), moonSet = ClimatesOfFerngill.MoonAPI.GetMoonSet() });
                }
                else
                {
                    text += Translator.Get("weather-menu.desc-moonUp", new { moonPhase = ClimatesOfFerngill.MoonAPI.GetCurrentMoonPhase(), moonSet = ClimatesOfFerngill.MoonAPI.GetMoonSet() });
                }
            }

            return(text);
        }
Пример #10
0
        /// <summary>Get the custom fields for a crop.</summary>
        /// <param name="dirt">The dirt the crop is planted in, if applicable.</param>
        /// <param name="crop">The crop to represent.</param>
        /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param>
        private IEnumerable <ICustomField> GetCropFields(HoeDirt dirt, Crop crop, bool isSeed)
        {
            if (crop == null)
            {
                yield break;
            }

            var  data     = new CropDataParser(crop, isPlanted: !isSeed);
            bool isForage = crop.whichForageCrop.Value > 0 && crop.fullyGrown.Value; // show crop fields for growing mixed seeds

            // add next-harvest field
            if (!isSeed)
            {
                // get next harvest
                SDate nextHarvest = data.GetNextHarvest();

                // generate field
                string summary;
                if (data.CanHarvestNow)
                {
                    summary = I18n.Generic_Now();
                }
                else if (!Game1.currentLocation.SeedsIgnoreSeasonsHere() && !data.Seasons.Contains(nextHarvest.Season))
                {
                    summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest));
                }
                else
                {
                    summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})";
                }

                yield return(new GenericField(I18n.Crop_Harvest(), summary));
            }

            // crop summary
            if (!isForage)
            {
                List <string> summary = new List <string>();

                // harvest
                if (!crop.forageCrop.Value)
                {
                    summary.Add(data.HasMultipleHarvests
                        ? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest)
                        : I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest)
                                );
                }

                // seasons
                summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons))));

                // drops
                if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0)
                {
                    summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2)));
                }
                else if (crop.minHarvest.Value > 1)
                {
                    summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value));
                }

                // crop sale price
                Item drop = data.GetSampleDrop();
                summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1)));

                // generate field
                yield return(new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary)));
            }

            // dirt water/fertilizer state
            if (dirt != null && !isForage)
            {
                // watered
                yield return(new GenericField(I18n.Crop_Watered(), this.Stringify(dirt.state.Value == HoeDirt.watered)));

                // fertilizer
                yield return(new GenericField(I18n.Crop_Fertilized(), dirt.fertilizer.Value switch
                {
                    HoeDirt.noFertilizer => this.Stringify(false),

                    HoeDirt.speedGro => GameI18n.GetObjectName(465),                  // Speed-Gro
                    HoeDirt.superSpeedGro => GameI18n.GetObjectName(466),             // Deluxe Speed-Gro
                    HoeDirt.hyperSpeedGro => GameI18n.GetObjectName(918),             // Hyper Speed-Gro

                    HoeDirt.fertilizerLowQuality => GameI18n.GetObjectName(368),      // Basic Fertilizer
                    HoeDirt.fertilizerHighQuality => GameI18n.GetObjectName(369),     // Quality Fertilizer
                    HoeDirt.fertilizerDeluxeQuality => GameI18n.GetObjectName(919),   // Deluxe Fertilizer

                    HoeDirt.waterRetentionSoil => GameI18n.GetObjectName(370),        // Basic Retaining Soil
                    HoeDirt.waterRetentionSoilQuality => GameI18n.GetObjectName(371), // Quality Retaining Soil
                    HoeDirt.waterRetentionSoilDeluxe => GameI18n.GetObjectName(920),  // Deluxe Retaining Soil

                    _ => I18n.Generic_Unknown()
                }));
Пример #11
0
 public bool MeetsCriteria(Farmer who, string locationName, WaterType waterType, SDate date, Weather weather, int time, int fishingLevel, int?mineLevel)
 {
     return((this.InvertLocations ^ (this.Location == null || locationName == this.Location)) &&
            (this.WaterType & waterType) != 0 &&
            (this.Season & date.GetSeason()) != 0 &&
            (this.Weather & weather) != 0 &&
            this.FishingLevel <= fishingLevel &&
            (this.MineLevel == null || this.MineLevel == mineLevel));
 }
        /// <summary>Checks if a new season has started every day and updates prices if it has.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event data.</param>
        private void TimeEvents_AfterDayStarted(object sender, EventArgs e)
        {
            // if save is loaded
            if (Context.IsWorldReady)
            {
                giftsGiven.Clear();
                foreach (KeyValuePair <string, int[]> NPC in Game1.player.friendships)
                {
                    if (NPC.Key == null || NPC.Value == null)
                    {
                        continue;
                    }
                    giftsGiven[NPC.Key] = new int[] { NPC.Value[0], NPC.Value[1] };
                }

                SDate currDate = SDate.Now();
                currSeason     = currDate.Season;
                prevSeason     = GetPrevSeason(currSeason);
                prevPrevSeason = GetPrevSeason(prevSeason);

                // Check if there is a stone in the fridge
                FarmHouse farmhouse = (FarmHouse)Game1.locations.First();
                Chest     fridge    = farmhouse.fridge;
                bool      hasStone  = false;

                // Check if there is a stone in the fridge
                foreach (Item item in fridge.items)
                {
                    if (item.Name == "Stone")
                    {
                        hasStone = true;
                        break;
                    }
                }

                // Update item prices everywhere if new season or there is a stone in the fridge
                if (currDate.Day == 1 || hasStone)
                {
                    // Remove outdated cache
                    Clear();

                    // Update inventory item prices
                    List <Item> items = Game1.player.items;

                    if (items.Count > 0)
                    {
                        foreach (Item item in items)
                        {
                            UpdatePriceBasedOnSeason(item);
                        }
                    }

                    // Update chests in the farmhouse
                    UpdateChestsInLocation(farmhouse);

                    // Update chests outside
                    foreach (GameLocation location in Game1.locations)
                    {
                        UpdateChestsInLocation(location);
                    }

                    // Update chests inside
                    foreach (SBuilding building in Game1.getFarm().buildings)
                    {
                        UpdateChestsInLocation(building.indoors);
                    }
                }
            }
        }
Пример #13
0
 internal static string GetFestivalName(SDate date) => SDVUtilities.GetFestivalName(date.Day, date.Season);
Пример #14
0
        /// <summary>When a menu is open (<see cref="Game1.activeClickableMenu"/> isn't null), raised after that menu is drawn to the sprite batch but before it's rendered to the screen.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnRenderedActiveMenu(object sender, RenderedActiveMenuEventArgs e)
        {
            bool outro = false;

            //revised this so it properly draws over the canon moon. :v
            if (Game1.activeClickableMenu is ShippingMenu ourMenu)
            {
                outro = Helper.Reflection.GetField <bool>(ourMenu, "outro").GetValue();
            }

            if (!Game1.wasRainingYesterday && !outro && Game1.activeClickableMenu is ShippingMenu currMenu && currMenu.currentPage == -1)
            {
                float scale = Game1.pixelZoom * 1.25f;

                if (Game1.viewport.Width < 1024)
                {
                    scale = Game1.pixelZoom * .8f;
                }
                if (Game1.viewport.Width < 810)
                {
                    scale = Game1.pixelZoom * .6f;
                }
                if (Game1.viewport.Width < 700)
                {
                    scale = Game1.pixelZoom * .35f;
                }

                Game1.spriteBatch.Draw(OurIcons.MoonSource, new Vector2(Game1.viewport.Width - 65 * Game1.pixelZoom, Game1.pixelZoom), Sprites.Icons.GetNightMoonSprite(SDVMoon.GetLunarPhaseForDay(SDate.Now().AddDays(-1))), Color.LightBlue, 0.0f, Vector2.Zero, scale, SpriteEffects.None, 1f);
            }
        }
Пример #15
0
 public OwnershipFrame(FrameFlags Flags, Price PricePayed, SDate PurchDate,
     string Seller, TextEncodings TEncoding)
     : base("OWNE", Flags)
 {
     _Price = PricePayed;
     _DateOfPurch = PurchDate;
     this.Seller = Seller;
 }
Пример #16
0
 internal string GetDescOfDay(SDate date)
 {
     return(Translator.Get("date" + GeneralFunctions.FirstLetterToUpper(date.Season) + date.Day));
 }
Пример #17
0
 private static int MinutesSinceStart()
 {
     return(Game1.timeOfDay + SDate.Now().DaysSinceStart * 10000);
 }
Пример #18
0
        internal string GenerateTVForecast(WeatherConditions Current, MersenneTwister Dice, double fogOdds, string MoonPhase = "", bool IsMoonUp = false)
        {
            string ret = "";

            //opening string
            ret += Translator.Get("weather-tv.opening", new
            {
                location       = Translator.Get("fern-loc." + Dice.Next(12)),
                playerLocation = Translator.Get("weather-location.player." + Dice.Next(4))
            });

            //hazard warning
            if (MoonPhase == "Blood Moon" && IsMoonUp)
            {
                ret += Translator.Get("weather-tv.bloodmoon");
            }

            if (Current.WeatherIsHazardous())
            {
                string hazard = "", rainfallW = "", hazardT = "", hazardF;

                if (Current.HasWeather(CurrentWeather.Heatwave))
                {
                    hazardT = Translator.Get("weather-tv.hazard.hw");
                }
                if (Current.HasWeather(CurrentWeather.Frost))
                {
                    hazardT = Translator.Get("weather-tv.hazard.frost");
                }

                if (Current.HasWeather(CurrentWeather.Blizzard))
                {
                    hazard = Translator.Get("weather-tv.hazard.blizzard");
                }
                if (Current.HasWeather(CurrentWeather.WhiteOut))
                {
                    hazard = Translator.Get("weather-tv.hazard.whiteout");
                }
                if (Current.HasWeather(CurrentWeather.ThunderFrenzy))
                {
                    hazard = Translator.Get("weather-tv.hazard.thunderfrenzy");
                }
                if (Current.HasWeather(CurrentWeather.Sandstorm))
                {
                    hazard = Translator.Get("weather-tv.hazard.sandstorm");
                }
                if (WeatherUtilities.IsSevereRainFall(Current.AmtOfRainDrops))
                {
                    switch (WeatherUtilities.GetRainCategory(Current.AmtOfRainDrops))
                    {
                    case RainLevels.Severe:
                        hazard = Translator.Get("weather-tv.hazard.rainfall.severe");
                        break;

                    case RainLevels.Torrential:
                        hazard = Translator.Get("weather-tv.hazard.rainfall.torrential");
                        break;

                    case RainLevels.Typhoon:
                        hazard = Translator.Get("weather-tv.hazard.rainfall.typhoon");
                        break;

                    case RainLevels.NoahsFlood:
                        hazard = Translator.Get("weather-tv.hazard.rainfall.noahsflood");
                        break;

                    default:
                        hazard = Translator.Get("weather-tv.hazard.rainfall.severe");
                        break;
                    }

                    rainfallW = Translator.Get("weather-tv.hazard.rainfallW");
                }

                if (!String.IsNullOrEmpty(hazard) && !String.IsNullOrEmpty(hazardT))
                {
                    hazardF = Translator.Get("weather-tv.twoHazardString", new { hazardOne = hazard, hazardTwo = hazardT });
                }
                else if (!String.IsNullOrEmpty(hazard))
                {
                    hazardF = hazard;
                }
                else
                {
                    hazardF = hazardT;
                }

                ret += Translator.Get("weather-tv.hazard", new {
                    hazard          = hazardF,
                    repLocation     = Translator.Get("weather-location.reporter." + Dice.Next(4)),
                    rainfallWarning = rainfallW
                });
            }

            //current conditions
            string time;

            switch (SDVTime.CurrentTimePeriod)
            {
            case SDVTimePeriods.Morning:
                time = Translator.Get("weather-tv.time.morning");
                break;

            case SDVTimePeriods.Noon:
            case SDVTimePeriods.Afternoon:
                time = Translator.Get("weather-tv.time.afternoon");
                break;

            case SDVTimePeriods.Evening:
                time = Translator.Get("weather-tv.time.evening");
                break;

            case SDVTimePeriods.Night:
                time = Translator.Get("weather-tv.time.night");
                break;

            case SDVTimePeriods.Midnight:
            case SDVTimePeriods.LateNight:
                time = Translator.Get("weather-tv.time.latenight");
                break;

            default:
                time = Translator.Get("weather-tv.time.generic");
                break;
            }

            string abText = "";

            if (Current.IsAbnormalHeat)
            {
                abText = Translator.Get("weather-tv.abnormalHeat");
            }

            if (Current.IsAbnormalChill)
            {
                abText = Translator.Get("weather-tv.abnormalChill");
            }

            string sysText = "";

            if (Current.trackerModel.WeatherSystemDays > 0)
            {
                if (Current.trackerModel.IsWeatherSystem)
                {
                    sysText = Translator.Get("weather-tv.systemMaint");
                }
            }

            //the first monster, describing the weather.
            string dWeather = "";

            if (!String.IsNullOrEmpty(SDVUtilities.GetFestivalName(SDate.Now())))
            {
                dWeather = Translator.Get("weather-tv.weat.festival", new { festivalName = SDVUtilities.GetFestivalName(SDate.Now()) });
            }

            if (Current.HasWeather(CurrentWeather.Wedding))
            {
                dWeather = Translator.Get("weather-tv.weat.wedding");
            }

            if (Current.HasWeather(CurrentWeather.Sunny))
            {
                dWeather = Translator.Get("weather-tv.weat.sunny");
            }

            if (Current.HasWeather(CurrentWeather.Rain) && !Current.HasWeather(CurrentWeather.Lightning))
            {
                dWeather = (Current.IsVariableRain ? Translator.Get("weather-tv.weat.rain.variable", new { rainDesc = GetRainDesc(Current.AmtOfRainDrops).Trim() })
                                                   : Translator.Get("weather-tv.weat.rain", new { rainDesc = GetRainDesc(Current.AmtOfRainDrops).Trim() }));
            }

            if (Current.HasWeather(CurrentWeather.Rain) && Current.HasWeather(CurrentWeather.Lightning) && !Current.HasWeather(CurrentWeather.ThunderFrenzy))
            {
                dWeather = Translator.Get("weather-tv.weat.thunderstorm");
            }

            if (Current.HasWeather(CurrentWeather.ThunderFrenzy))
            {
                dWeather = Translator.Get("weather-tv.weat.thunderfrenzy");
            }

            if (!Current.HasWeather(CurrentWeather.Rain) && Current.HasWeather(CurrentWeather.Lightning))
            {
                dWeather = Translator.Get("weather-tv.weat.drylightning");
            }

            if (Current.HasWeather(CurrentWeather.Blizzard) && !Current.HasWeather(CurrentWeather.WhiteOut))
            {
                dWeather = Translator.Get("weather-tv.weat.blizzard");
            }

            if (Current.HasWeather(CurrentWeather.WhiteOut))
            {
                dWeather = Translator.Get("weather-tv.weat.whiteout");
            }

            if (Current.HasWeather(CurrentWeather.Snow) && !Current.HasWeather(CurrentWeather.Blizzard) && !Current.HasWeather(CurrentWeather.WhiteOut) && !Current.HasWeather(CurrentWeather.Lightning))
            {
                dWeather = Translator.Get("weather-tv.weat.snowy");
            }

            if (Current.HasWeather(CurrentWeather.Snow) && !Current.HasWeather(CurrentWeather.Blizzard) && !Current.HasWeather(CurrentWeather.WhiteOut) && Current.HasWeather(CurrentWeather.Lightning))
            {
                dWeather = Translator.Get("weather-tv.weat.thundersnow");
            }

            if (Current.HasWeather(CurrentWeather.Sandstorm))
            {
                dWeather = Translator.Get("weather-tv.weat.sandstorms");
            }

            if (Current.HasWeather(CurrentWeather.Wind))
            {
                if (Game1.currentSeason == "winter")
                {
                    dWeather = Translator.Get("weather-tv.weat.windy.winter");
                }
                else
                {
                    dWeather = Translator.Get("weather-tv.weat.windy");
                }
            }

            string fog = "";

            if (Current.HasWeather(CurrentWeather.Fog))
            {
                if (!Current.HasWeather(CurrentWeather.Wedding))
                {
                    fog = Translator.Get("weather-tv.weat.fog", new { time = Current.GetFogTime() });
                }
                else
                {
                    fog = Translator.Get("weather-tv.weat.fogWed", new { time = Current.GetFogTime() });
                }
            }

            //ending up the current conditions.
            string tHazard = "";

            if (Current.HasWeather(CurrentWeather.Heatwave))
            {
                tHazard = Translator.Get("weather-tv.tempHazard.heat");
            }

            if (Current.HasWeather(CurrentWeather.Frost))
            {
                tHazard = Translator.Get("weather-tv.tempHazard.cold",
                                         new { time = (Game1.currentSeason == "spring"
                          ? Translator.Get("weather-tv.tempHazard.cold.spring") :
                                                       Translator.Get("weather-tv.tempHazard.cold.fall")) });
            }

            string rRate = "";

            if (Current.HasWeather(CurrentWeather.Rain))
            {
                rRate = Translator.Get("weather-tv.rainfallRate", new { rate = WeatherUtilities.GetRainfallAmt(Current.AmtOfRainDrops).ToString("N2") });
            }

            var transParams = new Dictionary <string, string> {
                { "time", time },
                { "currentTemp", GetTemperatureString(Current.GetCurrentTemperature(Game1.timeOfDay)) },
                { "abnormalText", abText },
                { "systemText", sysText },
                { "descWeather", dWeather },
                { "fogText", fog },
                { "tempHazard", tHazard },
                { "rainfallRate", rRate }
            };

            ret += Translator.Get("weather-tv.currentCond", transParams);
            transParams.Clear();

            //now, tomorrow!! :D

            sysText = "";
            if (Current.trackerModel.WeatherSystemDays > 0)
            {
                if (Current.trackerModel.IsWeatherSystem)
                {
                    sysText = Translator.Get("weather-tv.tmrw.systemMaint",
                                             new { desc = Translator.Get("weather-location.system.desc." + Dice.Next(6)) });
                }
                if (!Current.trackerModel.IsWeatherSystem && (Game1.weatherForTomorrow != WeatherUtilities.GetWeatherCode()))
                {
                    sysText = Translator.Get("weather-tv.tmrw.systemEnding",
                                             new { desc = Translator.Get("weather-location.system.desc." + Dice.Next(6)), direction = Translator.Get("weather-location.system.move." + Dice.Next(4)) });
                }
            }
            else
            {
                sysText = Translator.Get("weather-tv.tmrw.systemNone");
            }

            //now weather
            switch (Game1.weatherForTomorrow)
            {
            case Game1.weather_rain:
                dWeather = Translator.Get("weather-tv.rain." + Dice.Next(2));
                break;

            case Game1.weather_festival:
                dWeather = Translator.Get("weather-tv.festival", new { festName = SDVUtilities.GetFestivalName(SDate.Now().AddDays(1)) });
                break;

            case Game1.weather_debris:
                dWeather = Translator.Get("weather-tv.debris." + Dice.Next(2));
                break;

            case Game1.weather_snow:
                dWeather = Translator.Get("weather-tv.snowy." + Dice.Next(2));
                break;

            case Game1.weather_wedding:
                dWeather = Translator.Get("weather-tv.wedding");
                break;

            case Game1.weather_lightning:
                dWeather = Translator.Get("weather-tv.tstorm." + Dice.Next(2));
                break;

            case Game1.weather_sunny:
            default:
                dWeather = Translator.Get("weather-tv.sunny." + Dice.Next(2));
                break;
            }

            //overrides for festival and wedding (just in case, my paranoia is spiking. :|)
            if (!String.IsNullOrEmpty(SDVUtilities.GetFestivalName(SDate.Now().AddDays(1))))
            {
                dWeather = Translator.Get("weather-tv.festival", new { festName = SDVUtilities.GetFestivalName(SDate.Now().AddDays(1)) });
            }
            if (Game1.player.spouse != null && Game1.player.isEngaged() && Game1.player.friendshipData[Game1.player.spouse].CountdownToWedding == 1)
            {
                dWeather = Translator.Get("weather-tv.wedding");
            }

            fog = "";
            //now, the fog string
            if (fogOdds >= .6)
            {
                fog = Translator.Get("weather-tv.fogChance");
            }

            //tHazard string

            if (Current.TomorrowHigh > (Current.TodayHigh + 1.5))
            {
                tHazard = Translator.Get("weather-tv.tmrw.warmer", new
                {
                    high = GetTemperatureString(Current.TomorrowHigh),
                    low  = GetTemperatureString(Current.TomorrowLow),
                });
            }
            else if ((Current.TomorrowHigh < (Current.TodayHigh - 1.5)))
            {
                tHazard = Translator.Get("weather-tv.tmrw.cooler", new
                {
                    high = GetTemperatureString(Current.TomorrowHigh),
                    low  = GetTemperatureString(Current.TomorrowLow),
                });
            }
            else
            {
                tHazard = Translator.Get("weather-tv.tmrw.effsame", new
                {
                    high = GetTemperatureString(Current.TomorrowHigh),
                    low  = GetTemperatureString(Current.TomorrowLow),
                });
            }


            transParams.Add("sysText", sysText);
            transParams.Add("weather", dWeather);
            transParams.Add("fogChance", fog);
            transParams.Add("tempString", tHazard);

            ret += Translator.Get("weather-tv.tomorrowForecast", transParams);
            return(ret);
        }
Пример #19
0
 ["DaysOfWeek"] = (valueToCheck, _) => valueToCheck.Split(' ').Any(
     d => d.ToLower() == SDate.Now().DayOfWeek.ToString().ToLower()),
 public static int GetEventId(SDate date)
 {
     return(Convert.ToInt32($"{6572+date.Year/100}{date.Year%100:00}{Utility.getSeasonNumber(date.Season)}{date.Day:00}"));
 }
Пример #21
0
        /// <summary>
        /// Sets Wednesdays to rain.
        /// Adds greeting from a list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDayStarted(object sender, DayStartedEventArgs e)
        {
            int    MaxDays  = this.Config.MaxDays;
            string RainDay  = this.Config.RainDay;
            var    date     = SDate.Now();
            var    RainPrep = date.AddDays(-1).DayOfWeek;

            bool   UseMax      = this.Config.UseMax;
            var    CurrSeason  = Game1.currentSeason;
            Random newGreeting = new Random();
            int    greet2      = newGreeting.Next(0, morningPhrase.Count);

            Console.WriteLine(this.Config.Greetings);
            Console.WriteLine(morningPhrase[greet2]);



            var greeting = string.Format(morningPhrase[greet2] + Game1.player.name + "!");

            if (CurrSeason == "winter")
            {
                Game1.drawObjectDialogue(Game1.parseText(greeting.ToUpper()));

                return;
            }
            if (UseMax)
            {
                if (Game1.isRaining)
                {
                    DaysWORain = 0;
                    this.Monitor.Log($"It is currently raining.  Days without rain: {DaysWORain}", LogLevel.Debug);
                }
                else
                {
                    DaysWORain++;
                    this.Monitor.Log($"It is not raining.  Days without rain: {DaysWORain}", LogLevel.Debug);
                }
                if (DaysWORain >= MaxDays)
                {
                    Game1.weatherForTomorrow   = 1;
                    Game1.chanceToRainTomorrow = .999;
                    this.Monitor.Log($"It has been {DaysWORain} days without rain, chance of rain tomorrow: {Game1.chanceToRainTomorrow} ", LogLevel.Debug);
                }
            }
            else
            {
                if (date.AddDays(1).DayOfWeek.ToString() == RainDay.ToString() && Game1.IsMasterGame)
                {
                    Game1.weatherForTomorrow   = 1;
                    Game1.chanceToRainTomorrow = .999;
                    this.Monitor.Log($"Its {RainDay} tomorrow! ", LogLevel.Debug);
                }
                else if (!Game1.IsMasterGame)
                {
                    this.Monitor.Log($"User is not host.  Rain update cancelled", LogLevel.Debug);
                }
                else if (date.DayOfWeek.ToString() != RainDay)
                {
                    this.Monitor.Log($"Day is {date}.  Rain is scheduled for {RainDay}s", LogLevel.Debug);
                }
                if (Game1.isRaining)
                {
                    this.Monitor.Log($"It is raining, Chance of rain tomorrow: {Game1.chanceToRainTomorrow}.  Today's day: {date}, { date.DayOfWeek}", LogLevel.Debug);
                    greeting = "ITS RAINING!!!!";
                }
                else
                {
                    this.Monitor.Log($"It is not raining, Chance of rain tomorrow: {Game1.chanceToRainTomorrow}.  Today's day: {date}, { date.DayOfWeek}", LogLevel.Debug);
                }
            }
            Game1.drawObjectDialogue(Game1.parseText(greeting.ToUpper()));
        }
Пример #22
0
 /// <summary>Gets the <see cref="Season"/> associated with the given date.</summary>
 /// <param name="date">The date to get the season of.</param>
 /// <returns>The <see cref="Season"/> which matches the given date.</returns>
 public static Season GetSeason(this SDate date)
 {
     return(date.Season.GetSeason() ?? throw new InvalidOperationException($"Unexpected season {date.Season} when converting it to a Season enum value."));
 }
Пример #23
0
        public static CustomEvent CreateEvent(SDate contestDate)
        {
            int    eventId = GetEventId(contestDate);
            string key     = GenerateKey(eventId, contestDate);

            Random random = new Random((int)((long)Game1.uniqueIDForThisGame * 100000 + contestDate.Year * 1000 + Utility.getSeasonNumber(contestDate.Season) * 100 + contestDate.Day));

            //Player and Participant init
            long?        contestParticipantId    = AnimalContestController.ContestParticipantId(contestDate);
            AnimalStatus participantAnimalStatus = contestParticipantId != null?AnimalStatusController.GetAnimalStatus((long)contestParticipantId) : null;

            bool       isPlayerJustWatching = participantAnimalStatus == null;
            bool       isParticipantPet     = !isPlayerJustWatching && participantAnimalStatus.Id == AnimalData.PetId;
            FarmAnimal farmAnimal           = null;

            if (isParticipantPet)
            {
                AnimalContestController.TemporalyRemovePet();
            }
            else if (!isPlayerJustWatching)
            {
                farmAnimal = AnimalContestController.GetAnimal(participantAnimalStatus.Id);
                if (farmAnimal == null)
                {
                    isPlayerJustWatching = true;
                }
                else
                {
                    AnimalContestController.TemporalyRemoveFarmAnimal(farmAnimal);
                }
            }

            List <AnimalContestItem> history = FarmerLoader.FarmerData.AnimalContestData;

            string[] contenders = new string[3];
            contenders[0] = "Marnie";
            contenders[1] = GetContenderFromPool(new List <IAnimalContestAct>(PossibleSecondContenders).Where(c => !isPlayerJustWatching || !c.NpcName.Equals("Jas")).ToList(), history) ?? "Maru";
            contenders[2] = GetContenderFromPool(new List <IAnimalContestAct>(PossibleThirdContenders), history) ?? "Jodi";

            string        marnieAnimal  = MarnieAct.ChooseMarnieAnimal(random, history);
            VincentAnimal vincentAnimal = VincentAct.ChooseVincentAnimal(random, history);

            AnimalContestItem animalContestInfo = new AnimalContestItem(eventId, contestDate, contenders.ToList(), vincentAnimal.ToString(), marnieAnimal)
            {
                ParticipantId = isParticipantPet ? AnimalData.PetId : farmAnimal?.myID.Value,
                PlayerAnimal  = isParticipantPet ? Game1.player.catPerson ? "Cat" : "Dog" : farmAnimal?.type.Value
            };

            animalContestInfo = PickTheWinner(animalContestInfo, history, participantAnimalStatus, farmAnimal, contenders[2]);

            // Deciding who will be present
            bool isHaleyWatching     = Game1.player.eventsSeen.Contains(14) || Game1.player.spouse == "Haley";
            bool isKentWatching      = Game1.year > 1 && contenders.Contains("Jodi");
            bool isSebastianWatching = Game1.player.spouse != "Sebastian" && (vincentAnimal == VincentAnimal.Frog || contenders.Contains("Abigail"));
            bool isPennyWatching     = Game1.player.spouse != "Penny" && !isSebastianWatching && (contenders.Contains("Maru") || contenders.Contains("Jas") || isPlayerJustWatching || Game1.player.getFriendshipHeartLevelForNPC("Penny") >= 4);
            bool isDemetriusWatching = contenders.Contains("Maru");
            bool isClintWatching     = contenders.Contains("Emily");
            bool isLeahWatching      = Game1.player.spouse != "Leah" && Game1.player.eventsSeen.Contains(53);
            bool isLinusWatching     = !contenders.Contains("Linus") && (Game1.player.eventsSeen.Contains(26) || vincentAnimal == VincentAnimal.Rabbit);
            bool isShaneWatching     = !contenders.Contains("Shane") && (contenders.Contains("Jas") || isPlayerJustWatching || Game1.player.eventsSeen.Contains(3900074) || Game1.player.spouse == "Shane");

            StringBuilder initialPosition = new StringBuilder();

            initialPosition.Append("none/-100 -100");
            if (!isPlayerJustWatching)
            {
                initialPosition.Append("/farmer 27 62 2");
            }
            else
            {
                if (IsWatchingPositionNorthEast(animalContestInfo))
                {
                    initialPosition.Append("/farmer 37 62 2");
                }
                else
                {
                    initialPosition.Append($"/farmer 28 70 {(IsWatchingPositionSouthEest(animalContestInfo)?"1":"3")}");
                }
            }

            initialPosition.Append(" Lewis 28 63 2");
            initialPosition.Append($" {contenders[0]} 24 66 3");
            initialPosition.Append($" {contenders[1]} 30 66 1");
            initialPosition.Append($" {contenders[2]} 33 66 1");
            if (isKentWatching)
            {
                initialPosition.Append($" Kent 36 66 3");
            }

            if (!contenders.Contains("Jodi"))
            {
                initialPosition.Append($" Jodi 36 65 3");
            }
            initialPosition.Append($" Sam 37 66 3");
            initialPosition.Append($" Gus 36 68 3");
            initialPosition.Append($" Evelyn 30 69 1");
            initialPosition.Append($" George 31 69 0");
            if (!contenders.Contains("Alex"))
            {
                initialPosition.Append($" Alex 31 70 0");
            }
            initialPosition.Append($" Pierre 26 69 1");
            initialPosition.Append($" Caroline 27 69 3");
            if (Game1.player.spouse != "Elliott")
            {
                initialPosition.Append($" Elliott 33 69 0");
            }
            if (!contenders.Contains("Willy"))
            {
                initialPosition.Append($" Willy 35 69 0");
            }
            if (isHaleyWatching)
            {
                initialPosition.Append($" Haley 22 68 1");
            }
            if (isLeahWatching)
            {
                initialPosition.Append($" Leah 22 70 0");
            }
            if (isSebastianWatching)
            {
                initialPosition.Append($" Sebastian 37 67 3");
            }
            else if (isPennyWatching)
            {
                initialPosition.Append($" Penny 37 67 3");
            }
            if (isDemetriusWatching)
            {
                initialPosition.Append($" Demetrius 32 70 0");
            }
            if (isClintWatching)
            {
                initialPosition.Append($" Clint 34 70 0");
            }
            if (isPlayerJustWatching)
            {
                initialPosition.Append($" Jas 27 66 0");
            }
            else if (!contenders.Contains("Jas"))
            {
                initialPosition.Append($" Jas 23 70 0");
            }
            if (isShaneWatching)
            {
                initialPosition.Append($" Shane 24 70 0");
            }

            bool linusAlternateAnimal = false;

            if (isLinusWatching)
            {
                initialPosition.Append($" Linus 37 70 3");
            }
            else
            {
                linusAlternateAnimal = history.Count(h => h.Contenders.Contains("Linus")) % 2 == new Random((int)Game1.uniqueIDForThisGame).Next(2);
            }

            if (Game1.player.spouse != null && !new string[] { "Shane", "Alex", "Sam", "Haley" }.Contains(Game1.player.spouse) &&
                !animalContestInfo.Contenders.Contains(Game1.player.spouse))
            {
                initialPosition.Append($" {Game1.player.spouse} 25 69 0");
            }

            initialPosition.Append($" Vincent 28 80 0");

            if (isParticipantPet)
            {
                if (!Game1.player.catPerson)
                {
                    initialPosition.Append(" dog 26 66 2/showFrame Dog 23");
                }
                else
                {
                    initialPosition.Append(" cat 26 66 2/positionOffset Cat -8 0/showFrame Cat 18");
                }
            }
            else
            {
                if (!isPlayerJustWatching)
                {
                    string spriteTextureName = farmAnimal.Sprite.textureName.Value;
                    string playerAnimalTextureName;
                    if (spriteTextureName.StartsWith("Animals\\"))
                    {
                        playerAnimalTextureName = farmAnimal.Sprite.textureName.Value
                                                  .Substring(farmAnimal.Sprite.textureName.Value.IndexOf('\\') + 1)
                                                  .Replace(' ', '_');
                    }
                    else
                    {
                        DataLoader.AssetsToLoad["Animals\\" + spriteTextureName.Replace('_', ' ')] = farmAnimal.Sprite.Texture;
                        playerAnimalTextureName = spriteTextureName.Replace(' ', '_');;
                    }
                    bool isPlayerAnimalSmall = IsAnimalSmall(farmAnimal);
                    initialPosition.Append($"/addTemporaryActor {playerAnimalTextureName} {(isPlayerAnimalSmall? SmallSize : BigSize)} {(isPlayerAnimalSmall?26:25)} 66 0 false Animal participant/showFrame participant 0");
                    if (!isPlayerAnimalSmall)
                    {
                        initialPosition.Append("/positionOffset participant 5 0");
                    }
                }
            }
            initialPosition.Append("/specificTemporarySprite animalContest/skippable");
            initialPosition.Append(GetContendersAnimalPosition(contenders, marnieAnimal, isPlayerJustWatching, linusAlternateAnimal));

            initialPosition.Append("/viewport 28 65 true");

            StringBuilder eventAction = new StringBuilder();

            if (isHaleyWatching)
            {
                eventAction.Append("/showFrame Haley 25");
            }
            if (contenders.Contains("Maru"))
            {
                eventAction.Append("/animate Maru false false 130 16 16 16 16 16 17 18 19 20 21 22 23 23 23 23");
            }
            string faceDirectionPlayerPosition;

            if (!isPlayerJustWatching)
            {
                faceDirectionPlayerPosition = "farmer";
                eventAction.Append("/move farmer 0 4 2/faceDirection farmer 3");
                if (isParticipantPet)
                {
                    eventAction.Append($"/playSound {(Game1.player.catPerson ? "cat" : "dog_bark")}");
                }
                eventAction.Append("/emote farmer 32");
                //eventAction.Append($"/emote {(isParticipantPet?!Game1.player.catPerson? "Dog":"Cat": "participant")} 20");
            }
            else
            {
                faceDirectionPlayerPosition = "Jas";
                if (IsWatchingPositionNorthEast(animalContestInfo))
                {
                    eventAction.Append("/move farmer 0 3 2/faceDirection farmer 3");
                }
                else if (IsWatchingPositionSouthEest(animalContestInfo))
                {
                    eventAction.Append("/move farmer 2 0 1/faceDirection farmer 0");
                }
                else
                {
                    eventAction.Append("/move farmer -3 0 3/faceDirection farmer 0");
                }
                if (Game1.player.spouse != null)
                {
                    eventAction.Append($"/emote {Game1.player.spouse} 20 true/emote farmer 20");
                }
            }

            if (isHaleyWatching)
            {
                eventAction.Append("/pause 200/playSound cameraNoise/shake Haley 50/screenFlash .5/pause 1000/showFrame Haley 5/pause 1000");
            }
            if (!isPlayerJustWatching)
            {
                eventAction.Append("/faceDirection farmer 0");
                eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.PlayerParticipant")}\"");
            }
            else
            {
                eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.PlayerWatching")}\"");
            }
            eventAction.Append($"/faceDirection {contenders[0]} 0");
            eventAction.Append($"/pause 1000/emote Lewis 40/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.Attention")}\"");

            eventAction.Append($"/pause 100/faceDirection {contenders[1]} 0 true");
            eventAction.Append($"/faceDirection Pierre 0");
            eventAction.Append($"/faceDirection {contenders[2]} 0 true");
            eventAction.Append($"/faceDirection Evelyn 0 true");
            if (!contenders.Contains("Willy"))
            {
                initialPosition.Append($"/faceDirection Willy 3");
            }
            eventAction.Append($"/faceDirection Caroline 0");

            if (history.Count == 0)
            {
                eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.IntroductionFirstTime")}\"");
            }
            else
            {
                eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.IntroductionOtherTimes")}\"");
            }

            eventAction.Append(new VincentAct().GetAct(animalContestInfo, history));

            eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.ContestExplanation")}\"");
            eventAction.Append($"/faceDirection {contenders[2]} 3 true");
            eventAction.Append("/move Lewis 0 1 2");
            eventAction.Append($"/faceDirection {contenders[0]} 3 true");
            eventAction.Append("/move Lewis 0 1 2");
            eventAction.Append($"/faceDirection {faceDirectionPlayerPosition} 3 true");
            eventAction.Append($"/faceDirection {contenders[1]} 3 true");
            eventAction.Append("/move Lewis 0 2 2");
            eventAction.Append("/move Lewis -5 0 3/faceDirection Lewis 0");
            eventAction.Append(new MarnieAct().GetAct(animalContestInfo, history));
            eventAction.Append($"/faceDirection Lewis 1/move Lewis 1 0 1/faceDirection {contenders[0]} 2 true/move Lewis 2 0 1/faceDirection {contenders[0]} 1 true/faceDirection Lewis 0");
            if (!isPlayerJustWatching)
            {
                eventAction.Append(GetPlayerAct(animalContestInfo, farmAnimal, history));
            }
            else
            {
                eventAction.Append(JasAct.GetAct(animalContestInfo, history));
            }
            eventAction.Append($"/faceDirection Lewis 1/move Lewis 1 0 1/faceDirection {faceDirectionPlayerPosition} 2 true/move Lewis 1 0 1/faceDirection {faceDirectionPlayerPosition} 1 true/move Lewis 1 0 1/faceDirection {contenders[1]} 2 true/move Lewis 2 0 1/faceDirection {contenders[1]} 1 true/faceDirection Lewis 0");
            eventAction.Append(PossibleSecondContenders.First(c => c.NpcName.Equals(contenders[1])).GetAct(animalContestInfo, history));
            eventAction.Append($"/faceDirection Lewis 1/move Lewis 1 0 1/faceDirection {contenders[2]} 2 true/move Lewis 2 0 1/faceDirection {contenders[2]} 1 true/faceDirection Lewis 0");
            eventAction.Append(PossibleThirdContenders.First(c => c.NpcName.Equals(contenders[2])).GetAct(animalContestInfo, history));
            eventAction.Append($"/playMusic event1/faceDirection Lewis 3/faceDirection Lewis 2/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.Closure")}\"");
            eventAction.Append($"/faceDirection Lewis 3/move Lewis -6 0 3/faceDirection Lewis 0/move Lewis 0 -4 0/faceDirection {contenders[1]} 0 true/faceDirection {contenders[0]} 0 true/faceDirection Lewis 3/faceDirection {contenders[2]} 0 true/faceDirection {faceDirectionPlayerPosition} 0 true/faceDirection Lewis 2");

            eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.ClosureThanks")}#$b#");
            if (history.Count == 0)
            {
                eventAction.Append($"{i18n.Get("AnimalContest.Dialog.Lewis.ClosureSuccessFirstTime")}\"");
            }
            else
            {
                eventAction.Append($"{i18n.Get("AnimalContest.Dialog.Lewis.ClosureSuccessOtherTimes")}\"");
            }
            String winnerAnimalName = animalContestInfo.Winner == "Farmer"
                ? farmAnimal.displayName
                : animalContestInfo.Winner == "Emily"
                    ? i18n.Get("AnimalContest.Dialog.Lewis.EmilyUnnamedParrot")
                    : "%name";
            String winnerName = animalContestInfo.Winner == "Farmer"?"@":animalContestInfo.Winner;

            eventAction.Append($"/stopMusic/pause 200/speak Lewis \"{ i18n.Get("AnimalContest.Dialog.Lewis.WinnerAnnouncement", new {winnerName, winnerAnimalName})}\"");
            eventAction.Append("/playMusic event1/emote Alex 56 true/pause 60");
            if (animalContestInfo.Winner == "Farmer")
            {
                eventAction.Append("/emote farmer 32 true/pause 500");
                if (Game1.player.spouse != null)
                {
                    eventAction.Append($"/textAboveHead {Game1.player.spouse} \"{i18n.Get("AnimalContest.Dialog.Spouse.PlayerCongrats")}\"/pause 1500");
                }
                if (Game1.player.getFriendshipHeartLevelForNPC("Gus") >= 4)
                {
                    eventAction.Append($"/textAboveHead Gus \"{i18n.Get("AnimalContest.Dialog.Gus.PlayerCongrats", new { playerName = Game1.player.Name })}\"/pause 1500");
                }
                else if (Game1.player.spouse != null)
                {
                    eventAction.Append($"/pause 1500");
                }
                if (Game1.player.getFriendshipHeartLevelForNPC("Pierre") >= 4)
                {
                    eventAction.Append($"/textAboveHead Pierre \"{i18n.Get("AnimalContest.Dialog.Pierre.PlayerCongrats", new { playerName = Game1.player.Name })}\"/pause 1500");
                }
                if (isLinusWatching && Game1.player.getFriendshipHeartLevelForNPC("Linus") >= 4)
                {
                    eventAction.Append($"/textAboveHead Linus \"{i18n.Get("AnimalContest.Dialog.Linus.PlayerCongrats", new { playerName = Game1.player.Name })}\"/pause 1500");
                }
                else if (Game1.player.getFriendshipHeartLevelForNPC("Pierre") >= 4)
                {
                    eventAction.Append($"/pause 1500");
                }
            }
            else if (animalContestInfo.Winner == "Marnie")
            {
                eventAction.Append("/specificTemporarySprite animalContestMarnieWinning/warp Marnie -2000 -2000/pause 500");
                eventAction.Append($"/emote Jas 32 true/pause 1500");
                if (isShaneWatching || animalContestInfo.Contenders.Contains("Shane"))
                {
                    eventAction.Append($"/textAboveHead Shane \"{i18n.Get("AnimalContest.Dialog.Shane.MarnieCongrats")}\"/pause 1000");
                }
            }
            else if (animalContestInfo.Winner == "Shane")
            {
                eventAction.Append("/emote Shane 16 true/emote shaneAnimal 20 true");
                eventAction.Append($"/pause 500/emote Jas 32 true/pause 500/textAboveHead Marnie \"{i18n.Get("AnimalContest.Dialog.Marnie.ShaneContrats")}\"/pause 1000");
            }
            else if (animalContestInfo.Winner == "Emily")
            {
                eventAction.Append("/specificTemporarySprite animalContestEmilyParrotAction/emote Emily 20 true");
                eventAction.Append($"/textAboveHead Clint \"{i18n.Get("AnimalContest.Dialog.Clint.EmilyContrats")}\"/pause 500");
                if (isHaleyWatching)
                {
                    eventAction.Append($"/textAboveHead Haley \"{i18n.Get("AnimalContest.Dialog.Haley.EmilyContrats")}\"/pause 500");
                }
                eventAction.Append($"/pause 1000/textAboveHead Gus \"{i18n.Get("AnimalContest.Dialog.Gus.EmilyContrats")}\"/pause 1000");
            }
            else if (animalContestInfo.Winner == "Jodi")
            {
                eventAction.Append("/emote jodiAnimal 20 true/emote Jodi 32 true/pause 1000");
                if (isKentWatching)
                {
                    eventAction.Append($"/textAboveHead Kent \"{i18n.Get("AnimalContest.Dialog.Kent.JodiContrats")}\"/pause 1500");
                }
                eventAction.Append($"/textAboveHead Caroline \"{i18n.Get("AnimalContest.Dialog.Caroline.JodiContrats")}\"/pause 1500");
                eventAction.Append($"/textAboveHead Sam \"{i18n.Get("AnimalContest.Dialog.Sam.JodiContrats")}\"/pause 1500");
            }
            eventAction.Append($"/textAboveHead Evelyn \"{i18n.Get("AnimalContest.Dialog.Evelyn.Contrats")}\"");
            if (isHaleyWatching)
            {
                eventAction.Append("/showFrame Haley 25/pause 1000/playSound cameraNoise/shake Haley 50/screenFlash .5/pause 1000/showFrame Haley 5/pause 1500");
            }
            else
            {
                eventAction.Append($"/pause 3000");
            }

            eventAction.Append($"/speak Lewis \"{i18n.Get("AnimalContest.Dialog.Lewis.Ending")}\"/faceDirection Lewis 3/move Lewis -2 0 3 true");
            if (animalContestInfo.Winner != "Marnie")
            {
                eventAction.Append($"/faceDirection Marnie 0/move Marnie 0 -2 0 true");
            }
            eventAction.Append($"/pause 1500/showFrame Lewis 16/globalFade/viewport -1000 -1000");
            if (animalContestInfo.Winner == "Farmer" && !DataLoader.ModConfig.DisableContestBonus)
            {
                string bonusType = contestDate.Season == "spring" || contestDate.Season == "summer" ? i18n.Get("AnimalContest.Message.Reward.Fertility") : i18n.Get("AnimalContest.Message.Reward.Production");
                eventAction.Append($"/playSound reward/message \"{i18n.Get("AnimalContest.Message.Reward", new { animalName = farmAnimal.displayName, bonusType })}\"");
            }
            eventAction.Append("/specificTemporarySprite animalContestEnding/end");

            string script = initialPosition.ToString() + eventAction.ToString();

            FarmerLoader.FarmerData.AnimalContestData.Add(animalContestInfo);

            return(new CustomEvent(key, script));
        }
Пример #24
0
        /*********
        ** Private methods
        *********/
        /// <summary>Get the global value providers with which to initialize the token manager.</summary>
        /// <param name="contentHelper">The content helper from which to load data assets.</param>
        /// <param name="installedMods">The installed mod IDs.</param>
        private IEnumerable <IValueProvider> GetGlobalValueProviders(IContentHelper contentHelper, InvariantHashSet installedMods)
        {
            bool NeedsBasicInfo() => this.IsBasicInfoLoaded;

            // date and weather
            yield return(new ConditionTypeValueProvider(ConditionType.Day, () => SDate.Now().Day.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo, allowedValues: Enumerable.Range(0, 29).Select(p => p.ToString()))); // day 0 = new-game intro

            yield return(new ConditionTypeValueProvider(ConditionType.DayEvent, () => this.GetDayEvent(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.DayOfWeek, () => SDate.Now().DayOfWeek.ToString(), NeedsBasicInfo, allowedValues: Enum.GetNames(typeof(DayOfWeek))));

            yield return(new ConditionTypeValueProvider(ConditionType.DaysPlayed, () => Game1.stats.DaysPlayed.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.Season, () => SDate.Now().Season, NeedsBasicInfo, allowedValues: new[] { "Spring", "Summer", "Fall", "Winter" }));

            yield return(new ConditionTypeValueProvider(ConditionType.Year, () => SDate.Now().Year.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.Weather, this.GetCurrentWeather, NeedsBasicInfo, allowedValues: Enum.GetNames(typeof(Weather))));

            yield return(new TimeValueProvider(NeedsBasicInfo));

            // player
            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasConversationTopic, player => player.activeDialogueEvents.Keys, NeedsBasicInfo));

            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasDialogueAnswer, this.GetDialogueAnswers, NeedsBasicInfo));

            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasFlag, this.GetFlags, NeedsBasicInfo));

            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasProfession, this.GetProfessions, NeedsBasicInfo));

            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasReadLetter, player => player.mailReceived, NeedsBasicInfo));

            yield return(new LocalOrHostPlayerValueProvider(ConditionType.HasSeenEvent, this.GetEventsSeen, NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.HasWalletItem, this.GetWalletItems, NeedsBasicInfo, allowedValues: Enum.GetNames(typeof(WalletItem))));

            yield return(new ConditionTypeValueProvider(ConditionType.IsMainPlayer, () => Context.IsMainPlayer.ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.IsOutdoors, () => Game1.currentLocation?.IsOutdoors.ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.LocationName, () => Game1.currentLocation?.Name, NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.PlayerGender, () => (Game1.player.IsMale ? Gender.Male : Gender.Female).ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.PlayerName, () => Game1.player.Name, NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.PreferredPet, () => (Game1.player.catPerson ? PetType.Cat : PetType.Dog).ToString(), NeedsBasicInfo));

            yield return(new SkillLevelValueProvider(NeedsBasicInfo));

            // relationships
            yield return(new VillagerHeartsValueProvider());

            yield return(new VillagerRelationshipValueProvider());

            yield return(new ConditionTypeValueProvider(ConditionType.Spouse, () => Game1.player?.spouse, NeedsBasicInfo));

            // world
            yield return(new ConditionTypeValueProvider(ConditionType.FarmCave, () => this.GetEnum(Game1.player.caveChoice.Value, FarmCaveType.None).ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.FarmhouseUpgrade, () => Game1.player.HouseUpgradeLevel.ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.FarmName, () => Game1.player.farmName.Value, NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.FarmType, () => this.GetEnum(Game1.whichFarm, FarmType.Custom).ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.IsCommunityCenterComplete, () => this.GetIsCommunityCenterComplete().ToString(), NeedsBasicInfo));

            yield return(new ConditionTypeValueProvider(ConditionType.IsJojaMartComplete, () => this.GetIsJojaMartComplete().ToString(), NeedsBasicInfo));

            yield return(new HavingChildValueProvider(ConditionType.Pregnant, NeedsBasicInfo));

            yield return(new HavingChildValueProvider(ConditionType.HavingChild, NeedsBasicInfo));

            // number manipulation
            yield return(new QueryValueProvider());

            yield return(new RandomValueProvider());

            yield return(new RangeValueProvider());

            yield return(new RoundValueProvider());

            // string manipulation
            yield return(new LetterCaseValueProvider(ConditionType.Lowercase));

            yield return(new LetterCaseValueProvider(ConditionType.Uppercase));

            // metadata
            yield return(new ImmutableValueProvider(ConditionType.HasMod.ToString(), installedMods, canHaveMultipleValues: true));

            yield return(new HasValueValueProvider());

            yield return(new ConditionTypeValueProvider(ConditionType.Language, () => contentHelper.CurrentLocaleConstant.ToString(), allowedValues: Enum.GetNames(typeof(LocalizedContentManager.LanguageCode)).Where(p => p != LocalizedContentManager.LanguageCode.th.ToString())));
        }
Пример #25
0
 public override void performHoverAction(int x, int y)
 {
     base.performHoverAction(x, y);
     if (_movingAnimal.GetValue())
     {
         Vector2  tile             = new Vector2((float)((x + Game1.viewport.X) / Game1.tileSize), (float)((y + Game1.viewport.Y) / Game1.tileSize));
         Farm     locationFromName = Game1.getLocationFromName("Farm") as Farm;
         Building buildingAt       = locationFromName.getBuildingAt(tile);
         if (buildingAt != null &&
             buildingAt.color.Equals(Color.LightGreen * 0.8f) &&
             PregnancyController.IsAnimalPregnant(this._farmAnimal) &&
             PregnancyController.CheckBuildingLimit(this._farmAnimal))
         {
             buildingAt.color.Value = Color.Red * 0.8f;
         }
     }
     else
     {
         if (this.meatButton != null)
         {
             if (this.meatButton.containsPoint(x, y))
             {
                 this.meatButton.scale = Math.Min(4.1f, this.meatButton.scale + 0.05f);
                 _hoverText.SetValue(DataLoader.i18n.Get("Menu.AnimalQueryMenu.ExchangeAnimalForMeat"));
             }
             else
             {
                 this.meatButton.scale = Math.Max(4f, this.meatButton.scale - 0.05f);
             }
         }
         if (this.pregnantStatus != null)
         {
             if (this.pregnantStatus.containsPoint(x, y))
             {
                 int?daysUntilBirth = this._farmAnimal.GetDaysUntilBirth();
                 if (daysUntilBirth.HasValue)
                 {
                     _hoverText.SetValue(
                         daysUntilBirth.Value > 1
                         ? DataLoader.i18n.Get("Menu.AnimalQueryMenu.DaysUntilBirth", new { numberOfDays = daysUntilBirth.Value })
                         : DataLoader.i18n.Get("Menu.AnimalQueryMenu.ReadyForBirth")
                         );
                 }
                 else
                 {
                     this.pregnantStatus = null;
                 }
             }
         }
         if (this.treatStatus != null)
         {
             if (this.treatStatus.containsPoint(x, y))
             {
                 int daysUntilNextTreat = TreatsController.DaysUntilNextTreat(this._farmAnimal);
                 if (daysUntilNextTreat > 1)
                 {
                     _hoverText.SetValue(DataLoader.i18n.Get("Menu.AnimalQueryMenu.WantsTreatInDays", new { numberOfDays = daysUntilNextTreat }));
                 }
                 else if (daysUntilNextTreat == 1)
                 {
                     _hoverText.SetValue(DataLoader.i18n.Get("Menu.AnimalQueryMenu.WantsTreatTomorrow"));
                 }
                 else
                 {
                     _hoverText.SetValue(DataLoader.i18n.Get("Menu.AnimalQueryMenu.WantsTreat"));
                 }
             }
         }
         if (this.animalContestIndicator != null)
         {
             if (this.animalContestIndicator.containsPoint(x, y))
             {
                 if (AnimalContestController.CanChangeParticipant(this._farmAnimal))
                 {
                     this.animalContestIndicator.scale = Math.Min(4.1f, this.animalContestIndicator.scale + 0.05f);
                     _hoverText.SetValue(DataLoader.i18n.Get("Menu.AnimalQueryMenu.ChangeParticipant"));
                 }
                 else
                 {
                     string messageKey = AnimalContestController.HasWon(this._farmAnimal)
                         ? "Menu.AnimalQueryMenu.Winner"
                         : "Menu.AnimalQueryMenu.ContestParticipant";
                     SDate date = this._farmAnimal.GetDayParticipatedContest();
                     if (date != null)
                     {
                         _hoverText.SetValue(DataLoader.i18n.Get(messageKey, new { contestDate = Utility.getDateStringFor(date.Day, Utility.getSeasonNumber(date.Season), date.Year) }));
                     }
                 }
             }
             else
             {
                 this.animalContestIndicator.scale = Math.Max(4f, this.animalContestIndicator.scale - 0.05f);
             }
         }
     }
 }
Пример #26
0
        /// <summary>Get the custom fields for a crop.</summary>
        /// <param name="crop">The crop to represent.</param>
        /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param>
        private IEnumerable <ICustomField> GetCropFields(Crop crop, bool isSeed)
        {
            if (crop == null)
            {
                yield break;
            }

            var data = new CropDataParser(crop, isPlanted: !isSeed);

            // add next-harvest field
            if (!isSeed)
            {
                // get next harvest
                SDate nextHarvest = data.GetNextHarvest();

                // generate field
                string summary;
                if (data.CanHarvestNow)
                {
                    summary = L10n.Generic.Now();
                }
                else if (!Game1.currentLocation.IsGreenhouse && !data.Seasons.Contains(nextHarvest.Season))
                {
                    summary = L10n.Crop.HarvestTooLate(date: this.Stringify(nextHarvest));
                }
                else
                {
                    summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})";
                }

                yield return(new GenericField(this.GameHelper, L10n.Crop.Harvest(), summary));
            }

            // crop summary
            {
                List <string> summary = new List <string>();

                // harvest
                summary.Add(data.HasMultipleHarvests
                    ? L10n.Crop.SummaryHarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest)
                    : L10n.Crop.SummaryHarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest)
                            );

                // seasons
                summary.Add(L10n.Crop.SummarySeasons(seasons: string.Join(", ", this.Text.GetSeasonNames(data.Seasons))));

                // drops
                if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0)
                {
                    summary.Add(L10n.Crop.SummaryDropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2)));
                }
                else if (crop.minHarvest.Value > 1)
                {
                    summary.Add(L10n.Crop.SummaryDropsX(count: crop.minHarvest.Value));
                }

                // crop sale price
                Item drop = data.GetSampleDrop();
                summary.Add(L10n.Crop.SummarySellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1, this.Text)));

                // generate field
                yield return(new GenericField(this.GameHelper, L10n.Crop.Summary(), "-" + string.Join($"{Environment.NewLine}-", summary)));
            }
        }
Пример #27
0
        /// <summary>Update the current context.</summary>
        /// <param name="contentHelper">The content helper which manages game assets.</param>
        /// <param name="language">The current language.</param>
        /// <param name="date">The current in-game date (if applicable).</param>
        /// <param name="weather">The current in-game weather (if applicable).</param>
        /// <param name="spouse">The current player's internal spouse name (if applicable).</param>
        /// <param name="dayEvent">The day event (e.g. wedding or festival) occurring today (if applicable).</param>
        /// <param name="seenEvents">The event IDs which the player has seen.</param>
        /// <param name="mailFlags">The mail flags set for the player.</param>
        /// <param name="friendships">The current player's friendship details.</param>
        public void UpdateContext(IContentHelper contentHelper, LocalizedContentManager.LanguageCode language, SDate date, Weather?weather, string dayEvent, string spouse, int[] seenEvents, string[] mailFlags, IEnumerable <KeyValuePair <string, Friendship> > friendships)
        {
            this.VerboseLog("Propagating context...");

            // update context
            this.ConditionContext.Set(language: language, date: date, weather: weather, dayEvent: dayEvent, spouse: spouse, seenEvents: seenEvents, mailFlags: mailFlags, friendships: friendships);
            IDictionary <ConditionKey, string> tokenisableConditions = this.ConditionContext.GetSingleValueConditions();

            // update patches
            InvariantHashSet reloadAssetNames = new InvariantHashSet();
            string           prevAssetName    = null;

            foreach (IPatch patch in this.Patches.OrderBy(p => p.AssetName).ThenBy(p => p.LogName))
            {
                // log asset name
                if (this.Verbose && prevAssetName != patch.AssetName)
                {
                    this.VerboseLog($"   {patch.AssetName}:");
                    prevAssetName = patch.AssetName;
                }

                // track old values
                string wasAssetName = patch.AssetName;
                bool   wasApplied   = patch.MatchesContext;

                // update patch
                bool changed     = patch.UpdateContext(this.ConditionContext, tokenisableConditions);
                bool shouldApply = patch.MatchesContext;

                // track patches to reload
                bool reload = (wasApplied && changed) || (!wasApplied && shouldApply);
                if (reload)
                {
                    patch.IsApplied = false;
                    if (wasApplied)
                    {
                        reloadAssetNames.Add(wasAssetName);
                    }
                    if (shouldApply)
                    {
                        reloadAssetNames.Add(patch.AssetName);
                    }
                }

                // log change
                if (this.Verbose)
                {
                    IList <string> changes = new List <string>();
                    if (wasApplied != shouldApply)
                    {
                        changes.Add(shouldApply ? "enabled" : "disabled");
                    }
                    if (wasAssetName != patch.AssetName)
                    {
                        changes.Add($"target: {wasAssetName} => {patch.AssetName}");
                    }
                    string changesStr = string.Join(", ", changes);

                    this.VerboseLog($"      [{(shouldApply ? "X" : " ")}] {patch.LogName}: {(changes.Any() ? changesStr : "OK")}");
                }
            }

            // rebuild asset name lookup
            this.PatchesByCurrentTarget = new InvariantDictionary <HashSet <IPatch> >(
                from patchGroup in this.Patches.GroupBy(p => p.AssetName, StringComparer.InvariantCultureIgnoreCase)
                let key                         = patchGroup.Key
                                      let value = new HashSet <IPatch>(patchGroup)
                                                  select new KeyValuePair <string, HashSet <IPatch> >(key, value)
                );

            // reload assets if needed
            if (reloadAssetNames.Any())
            {
                this.VerboseLog($"   reloading {reloadAssetNames.Count} assets: {string.Join(", ", reloadAssetNames.OrderBy(p => p))}");
                contentHelper.InvalidateCache(asset =>
                {
                    this.VerboseLog($"      [{(reloadAssetNames.Contains(asset.AssetName) ? "X" : " ")}] reload {asset.AssetName}");
                    return(reloadAssetNames.Contains(asset.AssetName));
                });
            }
        }
Пример #28
0
        /// <summary>Get the custom fields for machine output.</summary>
        /// <param name="machine">The machine whose output to represent.</param>
        private IEnumerable <ICustomField> GetMachineOutputFields(SObject machine)
        {
            if (machine == null)
            {
                yield break;
            }

            SObject heldObj     = machine.heldObject.Value;
            int     minutesLeft = machine.MinutesUntilReady;

            // cask
            if (machine is Cask cask)
            {
                // output item
                if (heldObj != null)
                {
                    ItemQuality curQuality = (ItemQuality)heldObj.Quality;

                    // calculate aging schedule
                    float effectiveAge = this.Constants.CaskAgeSchedule.Values.Max() - cask.daysToMature.Value;
                    var   schedule     =
                        (
                            from entry in this.Constants.CaskAgeSchedule
                            let quality = entry.Key
                                          let baseDays = entry.Value
                                                         where baseDays > effectiveAge
                                                         orderby baseDays ascending
                                                         let daysLeft = (int)Math.Ceiling((baseDays - effectiveAge) / cask.agingRate.Value)
                                                                        select new
                    {
                        Quality = quality,
                        DaysLeft = daysLeft,
                        HarvestDate = SDate.Now().AddDays(daysLeft)
                    }
                        )
                        .ToArray();

                    // display fields
                    yield return(new ItemIconField(this.GameHelper, L10n.Item.Contents(), heldObj));

                    if (minutesLeft <= 0 || !schedule.Any())
                    {
                        yield return(new GenericField(this.GameHelper, L10n.Item.CaskSchedule(), L10n.Item.CaskScheduleNow(quality: curQuality)));
                    }
                    else
                    {
                        string scheduleStr = string.Join(Environment.NewLine, (
                                                             from entry in schedule
                                                             let str = this.Text.GetPlural(entry.DaysLeft, L10n.Item.CaskScheduleTomorrow(quality: entry.Quality), L10n.Item.CaskScheduleInXDays(quality: entry.Quality, count: entry.DaysLeft, date: entry.HarvestDate))
                                                                       select $"-{str}"
                                                             ));
                        yield return(new GenericField(this.GameHelper, L10n.Item.CaskSchedule(), $"{L10n.Item.CaskSchedulePartial(quality: curQuality)}{Environment.NewLine}{scheduleStr}"));
                    }
                }
            }

            // crab pot
            else if (machine is CrabPot pot)
            {
                // bait
                if (heldObj == null)
                {
                    if (pot.bait.Value != null)
                    {
                        yield return(new ItemIconField(this.GameHelper, L10n.Item.CrabpotBait(), pot.bait.Value));
                    }
                    else if (Game1.player.professions.Contains(11)) // no bait needed if luremaster
                    {
                        yield return(new GenericField(this.GameHelper, L10n.Item.CrabpotBait(), L10n.Item.CrabpotBaitNotNeeded()));
                    }
                    else
                    {
                        yield return(new GenericField(this.GameHelper, L10n.Item.CrabpotBait(), L10n.Item.CrabpotBaitNeeded()));
                    }
                }

                // output item
                if (heldObj != null)
                {
                    string summary = L10n.Item.ContentsReady(name: heldObj.DisplayName);
                    yield return(new ItemIconField(this.GameHelper, L10n.Item.Contents(), heldObj, summary));
                }
            }

            // furniture
            else if (machine is Furniture)
            {
                // displayed item
                if (heldObj != null)
                {
                    string summary = L10n.Item.ContentsPlaced(name: heldObj.DisplayName);
                    yield return(new ItemIconField(this.GameHelper, L10n.Item.Contents(), heldObj, summary));
                }
            }

            // auto-grabber
            else if (machine.ParentSheetIndex == Constant.ObjectIndexes.AutoGrabber)
            {
                string readyText = this.Text.Stringify(heldObj is Chest output && output.items.Any());
                yield return(new GenericField(this.GameHelper, L10n.Item.Contents(), readyText));
            }

            // generic machine
            else
            {
                // output item
                if (heldObj != null)
                {
                    string summary = minutesLeft <= 0
                    ? L10n.Item.ContentsReady(name: heldObj.DisplayName)
                    : L10n.Item.ContentsPartial(name: heldObj.DisplayName, time: this.Stringify(TimeSpan.FromMinutes(minutesLeft)));
                    yield return(new ItemIconField(this.GameHelper, L10n.Item.Contents(), heldObj, summary));
                }
            }
        }
Пример #29
0
 public static void SetLastDayFeedTreat(this Character character, SDate value)
 {
     SetKey(character, LastDayFeedTreatKey, value);
 }
Пример #30
0
        public void PickForageObject(TerrainFeature source)
        {
            int skill   = this.ForagingLevel;
            int quality = 0;

            if (skill >= 8 && this.r.NextDouble() < .05f)
            {
                quality = 4;
            }
            else if (skill >= 6 && this.r.NextDouble() < 0.2f)
            {
                quality = 2;
            }
            else if (skill >= 2 && this.r.NextDouble() < 0.55f)
            {
                quality = 1;
            }

            GameLocation location     = this.Forager.currentLocation;
            string       locationName = location.Name;
            string       season       = Game1.currentSeason;
            int          objectIndex  = -1;

            if (source != null && source is Tree tree && tree.growthStage.Value >= Tree.treeStage)
            {
                if (season == "winter" || this.ForagingLevel < 1)
                {
                    return;
                }

                switch (tree.treeType.Value)
                {
                case Tree.bushyTree:
                    objectIndex = 309;
                    break;

                case Tree.leafyTree:
                    objectIndex = 310;
                    break;

                case Tree.pineTree:
                    objectIndex = 311;
                    break;
                }

                if (season == "fall" && tree.treeType.Value == Tree.leafyTree && SDate.Now().Day >= 14)
                {
                    objectIndex = 408;
                }

                if (objectIndex != -1)
                {
                    this.SaveForage(new SObject(objectIndex, 1, false, -1, quality));
                }

                return;
            }

            if (source != null && source is Bush bush)
            {
                if (this.ForagingLevel > 5 && this.r.NextDouble() < 0.005)
                {
                    // There is a chance <1% to get a rare forage item
                    this.SaveForage(new SObject(this.FetchForage("rare"), 1, false, -1, 0));
                    return;
                }

                if (BushIsInBloom(bush))
                {
                    objectIndex = 296;

                    if (season == "fall")
                    {
                        objectIndex = 410;
                    }
                    if (bush.size.Value == 3)
                    {
                        objectIndex = 815;
                    }

                    this.SaveForage(new SObject(objectIndex, 1, false, -1, quality));
                    return;
                }
            }

            if (location is Farm)
            {
                var farmForages = new List <int>();

                farmForages.AddRange(this.GetForageSheet(season, "Farm"));
                farmForages.AddRange(this.GetForageSheet(season, $"farmType_{Farm.getMapNameFromTypeInt(Game1.whichFarm)}"));

                objectIndex = this.FetchForage(farmForages.Distinct().ToArray());
            }
            else if (location is MineShaft)
            {
                objectIndex = this.FetchForage("cave");
            }
            else
            {
                objectIndex = this.FetchGeneralForage(season, locationName);
            }

            if (objectIndex != -1)
            {
                this.SaveForage(new SObject(objectIndex, 1, false, -1, quality));
            }
        }
Пример #31
0
        /// <summary>
        /// New CommercialFrame
        /// </summary>
        /// <param name="FrameID">FrameID</param>
        /// <param name="Flags">Frame Flags</param>
        /// <param name="Data">Data of frame</param>
        /// <param name="Length">MaxLength of frame</param>
        internal CommercialFrame(string FrameID, FrameFlags Flags, FileStreamEx Data, int Length)
            : base(FrameID, Flags)
        {
            _TextEncoding = (TextEncodings)Data.ReadByte();
            Length--;
            if (!IsValidEnumValue(_TextEncoding, ValidatingErrorTypes.ID3Error))
                return;

            _Price = new Price(Data, Length);
            Length -= _Price.Length;

            _ValidUntil = new SDate(Data);
            Length -= 8;


            _ContactUrl = Data.ReadText(Length, TextEncodings.Ascii, ref Length, true);

            _RecievedAs = (RecievedAsEnum)Data.ReadByte();
            Length--;

            _SellerName = Data.ReadText(Length, _TextEncoding, ref Length, true);

            _Description = Data.ReadText(Length, _TextEncoding, ref Length, true);

            if (Length < 1) // Data finished
                return;

            _MIMEType = Data.ReadText(Length, TextEncodings.Ascii, ref Length, true);

            _Data = Data.ReadData(Length);
        }
Пример #32
0
 ["Days"] = (valueToCheck, _) => Utility.parseStringToIntArray(valueToCheck).Any(d => d == SDate.Now().Day),
Пример #33
0
        /// <summary>
        /// Create new OwnershipFrame
        /// </summary>
        /// <param name="FrameID">4 Characters tag identifier</param>
        /// <param name="Flags">2 Bytes flags identifier</param>
        /// <param name="Data">Contain Data for this frame</param>
        internal OwnershipFrame(string FrameID, FrameFlags Flags, FileStreamEx Data, int Length)
            : base(FrameID, Flags)
        {
            TextEncoding = (TextEncodings)Data.ReadByte();
            Length--;
            if (!IsValidEnumValue(TextEncoding, ValidatingErrorTypes.ID3Error))
                return;

            _Price = new Price(Data, Length);
            Length -= _Price.Length;
            if (!_Price.IsValid)
            {
                ErrorOccur("Price is not valid value. ownership frame will not read", true);
                return;
            }

            if (Length >= 8)
            {
                _DateOfPurch = new SDate(Data);
                Length -= 8;
            }
            else
            {
                ErrorOccur("Date is not valid for this frame", true);
                return;
            }

            Seller = Data.ReadText(Length, TextEncoding);
        }
Пример #34
0
        private void Input_ButtonPressed(object sender, ButtonPressedEventArgs e)
        {
            if (!Context.IsWorldReady || !Context.IsPlayerFree || Game1.activeClickableMenu != null ||
                !e.Button.IsActionButton() && e.Button != SButton.ControllerA)
            {
                return;
            }

            var property = Game1.currentLocation.doesTileHaveProperty((int)e.Cursor.GrabTile.X,
                                                                      (int)e.Cursor.GrabTile.Y, "Action", "Buildings");

            switch (property)
            {
            case "Buy General":
                if (_config.Pierre && (_config.ShopsAlwaysOpen || IsNpcInLocation("Pierre")))
                {
                    Helper.Input.Suppress(e.Button);
                    Game1.activeClickableMenu =
                        new ShopMenu(((SeedShop)Game1.currentLocation).shopStock(), 0, "Pierre");
                }
                break;

            case "Carpenter":
                if (_config.Carpenter)
                {
                    if (_config.ShopsAlwaysOpen)
                    {
                        Carpenters();
                    }
                    else
                    {
                        NPC robin;
                        if (Game1.currentLocation.characters.Find("Robin") is NPC npc)
                        {
                            robin = npc;
                        }
                        else
                        {
                            break;
                        }
                        var carpenters   = Helper.Reflection.GetMethod(Game1.currentLocation, "carpenters");
                        var tileLocation = robin.getTileLocation();
                        carpenters.Invoke(new Location((int)tileLocation.X, (int)tileLocation.Y));
                    }
                    Helper.Input.Suppress(e.Button);
                }
                break;

            case "AnimalShop":
                if (_config.Ranch)
                {
                    if (_config.ShopsAlwaysOpen)
                    {
                        AnimalShop();
                    }
                    else
                    {
                        NPC marnie;
                        if (Game1.currentLocation.characters.Find("Marnie") is NPC npc)
                        {
                            marnie = npc;
                        }
                        else
                        {
                            break;
                        }
                        var animalShop   = Helper.Reflection.GetMethod(Game1.currentLocation, "animalShop");
                        var tileLocation = marnie.getTileLocation();
                        animalShop.Invoke(new Location((int)tileLocation.X, (int)tileLocation.Y + 1));
                    }
                    Helper.Input.Suppress(e.Button);
                }
                break;

            case "Buy Fish":
                if (_config.FishShop &&
                    (_config.ShopsAlwaysOpen || IsNpcInLocation("Willy") || IsNpcInLocation("Willy", "Beach")))
                {
                    Helper.Input.Suppress(e.Button);
                    Game1.activeClickableMenu = new ShopMenu(Utility.getFishShopStock(Game1.player), 0, "Willy");
                }
                break;

            case "Blacksmith":
                if (_config.Blacksmith)
                {
                    if (_config.ShopsAlwaysOpen)
                    {
                        Blacksmith(Game1.getCharacterFromName("Clint"));
                    }
                    else
                    {
                        NPC clint;
                        if (Game1.currentLocation.characters.Find("Clint") is NPC npc)
                        {
                            clint = npc;
                        }
                        else
                        {
                            break;
                        }
                        Blacksmith(clint);
                    }
                    Helper.Input.Suppress(e.Button);
                }
                break;

            case "IceCreamStand":
                if (_config.IceCreamStand &&
                    (_config.ShopsAlwaysOpen || _config.IceCreamInAllSeasons || SDate.Now().Season == "summer"))
                {
                    var d = new Dictionary <Item, int[]>
                    {
                        { new Object(233, 1), new[] { 250, int.MaxValue } }
                    };
                    Game1.activeClickableMenu = new ShopMenu(d);
                    Helper.Input.Suppress(e.Button);
                }
                break;

            default:
                break;
            }
        }