Exemplo n.º 1
0
        public async Task <int> Add(FishPondModel _model)
        {
            if (_model.DefaultWarehouseId.GetValueOrDefault(0) == 0)
            {
                scopeContext.AddError("Chưa chọn kho");
                return(0);
            }
            if (_model.FarmRegionId == 0)
            {
                scopeContext.AddError("Chưa chọn vùng nuôi");
                return(0);
            }
            using (var transaction = context.Database.BeginTransaction())
            {
                // create new fish-pond-type warehouse
                Warehouse warehouse = new Warehouse()
                {
                    DefaultWarehouseId = _model.DefaultWarehouseId.Value,
                    FarmRegionId       = _model.FarmRegionId,
                    Name            = FISHPONDTYPE_WAREHOUSE_PREFIX + _model.Name,
                    WarehouseTypeId = DEFAULT_FISHPONDTYPE_WAREHOUSE_TYPE
                };
                var warehouseId = await svcWarehouse.Add(warehouse);

                FishPond entity = iMapper.Map <FishPond>(_model);
                entity.WarehouseId = warehouseId;
                entity.Id          = await svcFishPond.Add(entity);

                transaction.Commit();
                return(entity.Id);
            }
        }
Exemplo n.º 2
0
 public PondQueryMenu(FishPond fish_pond)
     : base(Game1.viewport.Width / 2 - width / 2, Game1.viewport.Height / 2 - height / 2, width, height)
 {
     Game1.player.Halt();
     width     = 384;
     height    = 512;
     _pond     = fish_pond;
     _fishItem = new Object(_pond.fishType.Value, 1);
     okButton  = new ClickableTextureComponent(new Rectangle(xPositionOnScreen + width + 4, yPositionOnScreen + height - 64 - IClickableMenu.borderWidth, 64, 64), Game1.mouseCursors, Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 46), 1f)
     {
         myID         = 101,
         upNeighborID = -99998
     };
     emptyButton = new ClickableTextureComponent(new Rectangle(xPositionOnScreen + width + 4, yPositionOnScreen + height - 256 - IClickableMenu.borderWidth, 64, 64), Game1.mouseCursors, new Rectangle(32, 384, 16, 16), 4f)
     {
         myID           = 103,
         downNeighborID = -99998
     };
     changeNettingButton = new ClickableTextureComponent(new Rectangle(xPositionOnScreen + width + 4, yPositionOnScreen + height - 192 - IClickableMenu.borderWidth, 64, 64), Game1.mouseCursors, new Rectangle(48, 384, 16, 16), 4f)
     {
         myID           = 106,
         downNeighborID = -99998,
         upNeighborID   = -99998
     };
     if (Game1.options.SnappyMenus)
     {
         populateClickableComponentList();
         snapToDefaultClickableComponent();
     }
     UpdateState();
     yPositionOnScreen = Game1.viewport.Height / 2 - measureTotalHeight() / 2;
 }
Exemplo n.º 3
0
        private void OnDayStarted(object sender, DayStartedEventArgs e)
        {
            Farm farm = Game1.getFarm();

            foreach (Building building in farm.buildings)
            {
                if (building is FishPond || building.GetType().IsSubclassOf(typeof(FishPond)))
                {
                    FishPond pond = (FishPond)building;
                    if (!pond.modData.ContainsKey(fishPondIdKey))
                    {
                        string fishQualities = "";
                        if (pond.FishCount > 0)
                        {
                            fishQualities = "0";
                            for (int x = 1; x < pond.FishCount; x++)
                            {
                                fishQualities += "0";
                            }
                        }
                        pond.modData.Add(fishPondIdKey, fishQualities);
                    }
                }
            }
        }
Exemplo n.º 4
0
 public static void performActionOnConstruction_Postfix(FishPond __instance)
 {
     if (!__instance.modData.ContainsKey(ModEntry.fishPondIdKey))
     {
         __instance.modData.Add(ModEntry.fishPondIdKey, "");
         return;
     }
 }
Exemplo n.º 5
0
        public async Task <bool> Modify(FishPond _model)
        {
            _model.UpdatedUser = scopeContext.UserCode;
            _model.UpdatedDate = DateTime.Now;
            context.Update(_model);
            await context.SaveChangesAsync();

            return(true);
        }
Exemplo n.º 6
0
        public async Task <int> Add(FishPond _model)
        {
            _model.CreatedUser = scopeContext.UserCode;
            _model.CreatedDate = DateTime.Now;
            context.Add(_model);
            await context.SaveChangesAsync();

            return(_model.Id);
        }
Exemplo n.º 7
0
 public static void addFishToPond_Postfix(FishPond __instance, StardewValley.Object fish)
 {
     if (__instance.modData.ContainsKey(ModEntry.fishPondIdKey))
     {
         __instance.modData[ModEntry.fishPondIdKey] += fish.Quality;
     }
     else
     {
         Monitor.Log("Couldn't find Fish Pond ID", LogLevel.Info);
     }
 }
Exemplo n.º 8
0
 public static string getCompletedRequestString(FishPond pond, Object fishItem, Random r)
 {
     if (fishItem != null)
     {
         string talk_suffix = GetFishTalkSuffix(fishItem);
         if (talk_suffix != "")
         {
             return(Lexicon.capitalize(Game1.content.LoadString("Strings\\UI:PondQuery_StatusRequestComplete" + talk_suffix + r.Next(3), pond.neededItem.Value.DisplayName)));
         }
     }
     return(Game1.content.LoadString("Strings\\UI:PondQuery_StatusRequestComplete" + r.Next(7), pond.neededItem.Value.DisplayName));
 }
Exemplo n.º 9
0
 public PondFishSilhouette(FishPond pond)
 {
     _pond       = pond;
     _fishObject = _pond.GetFishObject();
     if (_fishObject.HasContextTag("fish_upright"))
     {
         _upRight = true;
     }
     position      = (_pond.GetCenterTile() + new Vector2(0.5f, 0.5f)) * 64f;
     _age          = 0f;
     _randomOffset = Utility.Lerp(0f, 500f, (float)Game1.random.NextDouble());
     ResetDartTime();
 }
Exemplo n.º 10
0
        public static void SpawnFish_Postfix(FishPond __instance)
        {
            if (__instance.hasSpawnedFish.Value)
            {
                if (__instance.modData.ContainsKey(ModEntry.fishPondIdKey))
                {
                    double playerLuck = Game1.player.DailyLuck;
                    string pondData   = __instance.modData[ModEntry.fishPondIdKey];
                    double random     = Game1.random.NextDouble();

                    if (ModEntry.Instance.config.EnableGaranteedIridum && playerLuck < -0.02)
                    {
                        pondData += "2";
                        __instance.modData[ModEntry.fishPondIdKey] = pondData;
                        return;
                    }
                    else if (ModEntry.Instance.config.EnableGaranteedIridum && pondData.Count(x => x == '4') == pondData.Count() && playerLuck >= -0.02)
                    {
                        pondData += "4";
                        __instance.modData[ModEntry.fishPondIdKey] = pondData;
                        return;
                    }
                    else
                    {
                        if (Game1.player.professions.Contains(8) && random < (pondData.Count(x => x == '4') * (Game1.player.LuckLevel / 10)) / (2 * pondData.Count(x => int.TryParse(x.ToString(), out int result) == true)))
                        {
                            pondData += "4";
                        }
                        if (random < 0.33)
                        {
                            pondData += "2";
                        }
                        else if (random < 0.66)
                        {
                            pondData += "1";
                        }
                        else
                        {
                            pondData += "0";
                        }

                        __instance.modData[ModEntry.fishPondIdKey] = pondData;
                        return;
                    }
                }
                else
                {
                    Monitor.Log("Couldn't find Fish Pond ID", LogLevel.Info);
                }
            }
        }
Exemplo n.º 11
0
        public async Task <bool> Remove(int _id)
        {
            FishPond item = await context.FishPond.Where(i => i.Id == _id).FirstOrDefaultAsync();

            if (item == default(FishPond))
            {
                return(false);
            }
            item.IsDeleted = true;
            context.Entry(item).Property(x => x.IsDeleted).IsModified = true;
            await context.SaveChangesAsync();

            return(true);
        }
Exemplo n.º 12
0
        public static bool FishPond_dayUpdate_Prefix(FishPond __instance, ref int ___whichFish)
        {
            SMonitor.Log($"FishPond.dayUpdate: whichFish: {___whichFish}");

            Dictionary <string, string> animationDescriptions = Game1.content.Load <Dictionary <string, string> >("Data\\animationDescriptions");

            if (!Game1.objectInformation.ContainsKey(___whichFish))
            {
                SMonitor.Log($"FishingRod.draw: whichFish does not exist in objectInformation", LogLevel.Warn);
                ___whichFish = Game1.objectInformation.Keys.First();
                SMonitor.Log($"FishingRod.draw: trying to recover by setting whichFish to {___whichFish}", LogLevel.Warn);
            }
            return(true);
        }
		/// <summary>Patch for Aquarist increased max fish pond capacity.</summary>
		private static void FishPondUpdateMaximumOccupancyPostfix(ref FishPond __instance, ref FishPondData ____fishPondData)
		{
			if (__instance == null || ____fishPondData == null) return;

			try
			{
				var owner = Game1.getFarmer(__instance.owner.Value);
				if (Utility.SpecificPlayerHasProfession("Aquarist", owner) && __instance.lastUnlockedPopulationGate.Value >= ____fishPondData.PopulationGates.Keys.Max())
					__instance.maxOccupants.Set(12);
			}
			catch (Exception ex)
			{
				Monitor.Log($"Failed in {nameof(FishPondUpdateMaximumOccupancyPostfix)}:\n{ex}");
			}
		}
Exemplo n.º 14
0
 public JumpingFish(FishPond pond, Vector2 start_position, Vector2 end_position)
 {
     angularVelocity = Utility.RandomFloat(20f, 40f) * (float)Math.PI / 180f;
     startPosition   = start_position;
     endPosition     = end_position;
     position        = startPosition;
     _pond           = pond;
     _fishObject     = pond.GetFishObject();
     if (startPosition.X > endPosition.X)
     {
         _flipped = true;
     }
     jumpHeight = Utility.RandomFloat(75f, 100f);
     Splash();
 }
Exemplo n.º 15
0
        /// <summary>
        /// Smash Well, make (3x3) Pond with the same contents and data
        /// </summary>
        /// <param name="pondTile"></param>
        private void ConvertWellToPond(Vector2 pondTile)
        {
            Farm     farm    = Game1.getLocationFromName("Farm") as Farm;
            FishPond oldWell = (FishPond)farm.getBuildingAt(pondTile);
            FishPond NewPond = new FishPond(new BluePrint("Fish Pond"), Vector2.Zero);

            this.Monitor.Log($"Well -> Pond conversion at {pondTile}.", LogLevel.Trace);
            ReplacePondData(oldWell, NewPond);
            NewPond.tilesWide.Value = 3;
            NewPond.tilesHigh.Value = 3;
            bool destroyed = farm.destroyStructure(oldWell);
            bool built     = farm.buildStructure(NewPond, pondTile, Game1.player, true);

            NewPond.performActionOnBuildingPlacement();
            NewPond.UpdateMaximumOccupancy();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Smash Pond, make Well with the same contents and data
        /// </summary>
        /// <param name="pondTile"></param>
        private void ConvertPondToWell(Vector2 pondTile)
        {
            Farm     farm    = Game1.getLocationFromName("Farm") as Farm;
            FishPond oldPond = (FishPond)farm.getBuildingAt(pondTile);
            FishWell NewWell = new FishWell(new BluePrint("Fish Well"), Vector2.Zero);

            this.Monitor.Log($"Pond -> Well conversion at {pondTile}.", LogLevel.Trace);
            ReplacePondData(oldPond, NewWell);
            NewWell.Config = Config;
            bool destroyed = farm.destroyStructure(oldPond);
            bool built     = farm.buildStructure(NewWell, pondTile, Game1.player, true);

            NewWell.performActionOnBuildingPlacement();
            NewWell.ApplyPopulationCap();
            NewWell.resetTexture();
        }
Exemplo n.º 17
0
 private void AddFishToPond(FishPond pond, SObject o)
 {
     // We don't want to call the game's addFishToPond because it requires a farmer object and
     //   1) reduces the currently selected item of the farmer by 1
     //   2) tries to show the throwing animation into the pond
     // These are problems because we want to stealthily add items on day start.
     // To counter this, instead of calling that single function via reflection, we
     //   try to mimic most of what that function does, reflecting whenever necessary
     if (pond.currentOccupants == 0)
     {
         pond.fishType.Value = o.ParentSheetIndex;
         Helper.Reflection.GetField <FishPondData>(pond, "_fishPondData").SetValue(null);
         pond.UpdateMaximumOccupancy();
     }
     pond.currentOccupants.Value++;
 }
Exemplo n.º 18
0
        /// <summary>Get a fish pond's possible drops.</summary>
        /// <param name="pond">The fish pond.</param>
        /// <param name="data">The fish pond data.</param>
        /// <remarks>Derived from <see cref="FishPond.dayUpdate"/> and <see cref="FishPond.GetFishProduce"/>.</remarks>
        private IEnumerable <ItemDropData> GetPossibleDrops(FishPond pond, FishPondData data)
        {
            foreach (FishPondReward drop in data.ProducedItems)
            {
                if (pond.currentOccupants.Value < drop.RequiredPopulation)
                {
                    continue;
                }

                yield return(new ItemDropData(drop.ItemID, drop.MinQuantity, drop.MaxQuantity, drop.Chance));

                if (drop.Chance >= 1)
                {
                    break; // guaranteed drop, any further drops will be ignored
                }
            }
        }
 private static int GetAdditionalGrowthFactor(Random r, FishPond pond)
 {
     try
     {
         if (pond.modData?.GetBool(CanPlaceHandler.DomesticatedFishFood) == true &&
             r.NextDouble() < 0.15)
         {
             ModEntry.ModMonitor.DebugOnlyLog($"Speeding up fish growth at pond at {pond.tileX}, {pond.tileY}", LogLevel.Info);
             return(2);
         }
     }
     catch (Exception ex)
     {
         ModEntry.ModMonitor.Log($"Error in speeding up fish growth in fish ponds!\n\n{ex}", LogLevel.Error);
     }
     return(1);
 }
Exemplo n.º 20
0
        public static void dayUpdate_Postfix(FishPond __instance)
        {
            if (!__instance.modData.ContainsKey(ModEntry.fishPondIdKey))
            {
                string fishQualities = "";
                if (__instance.FishCount > 0)
                {
                    fishQualities = "0";
                    for (int x = 1; x < __instance.FishCount; x++)
                    {
                        fishQualities += "0";
                    }
                }

                __instance.modData.Add(ModEntry.fishPondIdKey, fishQualities);
                return;
            }
        }
Exemplo n.º 21
0
        public static bool FishPond_HasUnresolvedNeeds_Prefix(FishPond __instance, ref bool __result)
        {
            if (__instance.currentOccupants.Value < (int)__instance.maxOccupants)
            {
                return(true);
            }
            FishPondData f = __instance.GetFishPondData();

            if (f is null)
            {
                SMonitor.Log($"FishPond.HasUnresolvedNeeds: GetFishPondData did not return data", LogLevel.Warn);
                SMonitor.Log($"FishPond.HasUnresolvedNeeds: trying to recover by telling SDV the pond has no neededItem or unresolved needs", LogLevel.Warn);
                __instance.neededItem.Value = null;
                __result = false;
                return(false);
            }

            return(true);
        }
Exemplo n.º 22
0
        public static void pullFishFromWater_Prefix(FishingRod __instance, ref int fishQuality, bool fromFishPond)
        {
            if (fromFishPond)
            {
                var     calculateBobberTileMethod = AccessTools.Method(typeof(FishingRod), "calculateBobberTile");
                Vector2 bobberTile = (Vector2)calculateBobberTileMethod.Invoke(__instance, new object[] { });

                Building building = Game1.getFarm().getBuildingAt(bobberTile);
                if ((building is FishPond || building.GetType().IsSubclassOf(typeof(FishPond))) && building.modData.ContainsKey(ModEntry.fishPondIdKey))
                {
                    FishPond pond        = (FishPond)building;
                    string   pondData    = pond.modData[ModEntry.fishPondIdKey];
                    int      randomIndex = Game1.random.Next(pondData.Length);
                    fishQuality = int.Parse(pondData[randomIndex].ToString());
                    pond.modData[ModEntry.fishPondIdKey] = pondData.Remove(randomIndex, 1);
                    return;
                }
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Moves the important bits from one Building to another
 /// </summary>
 /// <param name="fromPond"></param>
 /// <param name="toPond"></param>
 private void ReplacePondData(FishPond fromPond, FishPond toPond)
 {
     toPond.daysOfConstructionLeft.Value = fromPond.daysOfConstructionLeft.Value;
     toPond.daysUntilUpgrade.Value       = fromPond.daysUntilUpgrade.Value;
     toPond.owner.Value                      = fromPond.owner.Value;
     toPond.fishType.Value                   = fromPond.fishType.Value;
     toPond.currentOccupants.Value           = fromPond.currentOccupants.Value;
     toPond.lastUnlockedPopulationGate.Value = fromPond.lastUnlockedPopulationGate.Value;
     toPond.hasCompletedRequest.Value        = fromPond.hasCompletedRequest.Value;
     toPond.sign.Value = fromPond.sign.Value;
     toPond.overrideWaterColor.Value = fromPond.overrideWaterColor.Value;
     toPond.output.Value             = fromPond.output.Value;
     toPond.neededItemCount.Value    = fromPond.neededItemCount.Value;
     toPond.neededItem.Value         = fromPond.neededItem.Value;
     toPond.daysSinceSpawn.Value     = fromPond.daysSinceSpawn.Value;
     toPond.nettingStyle.Value       = fromPond.nettingStyle.Value;
     toPond.seedOffset.Value         = fromPond.seedOffset.Value;
     toPond.hasSpawnedFish.Value     = fromPond.hasSpawnedFish.Value;
     toPond.maxOccupants.Value       = fromPond.maxOccupants;
 }
Exemplo n.º 24
0
        /*****************/
        /* Internal Code */
        /*****************/


        /// <summary>Applies customized colors to fish ponds based on the fish's name.</summary>
        /// <param name="__instance">The instance calling the original method.</param>
        private static void FishPond_doFishSpecificWaterColoring(FishPond __instance, FishPondData ____fishPondData)
        {
            try
            {
                if (__instance.currentOccupants.Value > 2 && ____fishPondData?.RequiredTags?.Count > 0) //if this pond has enough fish to be colored AND has loaded fish tag data
                {
                    foreach (string tag in ____fishPondData.RequiredTags)                               //for each tag required by this pond's data
                    {
                        if (FishDataTagsAndPondColors.TryGetValue(tag, out Color colorForThisTag))      //if this class has a custom color for this fish tag
                        {
                            __instance.overrideWaterColor.Value = colorForThisTag;                      //apply this color
                            return;                                                                     //stop here
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.LogOnce($"Harmony patch \"{nameof(HarmonyPatch_CustomFishPondColors)}\" has encountered an error. Custom fish pond colors might not be applied. Full error message: \n{ex.ToString()}", LogLevel.Error);
                return;
            }
        }
Exemplo n.º 25
0
        public async Task <bool> Modify(int _id, FishPondModel _model)
        {
            FishPond entity = await svcFishPond.GetDetail(_id);

            if (entity == null)
            {
                return(false);
            }
            Warehouse warehouse = await svcWarehouse.GetDetail(entity.WarehouseId.GetValueOrDefault(0));

            if (warehouse != null && warehouse.DefaultWarehouseId != _model.DefaultWarehouseId)
            {
                warehouse.DefaultWarehouseId = _model.DefaultWarehouseId.Value;
                if (!await svcWarehouse.Modify(warehouse))
                {
                    scopeContext.AddError("Có lỗi khi cập nhật kho mặc định.");
                    return(false);
                }
            }
            entity = iMapper.Map(_model, entity);
            return(await svcFishPond.Modify(entity));
        }
Exemplo n.º 26
0
 private void Input_ButtonPressed(object sender, ButtonPressedEventArgs e)
 {
     if (Context.IsWorldReady &&
         Game1.currentLocation != null &&
         Game1.activeClickableMenu == null &&
         Game1.player.CurrentItem != null &&
         Game1.player.CurrentItem.canBeGivenAsGift() &&
         e.Button.IsActionButton())
     {
         FishPond pond = GetPondAtTile(Game1.currentLocation, e.Cursor.GrabTile);
         if (pond != null && !pond.isUnderConstruction())
         {
             Monitor.Log($"Trying to add an item ({Game1.player.CurrentItem.ParentSheetIndex}) to a pond of type {pond.fishType.Value}.", LogLevel.Trace);
             if (pond.fishType.Value == -1 || pond.fishType.Value == Game1.player.CurrentItem.ParentSheetIndex)
             {
                 if (pond.currentOccupants.Value >= pond.maxOccupants.Value)
                 {
                     Monitor.Log("Right item, but pond is full.", LogLevel.Trace);
                     Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\Buildings:PondFull"));
                     Helper.Input.Suppress(e.Button);
                 }
                 else
                 {
                     bool success = Helper.Reflection.GetMethod(pond, "addFishToPond").Invoke <bool>(Game1.player, Game1.player.ActiveObject);
                     Monitor.Log("Pond is empty or pond contains this item with room for more so we tried to add it. Success? {success}.", LogLevel.Trace);
                     if (success)
                     {
                         Helper.Input.Suppress(e.Button);
                     }
                 }
             }
             else
             {
                 Monitor.Log("This is not the right item for this pond. Mod will ignore it and not suppress the click.", LogLevel.Trace);
             }
         }
     }
 }
Exemplo n.º 27
0
 private void ChangePondColor(FishPond pond, PondPainterDataEntry entry)
 {
     // This should be iterating in descending order, so the first match we have takes priority
     foreach (KeyValuePair <int, PondPainterDataColorDef> kvp in entry.Colors)
     {
         if (pond.FishCount >= kvp.Key)
         {
             if (kvp.Value.HasAnimation)
             {
                 pond.overrideWaterColor.Value   = kvp.Value.AnimationColors[0];
                 kvp.Value.AnimationCurrentFrame = 0;
                 Instance.ActiveAnimations[pond] = kvp.Value;
                 this.Monitor.Log($"Set the color for the pond at {pond.tileX}, {pond.tileY} with population {pond.FishCount} to an animation starting with Color {kvp.Key}: {kvp.Value.AnimationColors[0]}.", LogLevel.Trace);
             }
             else
             {
                 pond.overrideWaterColor.Value = kvp.Value.StaticColor;
                 this.Monitor.Log($"Set the color for the pond at {pond.tileX}, {pond.tileY} with population {pond.FishCount} to static Color {kvp.Key}: {kvp.Value.StaticColor}", LogLevel.Trace);
             }
             return;
         }
     }
     this.Monitor.Log($"Did not set color for pond at {pond.tileX}, {pond.tileY} with population {pond.FishCount} because no matching qualifying definition.", LogLevel.Trace);
 }
Exemplo n.º 28
0
 private void GameLoop_SaveLoaded(object sender, SaveLoadedEventArgs e)
 {
     // This function only reads the save data and uses it to create our internal pond list
     // Because of this, it is only relevant to the host
     if (Context.IsMainPlayer)
     {
         Monitor.Log("Checking for and restoring empty pond data from save", LogLevel.Trace);
         EmptyPonds = new Dictionary <FishPond, AnythingPondsTracker>();
         AnythingPondsSaveData saveData = Helper.Data.ReadSaveData <AnythingPondsSaveData>("EmptyPonds");
         if (saveData != null)
         {
             foreach (string key in saveData.EmptyPonds.Keys)
             {
                 string[] keySplit         = key.Split(new char[] { '/' });
                 BuildableGameLocation loc = Game1.getLocationFromName(keySplit[0]) as BuildableGameLocation;
                 if (loc != null)
                 {
                     Vector2 tile = new Vector2(Convert.ToInt32(keySplit[1]), Convert.ToInt32(keySplit[2]));
                     // We want to verify the pond exists and is still empty
                     FishPond pond = GetPondAtTile(loc, tile);
                     if (IsEmpty(pond))
                     {
                         EmptyPonds.Add(pond, new AnythingPondsTracker(keySplit[0], saveData.EmptyPonds[key]));
                     }
                 }
             }
         }
     }
     else
     {
         if (Config.Allow_Empty_Ponds_to_Become_Algae_or_Seaweed)
         {
             Monitor.Log("Not main player, so empty pond conversion to algae/seaweed unavailable", LogLevel.Debug);
         }
     }
 }
Exemplo n.º 29
0
        /// <summary>Get a fish pond's population gates for display.</summary>
        /// <param name="pond">The fish pond.</param>
        /// <param name="data">The fish pond data.</param>
        private IEnumerable <KeyValuePair <IFormattedText[], bool> > GetPopulationGates(FishPond pond, FishPondData data)
        {
            int nextQuest = -1;

            foreach (var gate in data.PopulationGates)
            {
                int newPopulation = gate.Key + 1;

                // done
                if (pond.lastUnlockedPopulationGate.Value >= gate.Key)
                {
                    yield return(new KeyValuePair <IFormattedText[], bool>(
                                     key: new IFormattedText[] { new FormattedText(L10n.Building.FishPondQuestsDone(count: newPopulation)) },
                                     value: true
                                     ));

                    continue;
                }

                // get required items
                if (nextQuest == -1)
                {
                    nextQuest = gate.Key;
                }
                List <string> requiredItems = new List <string>();
                foreach (string entry in gate.Value)
                {
                    // parse requirement
                    string[] parts    = entry.Split(' ');
                    int      id       = -1;
                    int      minCount = 1;
                    int      maxCount = 1;
                    if (parts.Length < 1 || parts.Length > 3 || !int.TryParse(parts[0], out int itemID))
                    {
                        requiredItems.Add(entry);
                        continue;
                    }
                    if (parts.Length >= 2 && !int.TryParse(parts[1], out minCount))
                    {
                        requiredItems.Add(entry);
                        continue;
                    }
                    if (parts.Length >= 3 && !int.TryParse(parts[1], out maxCount))
                    {
                        requiredItems.Add(entry);
                        continue;
                    }

                    // build display string
                    if (maxCount < minCount)
                    {
                        maxCount = minCount;
                    }
                    SObject obj     = this.GameHelper.GetObjectBySpriteIndex(itemID);
                    string  summary = obj.DisplayName;
                    if (minCount != maxCount)
                    {
                        summary += $" ({L10n.Generic.Range(min: minCount, max: maxCount)})";
                    }
                    else if (minCount > 1)
                    {
                        summary += $" ({minCount})";
                    }

                    // track requirement
                    requiredItems.Add(summary);
                }

                // display requirements
                string itemList = string.Join(", ", requiredItems);
                string result   = requiredItems.Count > 1
                    ? L10n.Building.FishPondQuestsIncompleteRandom(newPopulation, itemList)
                    : L10n.Building.FishPondQuestsIncompleteOne(newPopulation, requiredItems[0]);
                if (nextQuest == gate.Key)
                {
                    int nextQuestDays = data.SpawnTime
                                        + (data.SpawnTime * (pond.maxOccupants.Value - pond.currentOccupants.Value))
                                        - pond.daysSinceSpawn.Value;
                    result += $"; {L10n.Building.FishPondQuestsAvailable(relativeDate: this.GetRelativeDateStr(nextQuestDays))}";
                }
                yield return(new KeyValuePair <IFormattedText[], bool>(key: new IFormattedText[] { new FormattedText(result) }, value: false));
            }
        }
        public bool buildStructure(BluePrint structureForPlacement, Vector2 tileLocation, Farmer who, bool magicalConstruction = false, bool skipSafetyChecks = false)
        {
            if (!skipSafetyChecks)
            {
                for (int y2 = 0; y2 < structureForPlacement.tilesHeight; y2++)
                {
                    for (int x2 = 0; x2 < structureForPlacement.tilesWidth; x2++)
                    {
                        pokeTileForConstruction(new Vector2(tileLocation.X + (float)x2, tileLocation.Y + (float)y2));
                    }
                }
                for (int y3 = 0; y3 < structureForPlacement.tilesHeight; y3++)
                {
                    for (int x3 = 0; x3 < structureForPlacement.tilesWidth; x3++)
                    {
                        Vector2 currentGlobalTilePosition2 = new Vector2(tileLocation.X + (float)x3, tileLocation.Y + (float)y3);
                        if (!isBuildable(currentGlobalTilePosition2))
                        {
                            return(false);
                        }
                        foreach (Farmer farmer in farmers)
                        {
                            if (farmer.GetBoundingBox().Intersects(new Microsoft.Xna.Framework.Rectangle(x3 * 64, y3 * 64, 64, 64)))
                            {
                                return(false);
                            }
                        }
                    }
                }
                if (structureForPlacement.humanDoor != new Point(-1, -1))
                {
                    Vector2 doorPos = tileLocation + new Vector2(structureForPlacement.humanDoor.X, structureForPlacement.humanDoor.Y + 1);
                    if (!isBuildable(doorPos) && !isPath(doorPos))
                    {
                        return(false);
                    }
                }
            }
            Building b;

            switch (structureForPlacement.name)
            {
            case "Stable":
                b = new Stable(StardewValley.Util.GuidHelper.NewGuid(), structureForPlacement, tileLocation);
                break;

            case "Coop":
            case "Big Coop":
            case "Deluxe Coop":
                b = new Coop(structureForPlacement, tileLocation);
                break;

            case "Barn":
            case "Big Barn":
            case "Deluxe Barn":
                b = new Barn(structureForPlacement, tileLocation);
                break;

            case "Mill":
                b = new Mill(structureForPlacement, tileLocation);
                break;

            case "Junimo Hut":
                b = new JunimoHut(structureForPlacement, tileLocation);
                break;

            case "Shipping Bin":
                b = new ShippingBin(structureForPlacement, tileLocation);
                break;

            case "Fish Pond":
                b = new FishPond(structureForPlacement, tileLocation);
                break;

            default:
                b = new Building(structureForPlacement, tileLocation);
                break;
            }
            b.owner.Value = who.UniqueMultiplayerID;
            if (!skipSafetyChecks)
            {
                string finalCheckResult = b.isThereAnythingtoPreventConstruction(this);
                if (finalCheckResult != null)
                {
                    Game1.addHUDMessage(new HUDMessage(finalCheckResult, Color.Red, 3500f));
                    return(false);
                }
            }
            for (int y = 0; y < structureForPlacement.tilesHeight; y++)
            {
                for (int x = 0; x < structureForPlacement.tilesWidth; x++)
                {
                    Vector2 currentGlobalTilePosition = new Vector2(tileLocation.X + (float)x, tileLocation.Y + (float)y);
                    terrainFeatures.Remove(currentGlobalTilePosition);
                }
            }
            buildings.Add(b);
            b.performActionOnConstruction(this);
            return(true);
        }