NextDoublePositive() публичный Метод

Returns a pseudo-random number greater than 0.0 and less than 1.0.
public NextDoublePositive ( ) : Double
Результат Double
        public Solution[] GeneratePopulation(ExperimentParameters experimentParameters)
        {
            var basePopulationSize = experimentParameters.BasePopulationSize;
            var population         = new Solution[basePopulationSize];

            for (var i = 0; i < basePopulationSize; i++)
            {
                population[i] = new Solution(experimentParameters);

                var lenght = population[i].ObjectCoefficients.Length;

                for (var j = 0; j < lenght; j++)
                {
                    population[i].ObjectCoefficients[j]        = _randomGenerator.NextDouble();
                    population[i].StdDeviationsCoefficients[j] = _randomGenerator.NextDoublePositive();
                }

                lenght = population[i].RotationsCoefficients.Length;

                for (var j = 0; j < lenght; j++)
                {
                    population[i].RotationsCoefficients[j] = _randomGenerator.NextDoublePositive();
                }
            }

            return(population);
        }
Пример #2
0
 public void UpdateForBloodMoon()
 {
     if (CurrentPhase() == MoonPhase.FullMoon && Dice.NextDoublePositive() <= ModConfig.BadMoonRising && !Game1.isFestival() && !Game1.weddingToday && ModConfig.HazardousMoonEvents)
     {
         IsBloodMoon = true;
         DoBloodMoonAlert();
         Game1.currentLocation.waterColor.Value = BloodMoonWater;
         LunarDisturbances.ContentManager.InvalidateCache("LooseSprites/Cursors");
     }
 }
Пример #3
0
        /// <summary>
        /// This function grabs events when the menu changes to handle dialogue replace
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">paramaters</param>
        private void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e)
        {
            if (GameClimate is null)
            {
                Monitor.Log("GameClimate is null");
            }
            if (e.NewMenu is null)
            {
                Monitor.Log("e.NewMenu is null");
            }

            if (e.NewMenu is DialogueBox box)
            {
                bool          stormDialogue = false;
                double        odds = Dice.NextDoublePositive(), stormOdds = GameClimate.GetStormOdds(SDate.Now().AddDays(1), Dice, DebugOutput);
                List <string> lines = Helper.Reflection.GetField <List <string> >(box, "dialogues").GetValue();
                if (lines.FirstOrDefault() == Game1.content.LoadString("Strings\\StringsFromCSFiles:Object.cs.12822"))
                {
                    if (WeatherOpt.Verbose)
                    {
                        Monitor.Log($"Rain totem interception firing with roll {odds.ToString("N3")} vs. odds {stormOdds.ToString("N3")}");
                    }

                    // rain totem used, do your thing
                    if (WeatherOpt.StormTotemChange)
                    {
                        if (odds <= stormOdds)
                        {
                            if (WeatherOpt.Verbose)
                            {
                                Monitor.Log("Replacing rain with storm..");
                            }

                            Game1.weatherForTomorrow = Game1.weather_lightning;
                            stormDialogue            = true;
                        }
                    }

                    // change dialogue text
                    lines.Clear();
                    if (stormDialogue)
                    {
                        lines.Add(Helper.Translation.Get("hud-text.desc_stormtotem"));
                    }
                    else
                    {
                        lines.Add(Game1.content.LoadString("Strings\\StringsFromCSFiles:Object.cs.12822"));
                    }
                }
            }
        }
Пример #4
0
        /// <summary>Raised after a game menu is opened, closed, or replaced.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnMenuChanged(object sender, MenuChangedEventArgs e)
        {
            if (!Context.IsMainPlayer)
            {
                return;
            }

            // restore previous menu on close
            if (e.OldMenu is WeatherMenu && this.PreviousMenu != null)
            {
                Game1.activeClickableMenu = this.PreviousMenu;
                this.PreviousMenu         = null;
            }

            // bandle new dialogue box
            else if (e.NewMenu is DialogueBox box)
            {
                bool          stormDialogue = false;
                double        odds = Dice.NextDoublePositive(), stormOdds = GameClimate.GetStormOdds(SDate.Now().AddDays(1), Dice);
                List <string> lines = Helper.Reflection.GetField <List <string> >(box, "dialogues").GetValue();
                if (lines.FirstOrDefault() == Game1.content.LoadString("Strings\\StringsFromCSFiles:Object.cs.12822"))
                {
                    if (WeatherOpt.Verbose)
                    {
                        Monitor.Log($"Rain totem interception firing with roll {odds:N3} vs. odds {stormOdds:N3}");
                    }

                    // rain totem used, do your thing
                    if (WeatherOpt.StormTotemChange)
                    {
                        if (odds <= stormOdds)
                        {
                            if (WeatherOpt.Verbose)
                            {
                                Monitor.Log("Replacing rain with storm..");
                            }

                            Game1.netWorldState.Value.WeatherForTomorrow = Game1.weatherForTomorrow = Game1.weather_lightning;
                            stormDialogue = true;
                        }
                    }

                    // change dialogue text
                    lines.Clear();
                    lines.Add(stormDialogue
                        ? Helper.Translation.Get("hud-text.desc_stormtotem")
                        : Game1.content.LoadString("Strings\\StringsFromCSFiles:Object.cs.12822"));
                }
            }
        }
        public Solution Mutate(Solution solution)
        {
            solution.OneStepStdDeviation *= Math.Exp(IndividualLearningRate * _randomGenerator.NextDoublePositive());
            solution.OneStepStdDeviation  = solution.OneStepStdDeviation < StepThreshold ? StepThreshold : solution.OneStepStdDeviation;

            return(solution);
        }
Пример #6
0
        internal static void SetWeatherNonSystemForTomorrow(MersenneTwister Dice, FerngillClimate GameClimate, double rainDays, double stormDays, double windyDays, RangePair TmrwTemps)
        {
            ProbabilityDistribution <string> WeatherDist = new ProbabilityDistribution <string>("sunny");

            WeatherDist.AddNewEndPoint(rainDays, "rain");
            if (ClimatesOfFerngill.WeatherOpt.DisableHighRainWind)
            {
                WeatherDist.AddNewCappedEndPoint(windyDays, "debris");
            }

            double distOdd = Dice.NextDoublePositive();

            if (ClimatesOfFerngill.WeatherOpt.Verbose)
            {
                ClimatesOfFerngill.Logger.Log(WeatherDist.ToString());
                ClimatesOfFerngill.Logger.Log($"Distribution odds is {distOdd}");
            }

            if (!(WeatherDist.GetEntryFromProb(distOdd, out string Result)))
            {
                Result = "sunny";
                ClimatesOfFerngill.Logger.Log("The weather has failed to process in some manner. Falling back to [sunny]", LogLevel.Info);
            }

            if (ClimatesOfFerngill.WeatherOpt.Verbose)
            {
                ClimatesOfFerngill.Logger.Log($"Weather result is {Result}");
            }

            SetWeatherTomorrow(Result, Dice, GameClimate, stormDays, TmrwTemps);
        }
Пример #7
0
        public MoonPhase GetLunarPhase()
        {
            //divide it by the cycle.
            int currentDay = GetDayOfCycle(SDate.Now());

            MoonPhase ret = SDVMoon.GetLunarPhase(currentDay);

            if (ret == MoonPhase.FullMoon)
            {
                if (Dice.NextDoublePositive() <= ModConfig.BadMoonRising)
                {
                    return(MoonPhase.BloodMoon);
                }
            }

            return(ret);
        }
Пример #8
0
        internal static void SetWeatherTomorrow(string Result, MersenneTwister Dice, FerngillClimate GameClimate, double stormOdds, RangePair TmrwTemps)
        {
            //now parse the result.
            if (Result == "rain")
            {
                SDVUtilities.SetWeather(Game1.weather_rain);

                if (Game1.currentSeason == "winter")
                {
                    SDVUtilities.SetWeather(Game1.weather_snow);

                    if (GameClimate.AllowRainInWinter && ClimatesOfFerngill.Conditions.TomorrowHigh >= -2.5)
                    {
                        SDVUtilities.SetWeather(Game1.weather_rain);
                    }
                }

                //Moved from the *wrong function and logic gate*
                //snow applies first
                if (WeatherConditions.IsValidWeatherForSnow(TmrwTemps) && Game1.currentSeason != "spring")
                {
                    if (ClimatesOfFerngill.WeatherOpt.Verbose)
                    {
                        ClimatesOfFerngill.Logger.Log($"Snow is enabled, with the High for the day being: {TmrwTemps.HigherBound}" +
                                                      $" and the calculated midpoint temperature being {TmrwTemps.GetMidPoint()}");
                    }

                    SDVUtilities.SetWeather(Game1.weather_snow);
                }

                //apply lightning logic.
                if (Dice.NextDoublePositive() >= stormOdds && Game1.weatherForTomorrow == Game1.weather_rain)
                {
                    SDVUtilities.SetWeather(Game1.weather_lightning);
                    if (SDate.Now().Year == 1 && SDate.Now().Season == "spring" && !ClimatesOfFerngill.WeatherOpt.AllowStormsSpringYear1)
                    {
                        SDVUtilities.SetWeather(Game1.weather_rain);
                    }
                }

                //tracking time! - Snow fall on Fall 28, if the flag is set.
                if (Game1.dayOfMonth == 28 && Game1.currentSeason == "fall" && ClimatesOfFerngill.WeatherOpt.SnowOnFall28)
                {
                    ClimatesOfFerngill.Conditions.ForceTodayTemps(2, -1);
                    SDVUtilities.SetWeather(Game1.weather_snow);
                }
            }

            if (Result == "debris")
            {
                SDVUtilities.SetWeather(Game1.weather_debris);
            }

            if (Result == "sunny")
            {
                SDVUtilities.SetWeather(Game1.weather_sunny);
            }
        }
Пример #9
0
        /// <summary>
        /// Returns an item in range between Lower and Higher Bound
        /// </summary>
        /// <param name="d">The random object</param>
        /// <returns>Number in range</returns>
        public double RollInRange(MersenneTwister d)
        {
            if (HigherBound == LowerBound)
            {
                return(LowerBound);
            }

            return(d.NextDoublePositive() * (HigherBound - LowerBound) + LowerBound);
        }
Пример #10
0
        public MoonPhase GetLunarPhase()
        {
            //divide it by the cycle.
            int currentCycle = (int)Math.Floor(SDate.Now().DaysSinceStart / (double)cycleLength);
            int currentDay   = GetDayOfCycle(SDate.Now());

            MoonPhase ret = SDVMoon.GetLunarPhase(currentDay);

            if (ret == MoonPhase.FullMoon)
            {
                if (Dice.NextDoublePositive() <= ModConfig.BadMoonRising)
                {
                    return(MoonPhase.BloodMoon);
                }
            }

            return(ret);
        }
Пример #11
0
        public Solution Mutate(Solution solution)
        {
            var numberOfCoefficients = solution.ObjectCoefficients.Length;

            for (var i = 0; i < numberOfCoefficients; i++)
            {
                solution.ObjectCoefficients[i] += solution.OneStepStdDeviation * _randomGenerator.NextDoublePositive();
            }

            return(solution);
        }
        /// <summary>Raised after a game menu is opened, closed, or replaced.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnMenuChanged(object sender, MenuChangedEventArgs e)
        {
            if (!Context.IsMainPlayer)
            {
                return;
            }

            // restore previous menu on close
            if (e.OldMenu is WeatherMenu && this.PreviousMenu != null)
            {
                Game1.activeClickableMenu = this.PreviousMenu;
                this.PreviousMenu         = null;
            }

            // handle new dialogue box
            else if (e.NewMenu is DialogueBox box)
            {
                double odds = Dice.NextDoublePositive(), stormOdds = GameClimate.GetStormOdds(SDate.Now().AddDays(1), Dice);
                WeatherProcessing.HandleStormTotemInterception(box, odds, stormOdds);
            }
        }
        protected virtual Solution GenerateCoefficients(Solution solution)
        {
            var lenght = solution.ObjectCoefficients.Length;

            for (var i = 0; i < lenght; i++)
            {
                solution.ObjectCoefficients[i] = RandomGenerator.NextDouble();
            }

            solution.OneStepStdDeviation = RandomGenerator.NextDoublePositive();

            return(solution);
        }
        public Solution Mutate(Solution solution)
        {
            var vectorSize = solution.RotationsCoefficients.Length;

            //for (var i = 0; i < vectorSize; i++)
            //{
            //    for (var j = i + 1; j < vectorSize; j++)
            //    {
            //        //var mutationValue = RotationAngle * MersenneTwister.Instance.NextDoublePositive();
            //        var mutationValue = RotationAngle * _randomGenerator.NextDoublePositive();
            //        //var mutationValue = RotationAngle * 0.5;

            //        solution.RotationsCoefficients[i][j] += mutationValue;
            //        solution.RotationsCoefficients[j][i] += mutationValue;

            //        if (Math.Abs(solution.RotationsCoefficients[i][j]) > Math.PI)
            //        {
            //            var reduction = 2 * Math.PI * Math.Sign(solution.RotationsCoefficients[i][j]);

            //            solution.RotationsCoefficients[i][j] -= reduction;
            //            solution.RotationsCoefficients[j][i] -= reduction;
            //        }
            //    }
            //}

            for (var i = 0; i < vectorSize; i++)
            {
                //var mutationValue = RotationAngle * MersenneTwister.Instance.NextDoublePositive();
                var mutationValue = RotationAngle * _randomGenerator.NextDoublePositive();
                //var mutationValue = RotationAngle * 0.5;

                solution.RotationsCoefficients[i] += mutationValue;

                if (!(Math.Abs(solution.RotationsCoefficients[i]) > Math.PI))
                {
                    continue;
                }
                var reduction = 2 * Math.PI * Math.Sign(solution.RotationsCoefficients[i]);

                solution.RotationsCoefficients[i] -= reduction;
            }

            return(solution);
        }
Пример #15
0
 public static double drand()
 {
     return(gen.NextDoublePositive());
 }
Пример #16
0
        public int TenMinuteTick(WeatherConditions conditions, int ticksOutside, int ticksTotal, MersenneTwister Dice)
        {
            double amtOutside = ticksOutside / (double)ticksTotal, totalMulti = 0;
            int    staminaAffect = 0;
            int    sickReason    = 0;
            var    condList      = new List <string>();

            /* if (Config.Verbose)
             *   Monitor.Log($"Ticks: {ticksOutside}/{ticksTotal} with percentage {amtOutside.ToString("N3")} against" +
             *       $" target {Config.AffectedOutside}"); */

            //Logic: At all times, if the today danger is not null, we should consider processing.
            //However: If it's frost, only at night. If it's a heatwave, only during the day.
            //So this means: if it's storming, you can get sick. If it's a blizzard or thundersnow.. you can get sick
            //If it's frost or heatwave during the appropriate time.. you can get sick

            //First, update the sick status
            bool   farmerCaughtCold = false;
            double sickOdds         = Config.ChanceOfGettingSick - Game1.dailyLuck;

            //weee.
            if (Game1.player.hat?.which == 28 && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Lightning))
            {
                sickOdds -= (Dice.NextDoublePositive() / 5.0) - .1;
            }

            if (Game1.player.hat?.which == 25 && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Blizzard))
            {
                sickOdds -= .22;
            }

            if (Game1.player.hat?.which == 4 && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Heatwave) && !SDVTime.IsNight)
            {
                sickOdds -= .11;
            }

            farmerCaughtCold = (Dice.NextDoublePositive() <= sickOdds);

            if (amtOutside >= Config.AffectedOutside && farmerCaughtCold || this.FarmerSick)
            {
                //check if it's a valid condition
                if (FarmerCanGetSick())
                {
                    if (conditions.GetCurrentConditions().HasAnyFlags(CurrentWeather.Blizzard | CurrentWeather.Lightning) || (conditions.GetCurrentConditions().HasFlag(CurrentWeather.Frost) && SDVTime.IsNight) | (conditions.GetCurrentConditions().HasFlag(CurrentWeather.Heatwave) && !SDVTime.IsNight))
                    {
                        if ((conditions.GetCurrentConditions().HasFlag(CurrentWeather.Heatwave) && !SDVTime.IsNight))
                        {
                            sickReason = HEATWAVE;
                        }
                        else if (conditions.GetCurrentConditions().HasFlag(CurrentWeather.Frost) && SDVTime.IsNight)
                        {
                            sickReason = FROST;
                        }

                        this.MakeSick(sickReason);
                    }
                }

                //test status

                /*if (Config.Verbose)
                 *  Monitor.Log($"Status update. Farmer Sick: {FarmerSick} and Valid Conditions: {conditions.GetCurrentConditions().HasAnyFlags(CurrentWeather.Blizzard | CurrentWeather.Lightning) || (conditions.GetCurrentConditions().HasFlag(CurrentWeather.Frost) && SDVTime.IsNight) | (conditions.GetCurrentConditions().HasFlag(CurrentWeather.Heatwave) && !SDVTime.IsNight)}"); */

                //now that we've done that, go through the various conditions
                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Lightning))
                {
                    totalMulti += 1;
                    condList.Add("Lightning or Thundersnow");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Fog))
                {
                    totalMulti += .5;
                    condList.Add("Fog");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Fog) && SDVTime.IsNight)
                {
                    totalMulti += .25;
                    condList.Add("Night Fog");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Blizzard) && !conditions.GetCurrentConditions().HasFlag(CurrentWeather.WhiteOut))
                {
                    totalMulti += 1.25;
                    condList.Add("Blizzard");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Blizzard) && conditions.GetCurrentConditions().HasFlag(CurrentWeather.WhiteOut))
                {
                    totalMulti += 2.25;
                    condList.Add("White Out");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Frost) && SDVTime.IsNight)
                {
                    totalMulti += 1.25;
                    condList.Add("Night Frost");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasAllFlags(CurrentWeather.Lightning | CurrentWeather.Snow) && SDVTime.IsNight)
                {
                    totalMulti += .5;
                    condList.Add("Night Thundersnow");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Blizzard) && SDVTime.IsNight)
                {
                    totalMulti += .5;
                    condList.Add("Night Blizzard");
                }

                if (this.FarmerSick && conditions.GetCurrentConditions().HasFlag(CurrentWeather.Heatwave) && !SDVTime.IsNight)
                {
                    totalMulti += 1.25;
                    condList.Add("Day Heatwave");
                }
            }


            staminaAffect -= (int)Math.Floor(Config.StaminaDrain * totalMulti);

            if (Config.Verbose && this.FarmerSick)
            {
                string condString = "[ ";
                for (int i = 0; i < condList.Count; i++)
                {
                    if (i != condList.Count - 1)
                    {
                        condString += condList[i] + ", ";
                    }
                    else
                    {
                        condString += condList[i];
                    }
                }
                condString += " ]";

                /*
                 * Monitor.Log($"[{Game1.timeOfDay}] Conditions for the drain are {condString} for a total multipler of {totalMulti} for a total drain of {staminaAffect}"); */
            }

            return(staminaAffect);
        }
Пример #17
0
        internal bool TestForSpecialWeather(FerngillClimateTimeSpan ClimateForDay)
        {
            bool specialWeatherTriggered = false;
            // Conditions: Blizzard - occurs in weather_snow in "winter"
            //             Dry Lightning - occurs if it's sunny in any season if temps exceed 25C.
            //             Frost and Heatwave check against the configuration.
            //             Thundersnow  - as Blizzard, but really rare.
            //             Fog - per climate, although night fog in winter is double normal chance
            GenerateEveningFog = (Dice.NextDouble() < ClimateForDay.EveningFogChance * ClimateForDay.RetrieveOdds(Dice,"fog",Game1.dayOfMonth)) && !this.GetCurrentConditions().HasFlag(CurrentWeather.Wind);

            bool blockFog = ClimatesOfFerngill.MoonAPI != null && ClimatesOfFerngill.MoonAPI.IsSolarEclipse();

            if (blockFog)
                GenerateEveningFog = false;
            
            double fogRoll = Dice.NextDoublePositive();
           
            if (fogRoll < ClimateForDay.RetrieveOdds(Dice, "fog", Game1.dayOfMonth) && !this.GetCurrentConditions().HasFlag(CurrentWeather.Wind) && !blockFog)
            {
                this.CreateWeather("Fog");

                if (ModConfig.Verbose)
                    Monitor.Log($"{FogDescription(fogRoll, ClimateForDay.RetrieveOdds(Dice, "fog", Game1.dayOfMonth))}");

                specialWeatherTriggered = true;
            }

            if (this.HasWeather(CurrentWeather.Snow))
            {
                double blizRoll = Dice.NextDoublePositive();
                if (blizRoll <= ModConfig.BlizzardOdds)
                {
                    this.CreateWeather("Blizzard");
                    if (ModConfig.Verbose)
                        Monitor.Log($"With roll {blizRoll:N3} against {ModConfig.BlizzardOdds}, there will be blizzards today");
                    if (Dice.NextDoublePositive() < .05 && ModConfig.HazardousWeather)
                    {
                        this.CreateWeather("WhiteOut");
                    }
                }

                specialWeatherTriggered = true;
            }

            //Dry Lightning is also here for such like the dry and arid climates 
            //  which have so low rain chances they may never storm.
            if (this.HasWeather(CurrentWeather.Snow))
            {
                double oddsRoll = Dice.NextDoublePositive();

                if (oddsRoll <= ModConfig.ThundersnowOdds)
                {
                    this.AddWeather(CurrentWeather.Lightning);
                    if (ModConfig.Verbose)
                        Monitor.Log($"With roll {oddsRoll:N3} against {ModConfig.ThundersnowOdds}, there will be thundersnow today");

                    specialWeatherTriggered = true;
                }
            }

            if (!(this.HasPrecip()))
            {
                double oddsRoll = Dice.NextDoublePositive();

                if (oddsRoll <= ModConfig.DryLightning && this.TodayHigh >= ModConfig.DryLightningMinTemp &&
                    !this.CurrentConditionsN.HasFlag(CurrentWeather.Frost))
                {
                    this.AddWeather(CurrentWeather.Lightning);
                    if (ModConfig.Verbose)
                        Monitor.Log($"With roll {oddsRoll:N3} against {ModConfig.DryLightning}, there will be dry lightning today.");

                    specialWeatherTriggered = true;
                }

                if (this.TodayHigh > ModConfig.TooHotOutside && ModConfig.HazardousWeather)
                {
                    this.AddWeather(CurrentWeather.Heatwave);
                    specialWeatherTriggered = true;
                }
            }

            if (this.TodayLow < ModConfig.TooColdOutside && !Game1.IsWinter)
            {
                if (ModConfig.HazardousWeather)
                {
                    this.AddWeather(CurrentWeather.Frost);
                    specialWeatherTriggered = true;
                }
            }

            //test for spring conversion.- 50% chance
            if (this.HasWeather(CurrentWeather.Rain) && this.HasWeather(CurrentWeather.Frost) && Game1.currentSeason == "spring" && Dice.NextDoublePositive() <= .5)
            {
                CurrentConditionsN.RemoveFlags(CurrentWeather.Rain);
                CurrentConditionsN |= CurrentWeather.Snow;
                Game1.isRaining = false;
                Game1.isSnowing = true;
                specialWeatherTriggered = true;
            }

            //and finally, test for thunder frenzy
            if (this.HasWeather(CurrentWeather.Lightning) && this.HasWeather(CurrentWeather.Rain) && ModConfig.HazardousWeather)
            {
                double oddsRoll = Dice.NextDouble();
                if (oddsRoll < ModConfig.ThunderFrenzyOdds)
                {
                    this.AddWeather(CurrentWeather.ThunderFrenzy);
                    specialWeatherTriggered = true;
                    if (ModConfig.Verbose)
                        Monitor.Log($"With roll {oddsRoll:N3} against {ModConfig.ThunderFrenzyOdds}, there will be a thunder frenzy today");
                    this.CreateWeather("ThunderFrenzy");
                }
            }

            return specialWeatherTriggered;
        }
Пример #18
0
        public Solution Mutate(Solution solution)
        {
            var numberOfCoefficients = solution.StdDeviationsCoefficients.Length;

            for (var j = 0; j < numberOfCoefficients; j++)
            {
                solution.StdDeviationsCoefficients[j] *= Math.Exp(IndividualLearningRate * _randomGenerator.NextDoublePositive() + GlobalLearningRate * _randomGenerator.NextDoublePositive());
                solution.StdDeviationsCoefficients[j]  = solution.StdDeviationsCoefficients[j] < StepThreshold ? StepThreshold : solution.StdDeviationsCoefficients[j];
            }

            return(solution);
        }
Пример #19
0
        private void HandleMessageReceived(IAsyncResult result)
        {
            if (serverSocket != null)
            {
                try
                {
#if DEBUG
                    if (SimulatedPacketLossRate > 0.0 && (randomGenerator.NextDoublePositive() <= SimulatedPacketLossRate))
                    {
                        NeutrinoConfig.LogWarning("SIMULATING PACKET LOSS!");
                        receivedEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        IAsyncResult asyncResult = serverSocket.BeginReceiveFrom(receiveBuffer, 0, NeutrinoConfig.MaxMessageSize, SocketFlags.None, ref receivedEndPoint, new AsyncCallback(HandleMessageReceived), null);
                        if (asyncResult.CompletedSynchronously)
                        {
                            HandleMessageReceived(asyncResult);
                        }
                        return;
                    }
                    else if (SimulatedPacketShuffleRate > 0.0 && (randomGenerator.NextDoublePositive() <= SimulatedPacketShuffleRate))
                    {
                        NeutrinoConfig.LogWarning("SIMULATING PACKET OUT OF ORDER!");
                        int    numReceived        = serverSocket.EndReceiveFrom(result, ref receivedEndPoint);
                        byte[] receivedForShuffle = new byte[numReceived];
                        Array.Copy(receiveBuffer, receivedForShuffle, numReceived);
                        lock (receivedBuffersForShuffling)
                        {
                            receivedBuffersForShuffling.Add(new DeferredReceivable()
                            {
                                ReceivedBuffer     = receivedForShuffle,
                                TimeToReceiveTicks = Environment.TickCount + (int)(randomGenerator.NextDoublePositive() * 100.0),
                                Endpoint           = (IPEndPoint)receivedEndPoint
                            });
                        }
                        receivedEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        IAsyncResult asyncResult = serverSocket.BeginReceiveFrom(receiveBuffer, 0, NeutrinoConfig.MaxMessageSize, SocketFlags.None, ref receivedEndPoint, new AsyncCallback(HandleMessageReceived), null);
                        if (asyncResult.CompletedSynchronously)
                        {
                            HandleMessageReceived(asyncResult);
                        }
                        return;
                    }
#endif
                    int numBytesReceived = serverSocket.EndReceiveFrom(result, ref receivedEndPoint);
                    var receivedBuffer   = receivedBuffers.Pop();
                    Array.Copy(receiveBuffer, receivedBuffer.Buffer, numBytesReceived);
                    receivedBuffer.NumBytesReceived = numBytesReceived;
                    receivedBuffer.Endpoint         = (IPEndPoint)receivedEndPoint;
                    lock (readyBuffers)
                        readyBuffers.Add(receivedBuffer);
                }
                catch (Exception ex)
                {
                    NeutrinoConfig.LogError("Error handling message: " + ex);
                }

                // TBD: When tests are complete, test whether we need to reallocate here?
                receivedEndPoint = new IPEndPoint(IPAddress.Any, 0);
                IAsyncResult repeatAsyncResult = serverSocket.BeginReceiveFrom(receiveBuffer, 0, NeutrinoConfig.MaxMessageSize, SocketFlags.None, ref receivedEndPoint, new AsyncCallback(HandleMessageReceived), null);
                if (repeatAsyncResult.CompletedSynchronously)
                {
                    HandleMessageReceived(repeatAsyncResult);
                }
            }
        }
Пример #20
0
 public int probablity(int probSize = 100)
 {
     return((int)(probSize * dice.NextDoublePositive() + 1));
 }
Пример #21
0
        public int TenMinuteTick(int?hatID, double?temp, string conditions, int ticksInHouse, int ticksOutside, int ticksTotal, MersenneTwister Dice)
        {
            double amtOutside = ticksOutside / (double)ticksTotal, totalMulti = 0;
            double amtInHouse    = ticksInHouse / (double)ticksTotal;
            int    staminaAffect = 0;
            var    condList      = new List <string>();

            if (IllOptions.Verbose)
            {
                Monitor.Log($"Ticks: {ticksOutside}/{ticksTotal} with percentage {amtOutside:N3} against target {IllOptions.PercentageOutside}");
                Monitor.Log($"Ticks in house is {amtInHouse:N3} against target {IllOptions.PercentageOutside}");
                Monitor.Log($"Current Condition: {conditions}");
            }

            //First, update the sick status
            double sickOdds = IllOptions.ChanceOfGettingSick - Game1.player.DailyLuck;

            //weee.
            if (hatID == 28 && (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow")))
            {
                sickOdds -= (Dice.NextDoublePositive() / 5.0) - .1;
            }

            if (hatID == 25 && conditions.Contains("blizzard") || conditions.Contains("whiteout"))
            {
                sickOdds -= .22;
            }

            if (hatID == 4 && conditions.Contains("heatwave") && !SDVTime.IsNight)
            {
                sickOdds -= .11;
            }

            bool farmerCaughtCold = (Dice.NextDoublePositive() <= sickOdds) && (IllOptions.StaminaDrain > 0);

            FarmHouse fh           = Game1.getLocationFromName("FarmHouse") as FarmHouse;
            bool      isHeaterHere = false;

            foreach (var v in fh.objects.Pairs)
            {
                if (v.Value.Name.Contains("Heater"))
                {
                    if (IllOptions.Verbose)
                    {
                        Monitor.Log("Heater detected");
                    }
                    isHeaterHere = true;
                }
            }

            foreach (var v in fh.furniture)
            {
                if (v.furniture_type.Value == Furniture.fireplace && v.IsOn)
                {
                    if (IllOptions.Verbose)
                    {
                        Monitor.Log("fireplace detected");
                    }
                    isHeaterHere = true;
                }
            }

            if (!(temp is null))
            {
                turnTheHeatOn = (turnTheHeatOn || (amtInHouse >= IllOptions.PercentageOutside && farmerCaughtCold &&
                                                   temp < IllOptions.TooColdInside && !isHeaterHere && IssuedInHouseWarning &&
                                                   (Game1.timeOfDay < 1000 || Game1.timeOfDay > 1650)));


                if (!IssuedInHouseWarning && amtInHouse >= IllOptions.PercentageOutside && temp < IllOptions.TooColdInside &&
                    (Game1.timeOfDay < 1000 || Game1.timeOfDay > 1650) && !Game1.currentLocation.IsOutdoors && !isHeaterHere)
                {
                    SDVUtilities.ShowMessage(Helper.Get("hud-text.desc_HeatOn"), 4);
                    IssuedInHouseWarning = true;
                }
            }

            if (amtOutside >= IllOptions.PercentageOutside && farmerCaughtCold || this.FarmerSick || turnTheHeatOn)
            {
                //check if it's a valid condition
                if (FarmerCanGetSick())
                {
                    //rewrite time..
                    if (conditions.Contains("blizzard") || conditions.Contains("sandstorm") || conditions.Contains("whiteout") || (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow")) && !(Game1.currentLocation is Desert) || (conditions.Contains("frost") && SDVTime.IsNight) || (conditions.Contains("heatwave") && !SDVTime.IsNight) || turnTheHeatOn)
                    {
                        if (turnTheHeatOn && !Game1.currentLocation.IsOutdoors)
                        {
                            ReasonSick = IllCauses.TooColdInside;
                        }
                        else if ((conditions.Contains("heatwave") && !SDVTime.IsNight))
                        {
                            ReasonSick = IllCauses.TooHotOutside;
                        }
                        else if (conditions.Contains("frost") && SDVTime.IsNight)
                        {
                            ReasonSick = IllCauses.TooColdOutside;
                        }
                        else if (condList.Contains("blizzard"))
                        {
                            ReasonSick = IllCauses.BlizzardsOutside;
                        }
                        else if (condList.Contains("whiteout"))
                        {
                            ReasonSick = IllCauses.TheWampaWillGetYou;
                        }
                        else if (condList.Contains("sandstorm"))
                        {
                            ReasonSick = IllCauses.Darude;
                        }
                        else if (conditions.Contains("lightning") || conditions.Contains("stormy"))
                        {
                            ReasonSick = IllCauses.InclementWeather;
                        }
                        else
                        {
                            ReasonSick = IllCauses.NonspecificSevereWeather;
                        }

                        this.MakeSick();
                    }
                }

                //now that we've done that, go through the various conditions
                if (this.FarmerSick && (conditions.Contains("lightning") || conditions.Contains("stormy") || conditions.Contains("thundersnow")))
                {
                    totalMulti += 1;
                    condList.Add("Lightning or Thundersnow");
                }

                if (this.FarmerSick && conditions.Contains("fog"))
                {
                    totalMulti += .5;
                    condList.Add("Fog");
                }

                if (this.FarmerSick && conditions.Contains("fog") && SDVTime.IsNight)
                {
                    totalMulti += .25;
                    condList.Add("Night Fog");
                }

                if (this.FarmerSick && conditions.Contains("blizzard") && !conditions.Contains("whiteout"))
                {
                    totalMulti += 1.25;
                    condList.Add("Blizzard");
                }

                if (this.FarmerSick && conditions.Contains("sandstorm"))
                {
                    totalMulti += 1.25;
                    condList.Add("Sandstorm");
                }

                if (this.FarmerSick && conditions.Contains("blizzard") && conditions.Contains("whiteout"))
                {
                    totalMulti += 2.45;
                    condList.Add("White Out");
                }

                if (this.FarmerSick && conditions.Contains("thunderfrenzy"))
                {
                    totalMulti += 1.85;
                    condList.Add("Thunder Frenzy");
                }

                if (this.FarmerSick && conditions.Contains("frost") && SDVTime.IsNight)
                {
                    totalMulti += 1.25;
                    condList.Add("Night Frost");
                }

                if (this.FarmerSick && turnTheHeatOn)
                {
                    totalMulti += 1;
                    condList.Add("Cold House");
                }

                if (this.FarmerSick && conditions.Contains("thundersnow") && SDVTime.IsNight)
                {
                    totalMulti += .5;
                    condList.Add("Night Thundersnow");
                }

                if (this.FarmerSick && conditions.Contains("blizzard") && SDVTime.IsNight)
                {
                    totalMulti += .5;
                    condList.Add("Night Blizzard");
                }

                if (this.FarmerSick && conditions.Contains("heatwave") && !SDVTime.IsNight)
                {
                    totalMulti += 1.25;
                    condList.Add("Day Heatwave");
                }
            }

            staminaAffect -= (int)Math.Floor(IllOptions.StaminaDrain * totalMulti);

            if (IllOptions.Verbose && this.FarmerSick)
            {
                string condString = "[ ";
                for (int i = 0; i < condList.Count; i++)
                {
                    if (i != condList.Count - 1)
                    {
                        condString += condList[i] + ", ";
                    }
                    else
                    {
                        condString += condList[i];
                    }
                }
                condString += " ]";

                Monitor.Log($"[{Game1.timeOfDay}] Conditions for the drain are {condString} for a total multiplier of {totalMulti} for a total drain of {staminaAffect}");
            }

            return(staminaAffect);
        }
Пример #22
0
        internal string GenerateTVForecast(WeatherConditions Current, string MoonPhase = "")
        {
            //assemble params
            var talkParams = new Dictionary <string, string>
            {
                { "location", GetRandomLocation() },
                { "descWeather", GetWeather(Current, Game1.dayOfMonth, Game1.currentSeason) },
                { "festival", SDVUtilities.GetFestivalName(SDate.Now()) },
                { "festivalTomorrow", SDVUtilities.GetFestivalName(SDate.Now().AddDays(1)) },
                { "fogTime", Current.GetFogTime().ToString() },
                { "todayHigh", GetTemperatureString(Current.TodayHigh) },
                { "todayLow", GetTemperatureString(Current.TodayLow) },
                { "tomorrowWeather", GetWeather(Game1.weatherForTomorrow, Game1.dayOfMonth, Game1.currentSeason, true) },
                { "tomorrowHigh", GetTemperatureString(Current.TomorrowHigh) },
                { "tomorrowLow", GetTemperatureString(Current.TomorrowLow) },
                { "condWarning", GetCondWarning(Current) },
                { "condString", GetCondWarning(Current) },
                { "eveningFog", GetEveningFog(Current) }
            };

            //select the weather string for the TV.
            SDVTimePeriods CurrentPeriod = SDVTime.CurrentTimePeriod; //get the current time period
            int            nRandom       = OurDice.Next(2);

            //blood moon checks
            if ((Game1.player.spouse != null && Game1.player.isEngaged() && Game1.player.friendshipData[Game1.player.spouse].CountdownToWedding == 1) && MoonPhase == "Blood Moon")
            {
                talkParams["tomrrowWeather"] = Helper.Get($"weat-{Game1.currentSeason}.sunny.{nRandom}");
                return(Helper.Get("weat-wedTomorrow.BM.0", talkParams));
            }

            //festival tomorrow
            else if (SDVUtilities.GetFestivalName(SDate.Now().AddDays(1)) != "" && MoonPhase == "Blood Moon")
            {
                return(Helper.Get("weat-fesTomorrow.BM.0", talkParams));
            }

            else if (MoonPhase == "Blood Moon")
            {
                return(Helper.Get("weat-gen.bloodmoon.0", talkParams));
            }

            //first, check for special conditions -fog, festival, wedding
            else if (Current.HasWeather(CurrentWeather.Fog))
            {
                return(Helper.Get($"weat-loc.fog.{nRandom}", talkParams));
            }

            //festival today
            else if (Current.HasWeather(CurrentWeather.Festival))
            {
                return(Helper.Get("weat-fesToday.0", talkParams));
            }

            //festival tomorrow
            else if (SDVUtilities.GetFestivalName(SDate.Now().AddDays(1)) != "")
            {
                return(Helper.Get("weat-fesTomorrow.0", talkParams));
            }

            //wedding today
            else if (Current.HasWeather(CurrentWeather.Wedding))
            {
                return(Helper.Get("weat-wedToday.0", talkParams));
            }

            //wedding tomrrow
            else if (Game1.player.spouse != null && Game1.player.isEngaged() && Game1.player.friendshipData[Game1.player.spouse].CountdownToWedding == 1)
            {
                talkParams["tomrrowWeather"] = Helper.Get($"weat-{Game1.currentSeason}.sunny.{nRandom}");
                return(Helper.Get("weat-wedTomorrow.0", talkParams));
            }

            if (OurDice.NextDoublePositive() > .45)
            {
                if (CurrentPeriod == SDVTimePeriods.Morning)
                {
                    return(Helper.Get($"weat-morn.{nRandom}", talkParams));
                }
                else if (CurrentPeriod == SDVTimePeriods.Afternoon)
                {
                    return(Helper.Get($"weat-afternoon.{nRandom}", talkParams));
                }
                else if (CurrentPeriod == SDVTimePeriods.Evening)
                {
                    return(Helper.Get($"weat-evening.{nRandom}", talkParams));
                }
                else if (CurrentPeriod == SDVTimePeriods.Night)
                {
                    return(Helper.Get($"weat-night.{nRandom}", talkParams));
                }
                else if (CurrentPeriod == SDVTimePeriods.Midnight)
                {
                    return(Helper.Get($"weat-midnight.{nRandom}", talkParams));
                }
                else if (CurrentPeriod == SDVTimePeriods.LateNight)
                {
                    return(Helper.Get($"weat-latenight.{nRandom}", talkParams));
                }
            }
            else
            {
                //ye olde generic!
                return(Helper.Get($"weat-loc.{nRandom}", talkParams));
            }

            return("");
        }