コード例 #1
0
ファイル: FarmImprovement.cs プロジェクト: Gnomodia/Gnomodia
 public static bool CanBePlanted(Farm farm, Vector3 cellVector, out bool returnValue)
 {
     if (cellVector == -Vector3.One)
     {
         returnValue = false;
         return true;
     }
     Map map = GnomanEmpire.Instance.Map;
     MapCell cell = map.GetCell(cellVector);
     if ((bool)UndergroundField.GetValue(farm))
     {
         Mud mud = cell.EmbeddedFloor as Mud;
         if (mud != null && cell.ProposedJob == null && mud.PlantedSeed == null)
         {
             returnValue = true;
             return true;
         }
     }
     else
     {
         TilledSoil tilledSoil = cell.EmbeddedFloor as TilledSoil;
         if (tilledSoil != null && cell.ProposedJob == null && tilledSoil.PlantedSeed == null && !(cell.EmbeddedWall is Crop))
         {
             returnValue = true;
             return true;
         }
     }
     returnValue = false;
     return true;
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: niuniuliu/CSharp
        static void Main(string[] args)
        {
            Farm<Animal> farm = new Farm<Animal>();
            farm.Animals.Add(new Cow("Jack"));
            farm.Animals.Add(new Chicken("Vera"));
            farm.Animals.Add(new Chicken("Sally"));
            farm.Animals.Add(new SuperCow("Kevin"));
            farm.MakeNoises();

            Farm<Cow> dairyFarm = farm.GetCows();
            dairyFarm.FeedTheAnimals();

            foreach (Cow cow in dairyFarm)
            {
                if (cow is SuperCow)
                {
                    (cow as SuperCow).Fly();
                }
            }
            Console.ReadKey();

            #region Code for "Generic Operators" section
            //Farm<Animal> newFarm = farm + dairyFarm;
            #endregion

            #region Code for "Generic Operators" section
            //Farm<Cow> anotherDairyFarm = farm.GetSpecies<Cow>();
            //Farm<Chicken> poultryFarm = farm.GetSpecies<Chicken>();
            #endregion
        }
コード例 #3
0
 public AbstractBuilding Build(string type, Game.Point coords)
 {
     AbstractBuilding building = null;
     switch (type)
     {
         case ("Farm"):
             {
                 building = new Farm(coords);
                 break;
             }
         case ("Barrack"):
             {
                 building = new Barrack(coords);
                 break;
             }
         case ("BowWorkshop"):
             {
                 building = new BowWorkshop(coords);
                 break;
             }
         case ("Tower"):
             {
                 building = new Tower(coords);
                 break;
             }
         default:
             break;
     }
     return building;
 }
コード例 #4
0
        public void WeCanCreateMultipleFarms()
        {
            var sunnydaleFarm = new Farm(); 
            var willowFarm = new Farm();

            // TODO Please remove the incorrect assertion.
            Assert.That(sunnydaleFarm, Is.EqualTo(willowFarm));
            Assert.That(sunnydaleFarm, Is.Not.EqualTo(willowFarm));
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: niuniuliu/CSharp
   static void Main(string[] args)
   {
      Farm<Animal> farm = new Farm<Animal>
 {
     new Cow { Name="Norris" },
     new Chicken { Name="Rita" },
     new Chicken(),
     new SuperCow { Name="Chesney" }
 };
      farm.MakeNoises();
      Console.ReadKey();
   }
コード例 #6
0
        public void ButTheyMayAlsoHaveVeryDifferentBehavour()
        {
            var sunnydaleFarm = new Farm();
            var manorFarm = new AnimalFarm();
            var windFarm = new WindFarm();

            // You can feed animals on these two farms
            Assert.That(() => FeedTheAnimalsAt(sunnydaleFarm), Throws.Nothing);
            Assert.That(() => FeedTheAnimalsAt(manorFarm), Throws.Nothing);

            // TODO Please remove the incorrect assertion.
            Assert.That(() => FeedTheAnimalsAt(windFarm), Throws.Nothing);
            Assert.That(() => FeedTheAnimalsAt(windFarm), Throws.InstanceOf<FarmContainsNoAnimalsException>());
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: sev-it/asp.net
 static void Main(string[] args)
 {
     Farm<Animal> farm = new Farm<Animal>();
     farm.Animals.Add(new Cow("Jack"));
     farm.Animals.Add(new Chicken("Vera"));
     farm.Animals.Add(new Chicken("Sally"));
     farm.Animals.Add(new SuperCow("Kevin")); 
     farm.MakeNoises();
     Farm<Cow> dairyFarm = farm.GetSpecies<Cow>(); 
     dairyFarm.FeedTheAnimals(); 
     foreach (Cow cow in dairyFarm) 
     { 
         if (cow is SuperCow) 
         { 
             (cow as SuperCow).Fly(); 
         } 
     } 
     Console.ReadKey(); 
 } 
コード例 #8
0
 public static int CropCountInFarm(Farm f)
 {
     return(f.terrainFeatures.Values.Count(c => c is HoeDirt curr && curr.crop != null));
 }
コード例 #9
0
ファイル: WorkerRole.cs プロジェクト: robstoll/farmfinder
 private static void DeleteFarmFromIndex(Farm farm, IndexWriter indexWriter, ApplicationDbContext db)
 {
     indexWriter.DeleteDocuments(new Term("id", farm.FarmId.ToString()));
     db.Farms.Remove(farm);
 }
コード例 #10
0
        public static void Export(string path)
        {
            ApplicationDataModel adm = new ApplicationDataModel();

            adm.Catalog   = new Catalog();
            adm.Documents = new Documents();

            //--------------------------
            //Setup information
            //--------------------------
            //Add a crop
            Crop corn = new Crop()
            {
                Name = "Corn"
            };

            adm.Catalog.Crops.Add(corn);

            //Add some seed varieties
            CropVarietyProduct seedVariety1 = new CropVarietyProduct()
            {
                CropId = corn.Id.ReferenceId, Description = "Variety 1"
            };
            CropVarietyProduct seedVariety2 = new CropVarietyProduct()
            {
                CropId = corn.Id.ReferenceId, Description = "Variety 2"
            };

            adm.Catalog.Products.Add(seedVariety1);
            adm.Catalog.Products.Add(seedVariety2);

            //Add a liquid product
            CropNutritionProduct fertilizer = new CropNutritionProduct()
            {
                Description = "Starter", Form = ProductFormEnum.Liquid
            };

            fertilizer.ProductType = ProductTypeEnum.Fertilizer;
            adm.Catalog.Products.Add(fertilizer);

            //Add a granular product
            CropProtectionProduct insecticide = new CropProtectionProduct()
            {
                Description = "Insecticide", Form = ProductFormEnum.Solid
            };

            insecticide.ProductType = ProductTypeEnum.Chemical;
            adm.Catalog.Products.Add(insecticide);

            //GFF
            Grower grower = new Grower()
            {
                Name = "Example Grower"
            };

            adm.Catalog.Growers.Add(grower);

            Farm farm = new Farm()
            {
                Description = "Example Farm", GrowerId = grower.Id.ReferenceId
            };

            adm.Catalog.Farms.Add(farm);

            Field field = new Field()
            {
                Description = "Example Field", FarmId = farm.Id.ReferenceId, GrowerId = grower.Id.ReferenceId
            };

            field.Area = GetNumericRepresentationValue(23d, "ha", "vrReportedFieldArea");
            adm.Catalog.Fields.Add(field);

            //Crop zone
            TimeScope season = new TimeScope()
            {
                DateContext = DateContextEnum.CropSeason, TimeStamp1 = new DateTime(2021, 1, 1)
            };
            CropZone cropZone = new CropZone()
            {
                CropId = corn.Id.ReferenceId, FieldId = field.Id.ReferenceId, TimeScopes = new List <TimeScope>()
                {
                    season
                }
            };

            adm.Catalog.CropZones.Add(cropZone);

            //Field boundary
            FieldBoundary boundary = new FieldBoundary()
            {
                SpatialData = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.475010
                                    }
                                }
                            },
                            InteriorRings = new List <LinearRing>()
                            {
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        }
                                    }
                                },
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                FieldId = field.Id.ReferenceId
            };

            adm.Catalog.FieldBoundaries.Add(boundary);
            field.ActiveBoundaryId = boundary.Id.ReferenceId;

            //--------------------------
            //Prescription
            //--------------------------

            //Prescription setup data
            //Setup the representation and units for seed rate & seed depth prescriptions
            NumericRepresentation seedRate = GetNumericRepresentation("vrSeedRateSeedsTarget");
            UnitOfMeasure         seedUOM  = UnitInstance.UnitSystemManager.GetUnitOfMeasure("seeds1ac-1");
            RxProductLookup       seedVariety1RateLookup = new RxProductLookup()
            {
                ProductId = seedVariety1.Id.ReferenceId, Representation = seedRate, UnitOfMeasure = seedUOM
            };
            RxProductLookup seedVariety2RateLookup = new RxProductLookup()
            {
                ProductId = seedVariety2.Id.ReferenceId, Representation = seedRate, UnitOfMeasure = seedUOM
            };

            NumericRepresentation seedDepth = GetNumericRepresentation("vrSeedDepthTarget");
            UnitOfMeasure         depthUOM  = UnitInstance.UnitSystemManager.GetUnitOfMeasure("cm");
            RxProductLookup       seedVariety1DepthLookup = new RxProductLookup()
            {
                ProductId = seedVariety1.Id.ReferenceId, Representation = seedDepth, UnitOfMeasure = depthUOM
            };
            RxProductLookup seedVariety2DepthLookup = new RxProductLookup()
            {
                ProductId = seedVariety2.Id.ReferenceId, Representation = seedDepth, UnitOfMeasure = depthUOM
            };

            //Setup liquid rx representation/units
            NumericRepresentation fertilizerRate       = GetNumericRepresentation("vrAppRateVolumeTarget");
            UnitOfMeasure         fertilizerUOM        = UnitInstance.UnitSystemManager.GetUnitOfMeasure("gal1ac-1");
            RxProductLookup       fertilizerRateLookup = new RxProductLookup()
            {
                ProductId = fertilizer.Id.ReferenceId, Representation = fertilizerRate, UnitOfMeasure = fertilizerUOM
            };

            //Setup granular rx representation/units
            NumericRepresentation insecticideRate       = GetNumericRepresentation("vrAppRateMassTarget");
            UnitOfMeasure         insecticideUOM        = UnitInstance.UnitSystemManager.GetUnitOfMeasure("lb1ac-1");
            RxProductLookup       insecticideRateLookup = new RxProductLookup()
            {
                ProductId = insecticide.Id.ReferenceId, Representation = insecticideRate, UnitOfMeasure = insecticideUOM
            };


            //Prescription zones
            //Zone 1 - Variety 1 at 32000 seeds/acre, 4 cm depth target; Starter at 7 gal/ac; Insecticide at 5 lb/ac
            RxShapeLookup zone1 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 32000d,
                        RxProductLookupId = seedVariety1RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 4d,
                        RxProductLookupId = seedVariety1DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 7d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 5d,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.477404
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    }
                                }
                            },
                            InteriorRings = new List <LinearRing>()
                            {
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        }
                                    }
                                },
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Zone 2 - Variety 1 at 34000 seeds/acre, depth target 5cm; Starter at 4 gal/ac; Insecticide at 2.5 lb/ac
            RxShapeLookup zone2 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 34000d,
                        RxProductLookupId = seedVariety1RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 5d,
                        RxProductLookupId = seedVariety1DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 4d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 2.5,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.477404
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Zone 3 - Variety 2 at 29000 seeds/acre, depth target 6 cm; Starter at 6 gal/ac ; Insecticide at 2.75 lb/ac
            RxShapeLookup zone3 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 29000d,
                        RxProductLookupId = seedVariety2RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 6d,
                        RxProductLookupId = seedVariety2DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 6d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 2.75,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Assembled Rx
            VectorPrescription vectorPrescription = new VectorPrescription()
            {
                Description      = "Test Prescription",
                RxProductLookups = new List <RxProductLookup>()
                {
                    seedVariety1RateLookup,
                    seedVariety2RateLookup,
                    fertilizerRateLookup,
                    seedVariety1DepthLookup,
                    seedVariety2DepthLookup,
                    insecticideRateLookup
                },
                RxShapeLookups = new List <RxShapeLookup>()
                {
                    zone1, zone2, zone3
                },
                CropZoneId = cropZone.Id.ReferenceId,
                FieldId    = field.Id.ReferenceId
            };

            (adm.Catalog.Prescriptions as List <Prescription>).Add(vectorPrescription);

            //--------------------------
            //Export data to file via the Plugin
            //--------------------------
            PrecisionPlanting.ADAPT._2020.Plugin plugin = new Plugin();
            plugin.Export(adm, path);
        }
コード例 #11
0
        public static void CollectInput(Farm farm)
        {
            var ChickenList = new List <Chicken>();

            Console.WriteLine("1. Cow");
            Console.WriteLine("2. Ostrich");
            Console.WriteLine("3. Pig");
            Console.WriteLine("4. Goat");
            Console.WriteLine("5. Sheep");
            Console.WriteLine("6. Duck");
            Console.WriteLine("7. Chicken");

            Console.WriteLine();

            while (true)
            {
                Console.WriteLine("What are you buying today? Hit return to exit");
                Console.Write("> ");
                // try
                // {
                string choice = Console.ReadLine();
                if (String.IsNullOrEmpty(choice))
                {
                    break;
                }
                else
                {
                    if (Int32.Parse(choice) < 1 || Int32.Parse(choice) > 7)
                    {
                        Console.WriteLine("Please enter a valid index range");
                    }
                    else
                    {
                        switch (Int32.Parse(choice))
                        {
                        case 1:
                            ChooseGrazingField.CollectInput(farm, new Cow());
                            break;

                        case 2:
                            ChooseGrazingField.CollectInput(farm, new Ostrich());
                            break;

                        case 3:
                            ChooseGrazingField.CollectInput(farm, new Pig());
                            break;

                        case 4:
                            ChooseGrazingField.CollectInput(farm, new Goat());
                            break;

                        case 5:
                            ChooseGrazingField.CollectInput(farm, new Sheep());
                            break;

                        case 6:
                            ChooseDuckHouse.CollectInput(farm, new Duck());
                            break;

                        case 7:
                            Console.WriteLine("How many Chickens would you like to buy?");
                            try
                            {
                                int amount = int.Parse(Console.ReadLine());
                                for (int i = 0; i < amount; i++)
                                {
                                    ChickenList.Add(new Chicken());
                                }
                            }
                            catch
                            {
                            }
                            ChooseChickenHouse.CollectInput(farm, ChickenList);
                            break;

                        default:
                            break;
                        }
                        break;
                    }
                }
                // }
                // catch
                // {

                //     Console.WriteLine("Ibroke at the loop");
                //     Console.WriteLine("Please enter a valid index range");
                // }
            }
        }
コード例 #12
0
            /// <summary>Generates large objects (e.g. stumps and logs) in the game based on the current player's config settings.</summary>
            public static void LargeObjectGeneration()
            {
                if (Utility.Config.LargeObjectSpawnEnabled != true)
                {
                    return;
                }                          //if large object spawn is disabled, don't do anything

                Random rng = new Random(); //DEVNOTE: "Game1.random" exists, but causes some odd spawn behavior; using this for now...

                foreach (LargeObjectSpawnArea area in Utility.Config.Large_Object_Spawn_Settings.Areas)
                {
                    //validate the map name for the area
                    if (Game1.getLocationFromName(area.MapName) == null)
                    {
                        Utility.Monitor.Log($"Issue: No map named \"{area.MapName}\" could be found. Large objects won't be spawned there.", LogLevel.Info);
                        continue;
                    }

                    Farm loc = Game1.getLocationFromName(area.MapName) as Farm; //variable for the current location being worked on (NOTE: null if the current location isn't a "farm" map)
                    if (loc == null)                                            //if this area isn't a "farm" map, there's usually no built-in support for resource clumps (i.e. large objects), so display an error message and skip this area
                    {
                        Utility.Monitor.Log($"Issue: Large objects cannot be spawned in the \"{area.MapName}\" map. Only \"farm\" map types are currently supported.", LogLevel.Info);
                        continue;
                    }

                    List <int> objectIDs = Utility.GetLargeObjectIDs(area.ObjectTypes); //get a list of index numbers for relevant object types in this area

                    if (area.FindExistingObjectLocations == true)                       //if enabled, ensure that any existing objects are added to the include area list
                    {
                        List <string> existingObjects = new List <string>();            //any new object location strings to be added to area.IncludeAreas

                        foreach (ResourceClump clump in loc.resourceClumps)             //go through the map's set of resource clumps (stumps, logs, etc)
                        {
                            bool validObjectType = false;                               //whether the current object is listed in this area's config
                            foreach (int ID in objectIDs)                               //check the list of valid index numbers for this area
                            {
                                if (clump.parentSheetIndex.Value == ID)
                                {
                                    validObjectType = true; //this clump's ID matches one of the listed object IDs
                                    break;
                                }
                            }
                            if (validObjectType == false) //if this clump isn't listed in the config
                            {
                                continue;                 //skip to the next clump
                            }

                            string newInclude    = $"{clump.tile.X},{clump.tile.Y};{clump.tile.X},{clump.tile.Y}"; //generate an include string for this tile
                            bool   alreadyListed = false;                                                          //whether newInclude is already listed in area.IncludeAreas

                            foreach (string include in area.IncludeAreas)                                          //check each existing include string
                            {
                                if (include == newInclude)
                                {
                                    alreadyListed = true; //this tile is already specifically listed
                                    break;
                                }
                            }

                            if (!alreadyListed)                  //if this object isn't already specifically listed in the include areas
                            {
                                existingObjects.Add(newInclude); //add the string to the list of new include strings
                            }
                        }

                        if (existingObjects.Count > 0)                                               //if any existing objects need to be included
                        {
                            area.IncludeAreas = area.IncludeAreas.Concat(existingObjects).ToArray(); //add the new include strings to the end of the existing set
                        }

                        area.FindExistingObjectLocations = false; //disable this process so it doesn't happen every day (using it repeatedly while spawning new objects would fill the whole map over time...)
                    }

                    List <Vector2> validTiles = Utility.GenerateTileList(area, Utility.Config.Large_Object_Spawn_Settings.CustomTileIndex, true); //calculate a list of valid tiles for large objects in this area

                    //calculate how many objects to spawn today
                    int spawnCount = Utility.AdjustedSpawnCount(area.MinimumSpawnsPerDay, area.MaximumSpawnsPerDay, area.PercentExtraSpawnsPerSkillLevel, (Utility.Skills)Enum.Parse(typeof(Utility.Skills), area.RelatedSkill, true));

                    //begin to spawn objects
                    while (validTiles.Count > 0 && spawnCount > 0) //while there's still open space for objects & still objects to be spawned
                    {
                        //this section spawns 1 large object at a random valid location

                        spawnCount--; //reduce by 1, since one will be spawned

                        int     randomIndex;
                        Vector2 randomTile;
                        bool    tileConfirmed = false; //false until a valid large (2x2) object location is confirmed
                        do
                        {
                            randomIndex = rng.Next(validTiles.Count);                    //get the array index for a random valid tile
                            randomTile  = validTiles[randomIndex];                       //get the random tile's x,y coordinates
                            validTiles.RemoveAt(randomIndex);                            //remove the tile from the list, since it will be invalidated now
                            tileConfirmed = Utility.IsTileValid(area, randomTile, true); //is the tile still valid for large objects?
                        } while (validTiles.Count > 0 && !tileConfirmed);

                        if (!tileConfirmed)
                        {
                            break;
                        }                                                                                                       //if no more valid tiles could be found, stop trying to spawn things in this area

                        loc.addResourceClumpAndRemoveUnderlyingTerrain(objectIDs[rng.Next(objectIDs.Count)], 2, 2, randomTile); //generate an object using the list of valid index numbers
                    }
                }
            }
コード例 #13
0
        internal void SpreadPets(object sender, WarpedEventArgs e)
        {
            List <Pet> pets = ModApi.GetPets().ToList();

            // No pets are in the game
            if (pets.Count == 0)
            {
                return;
            }

            // Only do teleport if the player is entering the Farm, FarmHouse, or Marnie's
            if (!typeof(Farm).IsAssignableFrom(e.NewLocation.GetType()) &&
                !typeof(FarmHouse).IsAssignableFrom(e.NewLocation.GetType()) &&
                (Stray.Marnies != e.NewLocation))
            {
                return;
            }

            // Ensure Stray isn't moved around by vanilla
            ModEntry.Creator.MoveStrayToSpawn();


            if (IsIndoorWeather())
            {
                IndoorWeatherPetSpawn();
                return;
            }
            else
            {
                // Find area to warp pets to
                Farm           farm          = Game1.getFarm();
                int            initX         = (int)pets[0].getTileLocation().X;
                int            initY         = (int)pets[0].getTileLocation().Y;
                List <Vector2> warpableTiles = new List <Vector2>();
                int            cer           = ModEntry.Config.CuddleExplosionRadius;

                // Collect a set of potential tiles to warp a pet to
                for (int i = -cer; i < cer; i++)
                {
                    for (int j = -cer; j < cer; j++)
                    {
                        int warpX = initX + i;
                        int warpY = initY + j;
                        if (warpX < 0)
                        {
                            warpX = 0;
                        }
                        if (warpY < 0)
                        {
                            warpY = 0;
                        }

                        Vector2 tile = new Vector2(warpX, warpY);
                        if (IsTileAccessible(farm, tile))
                        {
                            warpableTiles.Add(tile);
                        }
                    }
                }

                // No placeable tiles found within the range given in the Config
                if (warpableTiles.Count == 0)
                {
                    ModEntry.SMonitor.Log($"Pets cannot be spread within the given radius: {cer}", LogLevel.Debug);
                    return;
                }

                // Spread pets
                foreach (Pet pet in ModApi.GetPets())
                {
                    if (!ModApi.IsStray(pet))
                    {
                        Vector2 ranTile = warpableTiles[Randomizer.Next(0, warpableTiles.Count)];
                        Game1.warpCharacter(pet, farm, ranTile);
                    }
                }
            }
        }
コード例 #14
0
        public FarmResponse ConvertFarm(string yaml)
        {
            FarmResponse response = new FarmResponse();

            Farm <string, string> animalStringString = null;
            Farm <Dog, string>    animalDogString    = null;
            Farm <string, Barn>   animalStringBarn   = null;
            Farm <Dog, Barn>      animalDogBarn      = null;

            try
            {
                animalStringString = DeserializeStringString(yaml);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                try
                {
                    animalDogString = DeserializeObjectString(yaml);
                }
                catch
                {
                    try
                    {
                        animalStringBarn = DeserializeStringObject(yaml);
                    }
                    catch
                    {
                        animalDogBarn = DeserializeObjectObject(yaml);
                    }
                    Console.WriteLine(ex.ToString());
                }
            }
            if (animalStringString != null)
            {
                response.Items.Add(animalStringString.FarmItem1);
                response.AnimalLegCount += 0;
                response.Items.Add(animalStringString.FarmItem2);
                response.BuildingCount += 0;
            }
            if (animalDogString != null)
            {
                response.Items.Add(animalDogString.FarmItem1.Name);
                response.AnimalLegCount += 4;

                response.Items.Add(animalDogString.FarmItem2);
                response.BuildingCount += 0;
            }
            if (animalStringBarn != null)
            {
                response.Items.Add(animalStringBarn.FarmItem1);
                response.AnimalLegCount += 0;

                response.Items.Add(animalStringBarn.FarmItem2.BarnType);
                response.BuildingCount += 1;
                response.BarnTools.AddRange(animalStringBarn.FarmItem2.Tools);
            }
            if (animalDogBarn != null)
            {
                response.Items.Add(animalDogBarn.FarmItem1.Name);
                response.AnimalLegCount += 4;

                response.Items.Add(animalDogBarn.FarmItem2.BarnType);
                response.BuildingCount += 1;
                response.BarnTools.AddRange(animalDogBarn.FarmItem2.Tools);
            }

            return(response);
        }
コード例 #15
0
 /// <summary>Reduce the hay count by one if possible.</summary>
 /// <param name="farm">The farm instance.</param>
 private void ConsumeHay(Farm farm)
 {
     farm.piecesOfHay.Value = Math.Max(0, farm.piecesOfHay.Value - 1);
 }
コード例 #16
0
ファイル: Cheats.cs プロジェクト: levi-middleton/SDV-Mods
        public static void onUpdate()
        {
            if (Game1.player != null)
            {
                Farmer plr = Game1.player;



                //Log.Info(Game1.currentLocation.name + ": " + plr.getTileLocation().X + ", " + plr.getTileLocation().Y);

                if (CJBCheatsMenu.config.increasedMovement && plr.running)
                {
                    plr.addedSpeed = CJBCheatsMenu.config.moveSpeed;
                }
                else if (!CJBCheatsMenu.config.increasedMovement && plr.addedSpeed == CJBCheatsMenu.config.moveSpeed)
                {
                    plr.addedSpeed = 0;
                }

                if (plr.controller != null)
                {
                    plr.addedSpeed = 0;
                }

                if (Game1.CurrentEvent == null)
                {
                    plr.movementDirections.Clear();
                }

                if (CJBCheatsMenu.config.infiniteHealth)
                {
                    plr.health = plr.maxHealth;
                }

                if (CJBCheatsMenu.config.infiniteStamina)
                {
                    plr.stamina = plr.maxStamina;
                }

                if (Game1.activeClickableMenu == null && plr.CurrentTool is FishingRod)
                {
                    FishingRod tool = (FishingRod)plr.CurrentTool;

                    if (CJBCheatsMenu.config.throwBobberMax)
                    {
                        tool.castingPower = 1.01F;
                    }
                    if (CJBCheatsMenu.config.instantBite && tool.isFishing)
                    {
                        if (tool.timeUntilFishingBite > 0)
                        {
                            tool.timeUntilFishingBite = 0;
                        }
                    }
                    if (CJBCheatsMenu.config.durableTackles && tool.attachments[1] != null)
                    {
                        tool.attachments[1].scale.Y = 1;
                    }
                }

                if (CJBCheatsMenu.config.oneHitBreak && plr.usingTool && (plr.CurrentTool is Axe || plr.CurrentTool is Pickaxe))
                {
                    int x = (int)plr.GetToolLocation().X / Game1.tileSize;
                    int y = (int)plr.GetToolLocation().Y / Game1.tileSize;

                    Vector2 index = new Vector2(x, y);

                    if (plr.CurrentTool is Pickaxe && plr.currentLocation.objects.ContainsKey(index))
                    {
                        StardewValley.Object o = plr.currentLocation.Objects[index];
                        if (o != null && o.name.Equals("Stone"))
                        {
                            o.minutesUntilReady = 0;
                        }
                    }

                    if (plr.CurrentTool is Axe && plr.currentLocation.terrainFeatures.ContainsKey(index))
                    {
                        TerrainFeature o = plr.currentLocation.terrainFeatures[index];
                        if (o != null && o is Tree)
                        {
                            Tree t = (Tree)o;
                            if (t.health > 1)
                            {
                                t.health = 1;
                            }
                        }
                    }

                    List <ResourceClump> rl = new List <ResourceClump>();
                    if (plr.currentLocation is MineShaft)
                    {
                        rl.AddRange(((MineShaft)plr.currentLocation).resourceClumps);
                    }

                    if (plr.currentLocation is Farm)
                    {
                        rl.AddRange(((Farm)plr.currentLocation).resourceClumps);
                    }

                    if (plr.currentLocation is Forest)
                    {
                        rl.Add(((Forest)plr.currentLocation).log);
                    }

                    if (plr.currentLocation is Woods)
                    {
                        rl.AddRange(((Woods)plr.currentLocation).stumps);
                    }

                    foreach (ResourceClump r in rl)
                    {
                        if (r == null)
                        {
                            continue;
                        }
                        if (r.getBoundingBox(r.tile).Contains((int)plr.GetToolLocation().X, (int)plr.GetToolLocation().Y) && r.health > 0)
                        {
                            r.health = 0;
                        }
                    }
                }

                if (CJBCheatsMenu.config.infiniteWateringCan && plr.CurrentTool is WateringCan)
                {
                    WateringCan tool = (WateringCan)plr.CurrentTool;
                    typeof(WateringCan).GetField("waterLeft", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tool, tool.waterCanMax);
                }

                if (CJBCheatsMenu.config.alwaysGiveGift)
                {
                    foreach (KeyValuePair <string, int[]> fr in plr.friendships)
                    {
                        if (fr.Value != null)
                        {
                            fr.Value[1] = 0;
                            fr.Value[3] = 0;

                            /*if (fr.Value[0] < 500)
                             *  fr.Value[0] = 500;*/
                        }
                    }
                }
            }

            if (CJBCheatsMenu.config.maxDailyLuck)
            {
                Game1.dailyLuck = 0.115d;
            }

            if (CJBCheatsMenu.config.oneHitKill && Game1.currentLocation != null)
            {
                if (Game1.currentLocation.characters != null)
                {
                    foreach (NPC npc in Game1.currentLocation.characters)
                    {
                        if (npc is Monster)
                        {
                            ((Monster)npc).health = 1;
                        }
                    }
                }
            }

            if ((CJBCheatsMenu.config.instantCatch || CJBCheatsMenu.config.alwaysTreasure) && Game1.activeClickableMenu is BobberBar)
            {
                BobberBar menu = (BobberBar)Game1.activeClickableMenu;

                if (CJBCheatsMenu.config.alwaysTreasure)
                {
                    typeof(BobberBar).GetField("treasure", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(menu, true);
                }

                if (CJBCheatsMenu.config.instantCatch)
                {
                    typeof(BobberBar).GetField("distanceFromCatching", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(menu, 1F);
                }

                if ((bool)typeof(BobberBar).GetField("treasure", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(menu))
                {
                    typeof(BobberBar).GetField("treasureCaught", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(menu, true);
                }
            }

            if (CJBCheatsMenu.config.infiniteHay)
            {
                Farm farm = (Farm)Game1.getLocationFromName("Farm");
                if (farm != null)
                {
                    farm.piecesOfHay = Utility.numSilos() * 240;
                }
            }
        }
コード例 #17
0
        public static void Postfix(Farm __instance, SpriteBatch b)
        {
            int x;

            if (__instance.Name != "Farm")
            {
                return;
            }
            NetRectangle house      = (NetRectangle)Traverse.Create(__instance).Field("houseSource").GetValue();
            NetRectangle greenhouse = (NetRectangle)Traverse.Create(__instance).Field("greenhouseSource").GetValue();

            //Farmhouse & Farmhouse Shadows
            //For Custom
            if (Memory.isCustomFarmLoaded && Memory.isFarmHouseRelocated)
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getFarmHouseRenderPosition(64, 568)), new Rectangle?(Building.leftShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                for (x = 2; x < 9; x++)
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getFarmHouseRenderPosition(x * 64f, 568)), new Rectangle?(Building.middleShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                }
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getFarmHouseRenderPosition(x * 64f, 568)), new Rectangle?(Building.rightShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getFarmHouseRenderPosition()), new Rectangle?(house), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, ((Memory.loadedFarm.farmHousePorchY() - 5 + 3) * 64) / 10000f);
            }
            else
            //For Canon & Customs with Canon Position
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2(3776f, 1088f)), new Rectangle?(Building.leftShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                for (x = 1; x < 8; x++)
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(3776 + x * 64), 1088f)), new Rectangle?(Building.middleShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                }
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2(4288f, 1088f)), new Rectangle?(Building.rightShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
                b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, new Vector2(3712f, 520f)), new Rectangle?(house), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.075f);
            }

            //Actual Farmhouse & Green House
            //For Custom
            if (Memory.isCustomFarmLoaded && Memory.isGreenHouseRelocated)
            {
                b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getGreenHouseRenderPosition()), new Rectangle?(greenhouse), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, ((Memory.loadedFarm.greenHousePorchY() - 7 + 2) * 64f) / 10000f);
            }
            //For Canon & Customs with Canon Position
            else
            {
                b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, new Vector2(1600f, 384f)), new Rectangle?(greenhouse), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.0704f);
            }


            //Mailbox "!" when new mail arrived.
            if (Game1.mailbox.Count > 0)
            {
                float yOffset = 4f * (float)Math.Round(Math.Sin(DateTime.Now.TimeOfDay.TotalMilliseconds / 250.0), 2);

                //For Custom
                if (Memory.isCustomFarmLoaded && Memory.isMailBoxRelocated)
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getMailBoxNotificationRenderPosition(0, (2.25f * -64f) + yOffset)), new Rectangle?(new Rectangle(141, 465, 20, 24)), Color.White * 0.75f, 0f, Vector2.Zero, 4f, SpriteEffects.None, (((Memory.loadedFarm.mailBoxPointY() + 2) * 64f) / 10000f) + 0.000401f);
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getMailBoxNotificationRenderPosition(0.5626f * 64f, (1.5f * -64f) + yOffset)), new Rectangle?(new Rectangle(189, 423, 15, 13)), Color.White, 0f, new Vector2(7f, 6f), 4f, SpriteEffects.None, (((Memory.loadedFarm.mailBoxPointY() + 2) * 64f) / 10000f) + 0.00041f);
                }
                else
                //For Canon & Custom with Canon Position
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2(4352f, 880f + yOffset)), new Rectangle?(new Rectangle(141, 465, 20, 24)), Color.White * 0.75f, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.115601f);
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2(4388f, 928f + yOffset)), new Rectangle?(new Rectangle(189, 423, 15, 13)), Color.White, 0f, new Vector2(7f, 6f), 4f, SpriteEffects.None, 0.11561f);
                }
            }

            //Shrine note
            if (!__instance.hasSeenGrandpaNote)
            {
                //For Custom
                if (Memory.isCustomFarmLoaded && Memory.isShrineRelocated)
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, Memory.loadedFarm.getgrandpaShrineRenderPosition()), new Rectangle?(new Rectangle(575, 1972, 11, 8)), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.0448009968f);
                }
                //For Canon & Custom with Canon Position
                else
                {
                    b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2(576f, 448f)), new Rectangle?(new Rectangle(575, 1972, 11, 8)), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.0448009968f);
                }
            }
        }
コード例 #18
0
 /*********
 ** Private methods
 *********/
 /// <summary>Get whether hay is available for animal feed.</summary>
 /// <param name="farm">The farm instance.</param>
 /// <param name="context">The cheat context.</param>
 private bool HasHay(Farm farm, CheatContext context)
 {
     return
         (context.Config.InfiniteHay ||
          farm.piecesOfHay.Value > 0);
 }
コード例 #19
0
 /// <summary>Construct an instance.</summary>
 /// <param name="bin">The constructed shipping bin.</param>
 /// <param name="location">The location which contains the machine.</param>
 /// <param name="farm">The farm which has the shipping bin data.</param>
 public ShippingBinMachine(ShippingBin bin, GameLocation location, Farm farm)
     : base(location, BaseMachine.GetTileAreaFor(bin))
 {
     this.Farm = farm;
 }
コード例 #20
0
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="farm">The farm containing the shipping bin.</param>
 /// <param name="tileArea">The tile area covered by the machine.</param>
 public ShippingBinMachine(Farm farm, Rectangle tileArea)
     : base(farm, tileArea)
 {
     this.Farm = farm;
 }
コード例 #21
0
        /// <summary>
        /// Called after load. Performs the needed warp overrides when a custom farm is loaded in.
        /// If a canon farm is loaded in, no overrides will occur.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void overRideWarps(object sender, EventArgs e)
        {
            //Check if Canon or Custom
            if (Game1.whichFarm > 4)
            {
                int i;

                //This should never be true, but just in case (Due to specific tests)
                if (Memory.loadedFarm == null)
                {
                    return;
                }

                //Take care of Neighboring map's warps, if entry/exit has moved.
                if (Memory.loadedFarm.neighboringMaps != null)
                {
                    foreach (neighboringMap map in Memory.loadedFarm.neighboringMaps)
                    {
                        string       mapName    = map.MapName;
                        GameLocation workingMap = Game1.getLocationFromName(mapName);
                        foreach (neighboringMap.Warp warp in map.warpPoints)
                        {
                            for (i = 0; i < workingMap.warps.Count; i++)
                            {
                                if (workingMap.warps[i].TargetName == warp.TargetMap && warp.fromX == workingMap.warps[i].X && warp.fromY == workingMap.warps[i].Y)
                                {
                                    workingMap.warps[i].TargetX = warp.toX;
                                    workingMap.warps[i].TargetY = warp.toY;
                                }
                            }
                        }
                    }
                }

                //Cave (Skipped if it was not specified in farmType.Json. It will be assumed it did not move from canon position).
                if (Memory.loadedFarm.farmCave != null && Memory.loadedFarm.farmCave.useCustomMapPoints == false)
                {
                    Game1.locations[2].warps.Clear();
                    Game1.locations[2].warps.Add(new Warp(8, 12, "Farm", Memory.loadedFarm.farmCavePointX(), Memory.loadedFarm.farmCavePointY(), false));
                }

                //Greenhouse (Skipped if it was not specified in farmType.Json. It will be assumed it did not move from canon position).
                GameLocation greenhouse = Game1.getLocationFromName("Greenhouse");
                if (greenhouse != null && Memory.loadedFarm.greenHouse != null && Memory.loadedFarm.greenHouse.useCustomMapPoints == false)
                {
                    greenhouse.warps.Clear();
                    greenhouse.warps.Add(new Warp(10, 24, "Farm", Memory.loadedFarm.greenHousePorchX(), Memory.loadedFarm.greenHousePorchY(), false));
                }

                //Buildings for f***s.
                if (Memory.loadedFarm.additionalMaps != null)
                {
                    foreach (additionalMap <GameLocation> m in Memory.loadedFarm.additionalMaps)
                    {
                        //if (Game1.multiplayerMode == 1) return;
                        if (m.mapType == "Farm")
                        {
                            Farm workingFarm = (Farm)Game1.getLocationFromName(m.Location);
                            if (workingFarm == null)
                            {
                                return;
                            }
                            foreach (Building b in workingFarm.buildings)
                            {
                                if (b.indoors.Value == null)
                                {
                                    continue;
                                }
                                foreach (Warp w in b.indoors.Value.warps)
                                {
                                    NetString warp = Helper.Reflection.GetField <NetString>(w, "targetName").GetValue();
                                    warp.Value = m.Location;
                                }
                            }
                        }
                    }
                }
            }
        }
        public static void CollectInput(Farm farm, ISeedProducing plant)
        {
            Console.Clear();

            Console.WriteLine($"How many {plant.Type}s would you like to plant?");

            // store that number in the variable "number"
            // Use Enumberable.Repeat() to put x("number") amount of plants("plant") in new list named "manyPlants"
            Console.Write("> ");

            int number = Int32.Parse(Console.ReadLine());

            List <ISeedProducing> manyPlants = Enumerable.Repeat(plant, number).ToList();

            Console.Clear();

            for (int i = 0; i < farm.PlowedFields.Count; i++)
            {
                if (farm.PlowedFields[i].plantCount() == 1)
                {
                    Console.WriteLine($"{i + 1}. Plowed Field ({farm.PlowedFields[i].plantCount()} row of plants)");
                }
                else if (farm.PlowedFields[i].plantCount() < farm.PlowedFields[i].Capacity)
                {
                    Console.WriteLine($"{i + 1}. Plowed Field ({farm.PlowedFields[i].plantCount()} rows of plants)");
                }
                // else
                // {
                //   Console.WriteLine($"{i + 1}. Plowed Field is full. ({farm.PlowedFields[i].plantCount()} rows of plants)");
                // }
            }
            Console.WriteLine();

            // How can I output the type of plant chosen here?
            Console.WriteLine($"Place the {plant.Type}s where?");

            Console.Write("> ");
            int choice = Int32.Parse(Console.ReadLine()) - 1;

            if (farm.PlowedFields[choice].plantCount() + manyPlants.Count() <= farm.PlowedFields[choice].Capacity)
            {
                farm.PlowedFields[choice].AddResource(manyPlants);
            }
            else
            {
                Console.Clear();
                Console.WriteLine($@"
~ I'm sorry! That facility can only hold ({farm.PlowedFields[0].Capacity}) plants ~

************************************************************************
**************      Please choose another facility.     ****************
********** If there are no other plowed fields, build one.  ***********
************************************************************************

-----------------------((press enter to continue))----------------------
");
                Console.ReadLine();
                Console.Clear();
                // after user hits enter ask if they want to create a new field
                Console.WriteLine($@"
 _______________________________________________
| Would you like to create a new Plowed Field? |
|         Press 1 for yes or 2 for no           |
 -----------------------------------------------
");
                Console.Write("> ");
                // collect the user's input and store it in the string "input"
                string input = Console.ReadLine();
                // parse the string and create a switch case
                switch (Int32.Parse(input))
                {
                // create a new plowedField and add it to the farm.
                // go to the ChoosePlowedField menu and pass the animal and farm
                case 1:
                    farm.AddPlowedField(new PlowedField());
                    Console.Clear();
                    Console.WriteLine("Success! One Plowed Field Added. Press enter to continue.");
                    Console.ReadLine();
                    ChoosePlowedField.CollectInput(farm, plant);
                    break;

                case 2:
                    break;
                }
            }
        }
コード例 #23
0
 public AnimalBuilding(StardewValley.Buildings.Building building, Farm farm) :
     base(building)
 {
     this.Farm = farm;
 }
コード例 #24
0
        internal void SpreadPets(object sender, WarpedEventArgs e)
        {
            // ** TODO: Only one pet on farmer's bed

            // Only allow host player to move pets
            if (!Context.IsMainPlayer)
            {
                return;
            }

            // TODO: If no pets, handle error. Does this error?
            List <Pet> pets = ModApi.GetPets().ToList();

            // No pets are in the game
            if (pets.Count == 0)
            {
                return;
            }

            // Ensure Stray isn't moved around by vanilla
            if (typeof(Farm).IsAssignableFrom(e.NewLocation.GetType()) ||
                typeof(FarmHouse).IsAssignableFrom(e.NewLocation.GetType()) ||
                Stray.Marnies != e.NewLocation)
            {
                ModEntry.Creator.MoveStrayToSpawn();
            }

            // Only move pets once at beginning of day and once at night
            if ((!Game1.isDarkOut() && PetsPlacedForDay) ||
                (Game1.isDarkOut() && PetsPlacedForNight))
            {
                return;
            }


            if (IsIndoorWeather())
            {
                IndoorWeatherPetSpawn();
                PetsPlacedForDay   = true;
                PetsPlacedForNight = true;
                return;
            }
            else
            {
                // Place everyone at the correct starting point, at the water dish
                if (ModEntry.Config.CustomPetLocation == false)
                {
                    foreach (Pet pet in ModApi.GetPets())
                    {
                        pet.setAtFarmPosition();
                    }
                }
                // Place pets at custom spawn point if enabled in the Config
                else
                {
                    Vector2 location = new Vector2(ModEntry.Config.PuddleX, ModEntry.Config.PuddleY);
                    foreach (Pet pet in ModApi.GetPets())
                    {
                        pet.setTileLocation(location);
                    }
                }


                // Find area to warp pets to
                Farm           farm          = Game1.getFarm();
                int            initX         = (int)pets[0].getTileLocation().X;
                int            initY         = (int)pets[0].getTileLocation().Y;
                List <Vector2> warpableTiles = new List <Vector2>();
                int            cer           = ModEntry.Config.CuddleExplosionRadius;

                // Collect a set of potential tiles to warp a pet to
                for (int i = -cer; i < cer; i++)
                {
                    for (int j = -cer; j < cer; j++)
                    {
                        int warpX = initX + i;
                        int warpY = initY + j;
                        if (warpX < 0)
                        {
                            warpX = 0;
                        }
                        if (warpY < 0)
                        {
                            warpY = 0;
                        }

                        Vector2 tile = new Vector2(warpX, warpY);
                        if (IsTileAccessible(farm, tile))
                        {
                            warpableTiles.Add(tile);
                        }
                    }
                }

                // No placeable tiles found within the range given in the Config
                if (warpableTiles.Count == 0)
                {
                    ModEntry.SMonitor.Log($"Pets cannot be spread within the given radius: {cer}", LogLevel.Debug);
                    return;
                }

                // Spread pets
                foreach (Pet pet in ModApi.GetPets())
                {
                    Vector2 ranTile = warpableTiles[Randomizer.Next(0, warpableTiles.Count)];
                    Game1.warpCharacter(pet, farm, ranTile);
                }

                PetsPlacedForDay = true;
            }
        }
コード例 #25
0
    public string buildingFlavorText(string building)
    {
        if (building == "House")
        {
            House x = new House();
            return x.flavorText;
        }

        else if (building == "Farm")
        {
            Farm x = new Farm();
            return x.flavorText;
        }

        else if (building == "Factory")
        {
            Factory x = new Factory();
            return x.flavorText;
        }

        else if (building == "Executive Building")
        {
            ExecutiveBuilding x = new ExecutiveBuilding();
            return x.flavorText;
        }

        else if (building == "Educational Building")
        {
            EducationalBuilding x = new EducationalBuilding();
            return x.flavorText;
        }

        else if (building == "Hospital")
        {
            Hospital x = new Hospital();
            return x.flavorText;
        }

        else if (building == "Laboratory")
        {
            Laboratory x = new Laboratory();
            return x.flavorText;
        }

        else if (building == "Police Station")
        {
            PoliceStation x = new PoliceStation();
            return x.flavorText;
        }

        else if (building == "Workplace")
        {
            Workplace x = new Workplace();
            return x.flavorText;
        }

        else if (building == "Public Space")
        {
            PublicSpace x = new PublicSpace();
            return x.flavorText;
        }

        else if (building == "World Trade Center")
        {
            WTC x = new WTC();
            return x.flavorText;
        }

        else if (building == "Military Outpost")
        {
            MilitaryOutpost x = new MilitaryOutpost();
            return x.flavorText;
        }

        else if (building == "Food Territory")
        {
            FoodTerritory x = new FoodTerritory();
            return x.flavorText;
        }

        else if (building == "Materials Territory")
        {
            MaterialsTerritory x = new MaterialsTerritory();
            return x.flavorText;
        }

        else if (building == "Citizens Territory")
        {
            CitizensTerritory x = new CitizensTerritory();
            return x.flavorText;
        }

        else
            return "";
    }
        public static void ListResources(Farm farm, string id, string type, int alreadyProcessedSunflowers)
        {
            IEnumerable<NaturalField> CorrectFieldEnumerable = from field in farm.NaturalFields
                                                               where field.ShortId == id
                                                               select field;

            List<NaturalField> CorrectFieldList = CorrectFieldEnumerable.ToList();

            NaturalField CorrectField = CorrectFieldList[0];

            IEnumerable<NaturalFieldReport> OrderedFlowers = (from flower in CorrectField.plantsList
                                                              group flower by flower.Type into NewGroup
                                                              select new NaturalFieldReport
                                                              {
                                                                  PlantType = NewGroup.Key,
                                                                  Number = NewGroup.Count().ToString()
                                                              }
                );

            IEnumerable<NaturalFieldReport> JustSunflowers = from flower in OrderedFlowers
                                                             where flower.PlantType == "Sunflower"
                                                             select flower;

            List<NaturalFieldReport> OrderedSunflowersList = JustSunflowers.ToList();

            int count = 1;

            int numberToCheckSunflower = 0;

            Console.WriteLine();
            Console.WriteLine("The following flowers can be processed in the Natural Field");
            Console.WriteLine();
            foreach (NaturalFieldReport flower in JustSunflowers)
            {
                numberToCheckSunflower = Int32.Parse(flower.Number) - alreadyProcessedSunflowers;
                Console.WriteLine($"{count}: {numberToCheckSunflower} {flower.PlantType}");
                count++;
            }

            Console.WriteLine();
            Console.WriteLine("Which resource should be processed?");
            Console.Write("> ");
            int choice = Int32.Parse(Console.ReadLine());
            int correctedChoice = choice - 1;

            string PlantType = OrderedSunflowersList[correctedChoice].PlantType;

            Console.WriteLine($"How many {PlantType} should be processed? (Max 5)");
            int amountToProcess = Int32.Parse(Console.ReadLine());

            while (amountToProcess > 5)
            {
                Console.WriteLine("Yo I can't process that much at once, dumbass");
                amountToProcess = Int32.Parse(Console.ReadLine());
            }
            while (amountToProcess > numberToCheckSunflower)
            {
                Console.WriteLine("Yo there aren't that many to process, dumbass");
                amountToProcess = Int32.Parse(Console.ReadLine());
            }

            farm.ProcessingList.Add(new ToProcess
            {
                FacilityId = CorrectField.ShortId,
                Type = PlantType,
                AmountToProcess = amountToProcess
            });

            Console.WriteLine("Ready to process? (Y/n)");
            Console.Write("> ");
            string input = Console.ReadLine();

            switch (input)
            {
                case "Y":
                    break;
                case "n":
                    ChooseSeedHarvester.CollectInput(farm);
                    break;
                default:
                    break;
            }
        }
コード例 #27
0
        public static void CollectInput(Farm farm, Chicken chicken)
        {
            Console.Clear();

            if (farm.ChickenHouses.Count() == 0 || farm.ChickenHouses.Where(field => field.Chickens.Count == field.Capacity).ToList().Count == farm.ChickenHouses.Count())
            {
                Console.WriteLine("There are no available chicken houses. Try creating a new one.");
                Console.WriteLine("Press return... or else");
                Console.ReadLine();
            }
            else
            {
                for (int i = 0; i < farm.ChickenHouses.Count; i++)
                {
                    // Only display chicken houses that have room
                    if (farm.ChickenHouses[i].Chickens.Count < farm.ChickenHouses[i].Capacity)
                    {
                        Console.WriteLine($"{i + 1}. Chicken House. Current Chicken Count: {farm.ChickenHouses[i].Chickens.Count}");
                    }
                }

                Console.WriteLine();

                // How can I output the type of animal chosen here?
                Console.WriteLine($"Place the {chicken.GetType().ToString().Split(".")[3]} where?");

                Console.Write("> ");
                try
                {
                    int choice = Int32.Parse(Console.ReadLine());

                    if (farm.ChickenHouses[choice - 1].Chickens.Count < farm.ChickenHouses[choice - 1].Capacity)
                    {
                        farm.ChickenHouses[choice - 1].AddResource(chicken);
                    }
                    else if (farm.ChickenHouses.Where(field => field.Chickens.Count < field.Capacity).ToList().Count > 0)
                    {
                        Console.Write("Facility is full. Please select another facility. Press any key to continue...");
                        Console.ReadLine();
                        ChooseChickenHouse.CollectInput(farm, chicken);
                    }
                    else
                    {
                        Console.Write("All facilities full. Press any key to continue...");
                        Console.ReadLine();
                    }
                }
                catch (System.FormatException)
                {
                    Console.WriteLine("Please enter one of the specified options...\nI love you.\nPress return to continue");
                    Console.ReadLine();
                    ChooseChickenHouse.CollectInput(farm, chicken);
                }
                catch (System.ArgumentOutOfRangeException)
                {
                    Console.WriteLine("The chicken house you selected does not exist\nPress return to continue");
                    Console.ReadLine();
                    ChooseChickenHouse.CollectInput(farm, chicken);
                }
            }
        }
コード例 #28
0
ファイル: FarmInfoPage.cs プロジェクト: sikker/StawdewValley
        public FarmInfoPage(int x, int y, int width, int height)
            : base(x, y, width, height, false)
        {
            this.moneyIcon = new ClickableTextureComponent("", new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize / 2, Game1.player.Money > 9999 ? 18 : 20, 16), Game1.player.Money.ToString() + "g", "", Game1.debrisSpriteSheet, new Rectangle(88, 280, 16, 16), 1f, false);
            this.mapX      = x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize * 2 + Game1.tileSize / 2 + Game1.tileSize / 4;
            this.mapY      = y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize / 3 - 4;
            this.farmMap   = new ClickableTextureComponent(new Rectangle(this.mapX, this.mapY, 20, 20), Game1.content.Load <Texture2D>("LooseSprites\\farmMap"), Rectangle.Empty, 1f, false);
            int num1  = 0;
            int num2  = 0;
            int num3  = 0;
            int num4  = 0;
            int num5  = 0;
            int num6  = 0;
            int num7  = 0;
            int num8  = 0;
            int num9  = 0;
            int num10 = 0;
            int num11 = 0;
            int num12 = 0;
            int num13 = 0;
            int num14 = 0;
            int num15 = 0;
            int num16 = 0;

            this.farm      = (Farm)Game1.getLocationFromName("Farm");
            this.farmHouse = new ClickableTextureComponent("FarmHouse", new Rectangle(this.mapX + 443, this.mapY + 43, 80, 72), "FarmHouse", "", Game1.content.Load <Texture2D>("Buildings\\houses"), new Rectangle(0, 0, 160, 144), 0.5f, false);
            foreach (FarmAnimal allFarmAnimal in this.farm.getAllFarmAnimals())
            {
                if (allFarmAnimal.type.Contains("Chicken"))
                {
                    ++num1;
                    num9 += allFarmAnimal.friendshipTowardFarmer;
                }
                else
                {
                    string type = allFarmAnimal.type;
                    if (!(type == "Cow"))
                    {
                        if (!(type == "Duck"))
                        {
                            if (!(type == "Rabbit"))
                            {
                                if (!(type == "Sheep"))
                                {
                                    if (!(type == "Goat"))
                                    {
                                        if (type == "Pig")
                                        {
                                            ++num8;
                                            num16 += allFarmAnimal.friendshipTowardFarmer;
                                        }
                                        else
                                        {
                                            ++num4;
                                            num12 += allFarmAnimal.friendshipTowardFarmer;
                                        }
                                    }
                                    else
                                    {
                                        ++num7;
                                        num14 += allFarmAnimal.friendshipTowardFarmer;
                                    }
                                }
                                else
                                {
                                    ++num6;
                                    num15 += allFarmAnimal.friendshipTowardFarmer;
                                }
                            }
                            else
                            {
                                ++num3;
                                num10 += allFarmAnimal.friendshipTowardFarmer;
                            }
                        }
                        else
                        {
                            ++num2;
                            num11 += allFarmAnimal.friendshipTowardFarmer;
                        }
                    }
                    else
                    {
                        ++num5;
                        num13 += allFarmAnimal.friendshipTowardFarmer;
                    }
                }
            }
            List <ClickableTextureComponent> animals1 = this.animals;
            string    name1   = "";
            Rectangle bounds1 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize, Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label1  = string.Concat((object)num1);
            string    str1    = "Chickens";
            string    str2;

            if (num1 <= 0)
            {
                str2 = "";
            }
            else
            {
                str2 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num9 / num1));
            }
            string    hoverText1    = str1 + str2;
            Texture2D mouseCursors1 = Game1.mouseCursors;
            Rectangle sourceRect1   = new Rectangle(Game1.tileSize * 4, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num17         = 1.0;
            int       num18         = 0;
            ClickableTextureComponent textureComponent1 = new ClickableTextureComponent(name1, bounds1, label1, hoverText1, mouseCursors1, sourceRect1, (float)num17, num18 != 0);

            animals1.Add(textureComponent1);
            List <ClickableTextureComponent> animals2 = this.animals;
            string    name2   = "";
            Rectangle bounds2 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label2  = string.Concat((object)num2);
            string    str3    = "Ducks";
            string    str4;

            if (num2 <= 0)
            {
                str4 = "";
            }
            else
            {
                str4 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num11 / num2));
            }
            string    hoverText2    = str3 + str4;
            Texture2D mouseCursors2 = Game1.mouseCursors;
            Rectangle sourceRect2   = new Rectangle(Game1.tileSize * 4 + Game1.tileSize / 2, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num19         = 1.0;
            int       num20         = 0;
            ClickableTextureComponent textureComponent2 = new ClickableTextureComponent(name2, bounds2, label2, hoverText2, mouseCursors2, sourceRect2, (float)num19, num20 != 0);

            animals2.Add(textureComponent2);
            List <ClickableTextureComponent> animals3 = this.animals;
            string    name3   = "";
            Rectangle bounds3 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 2 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label3  = string.Concat((object)num3);
            string    str5    = "Rabbits";
            string    str6;

            if (num3 <= 0)
            {
                str6 = "";
            }
            else
            {
                str6 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num10 / num3));
            }
            string    hoverText3    = str5 + str6;
            Texture2D mouseCursors3 = Game1.mouseCursors;
            Rectangle sourceRect3   = new Rectangle(Game1.tileSize * 4, Game1.tileSize + Game1.tileSize / 2, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num21         = 1.0;
            int       num22         = 0;
            ClickableTextureComponent textureComponent3 = new ClickableTextureComponent(name3, bounds3, label3, hoverText3, mouseCursors3, sourceRect3, (float)num21, num22 != 0);

            animals3.Add(textureComponent3);
            List <ClickableTextureComponent> animals4 = this.animals;
            string    name4   = "";
            Rectangle bounds4 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 3 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label4  = string.Concat((object)num5);
            string    str7    = "Cows";
            string    str8;

            if (num5 <= 0)
            {
                str8 = "";
            }
            else
            {
                str8 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num13 / num5));
            }
            string    hoverText4    = str7 + str8;
            Texture2D mouseCursors4 = Game1.mouseCursors;
            Rectangle sourceRect4   = new Rectangle(Game1.tileSize * 5, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num23         = 1.0;
            int       num24         = 0;
            ClickableTextureComponent textureComponent4 = new ClickableTextureComponent(name4, bounds4, label4, hoverText4, mouseCursors4, sourceRect4, (float)num23, num24 != 0);

            animals4.Add(textureComponent4);
            List <ClickableTextureComponent> animals5 = this.animals;
            string    name5   = "";
            Rectangle bounds5 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 4 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label5  = string.Concat((object)num7);
            string    str9    = "Goats";
            string    str10;

            if (num7 <= 0)
            {
                str10 = "";
            }
            else
            {
                str10 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num14 / num7));
            }
            string    hoverText5    = str9 + str10;
            Texture2D mouseCursors5 = Game1.mouseCursors;
            Rectangle sourceRect5   = new Rectangle(Game1.tileSize * 5 + Game1.tileSize / 2, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num25         = 1.0;
            int       num26         = 0;
            ClickableTextureComponent textureComponent5 = new ClickableTextureComponent(name5, bounds5, label5, hoverText5, mouseCursors5, sourceRect5, (float)num25, num26 != 0);

            animals5.Add(textureComponent5);
            List <ClickableTextureComponent> animals6 = this.animals;
            string    name6   = "";
            Rectangle bounds6 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 5 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label6  = string.Concat((object)num6);
            string    str11   = "Sheep";
            string    str12;

            if (num6 <= 0)
            {
                str12 = "";
            }
            else
            {
                str12 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num15 / num6));
            }
            string    hoverText6    = str11 + str12;
            Texture2D mouseCursors6 = Game1.mouseCursors;
            Rectangle sourceRect6   = new Rectangle(Game1.tileSize * 5 + Game1.tileSize / 2, Game1.tileSize + Game1.tileSize / 2, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num27         = 1.0;
            int       num28         = 0;
            ClickableTextureComponent textureComponent6 = new ClickableTextureComponent(name6, bounds6, label6, hoverText6, mouseCursors6, sourceRect6, (float)num27, num28 != 0);

            animals6.Add(textureComponent6);
            List <ClickableTextureComponent> animals7 = this.animals;
            string    name7   = "";
            Rectangle bounds7 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 6 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label7  = string.Concat((object)num8);
            string    str13   = "Pigs";
            string    str14;

            if (num8 <= 0)
            {
                str14 = "";
            }
            else
            {
                str14 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num16 / num8));
            }
            string    hoverText7    = str13 + str14;
            Texture2D mouseCursors7 = Game1.mouseCursors;
            Rectangle sourceRect7   = new Rectangle(Game1.tileSize * 5, Game1.tileSize + Game1.tileSize / 2, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num29         = 1.0;
            int       num30         = 0;
            ClickableTextureComponent textureComponent7 = new ClickableTextureComponent(name7, bounds7, label7, hoverText7, mouseCursors7, sourceRect7, (float)num29, num30 != 0);

            animals7.Add(textureComponent7);
            List <ClickableTextureComponent> animals8 = this.animals;
            string    name8   = "";
            Rectangle bounds8 = new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 7 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2);
            string    label8  = string.Concat((object)num4);
            string    str15   = "???";
            string    str16;

            if (num4 <= 0)
            {
                str16 = "";
            }
            else
            {
                str16 = Environment.NewLine + Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10425", (object)(num12 / num4));
            }
            string    hoverText8    = str15 + str16;
            Texture2D mouseCursors8 = Game1.mouseCursors;
            Rectangle sourceRect8   = new Rectangle(Game1.tileSize * 4 + Game1.tileSize / 2, Game1.tileSize + Game1.tileSize / 2, Game1.tileSize / 2, Game1.tileSize / 2);
            double    num31         = 1.0;
            int       num32         = 0;
            ClickableTextureComponent textureComponent8 = new ClickableTextureComponent(name8, bounds8, label8, hoverText8, mouseCursors8, sourceRect8, (float)num31, num32 != 0);

            animals8.Add(textureComponent8);
            this.animals.Add(new ClickableTextureComponent("", new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 8 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2), string.Concat((object)Game1.stats.CropsShipped), Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10440"), Game1.mouseCursors, new Rectangle(Game1.tileSize * 7 + Game1.tileSize / 2, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2), 1f, false));
            this.animals.Add(new ClickableTextureComponent("", new Rectangle(x + IClickableMenu.spaceToClearSideBorder + Game1.tileSize / 2, y + IClickableMenu.spaceToClearTopBorder + Game1.tileSize + 9 * (Game1.tileSize / 2 + 4), Game1.tileSize / 2 + 8, Game1.tileSize / 2), string.Concat((object)this.farm.buildings.Count <Building>()), Game1.content.LoadString("Strings\\StringsFromCSFiles:FarmInfoPage.cs.10441"), Game1.mouseCursors, new Rectangle(Game1.tileSize * 7, Game1.tileSize, Game1.tileSize / 2, Game1.tileSize / 2), 1f, false));
            int num33 = 8;

            foreach (Building building in this.farm.buildings)
            {
                this.mapBuildings.Add(new ClickableTextureComponent("", new Rectangle(this.mapX + building.tileX * num33, this.mapY + building.tileY * num33 + (building.tilesHigh + 1) * num33 - (int)((double)building.texture.Height / 8.0), building.tilesWide * num33, (int)((double)building.texture.Height / 8.0)), "", building.buildingType, building.texture, building.getSourceRectForMenu(), 0.125f, false));
            }
            foreach (KeyValuePair <Vector2, TerrainFeature> terrainFeature in (Dictionary <Vector2, TerrainFeature>) this.farm.terrainFeatures)
            {
                this.mapFeatures.Add(new MiniatureTerrainFeature(terrainFeature.Value, new Vector2(terrainFeature.Key.X * (float)num33 + (float)this.mapX, terrainFeature.Key.Y * (float)num33 + (float)this.mapY), terrainFeature.Key, 0.125f));
            }
            if (!(Game1.currentLocation.GetType() == typeof(Farm)))
            {
                return;
            }
            this.mapFarmer = new ClickableTextureComponent("", new Rectangle(this.mapX + (int)((double)Game1.player.Position.X / 8.0), this.mapY + (int)((double)Game1.player.position.Y / 8.0), 8, 12), "", Game1.player.name, (Texture2D)null, new Rectangle(0, 0, Game1.tileSize, Game1.tileSize * 3 / 2), 0.125f, false);
        }
コード例 #29
0
        public void importFarm(string[] p)
        {
            if (Game1.currentLocation is Farm)
            {
                Monitor.Log("You can't do this while you are on the farm", LogLevel.Warn);
                return;
            }

            if (p.Length == 0)
            {
                Monitor.Log("No plan id provided", LogLevel.Warn);
                return;
            }

            string id = p[0];

            if (!Imports.ContainsKey(id))
            {
                Monitor.Log("Could not find a plan with the id " + id + ". Checking online..", LogLevel.Warn);
                importFarmWeb(p);
                return;
            }
            Import import = Imports[id];


            Monitor.Log("Clearing Farm", LogLevel.Trace);

            Farm farm = Game1.getFarm();

            farm.objects.Clear();
            farm.largeTerrainFeatures.Clear();
            farm.terrainFeatures.Clear();
            farm.buildings.Clear();
            farm.animals.Clear();
            farm.resourceClumps.Clear();

            Monitor.Log("OK", LogLevel.Trace);

            Monitor.Log("Importing: " + id, LogLevel.Info);
            List <ImportTile> list = import.tiles;

            list.AddRange(import.buildings);
            foreach (ImportTile tile in list)
            {
                Vector2 pos = new Vector2(int.Parse(tile.x) / 16, int.Parse(tile.y) / 16);

                TerrainFeature tf = getTerrainFeature(tile.type, pos);
                if (tf != null)
                {
                    if (tf is FruitTree ft)
                    {
                        ft.growthStage.Value     = 5;
                        ft.daysUntilMature.Value = 0;
                    }

                    if (farm.terrainFeatures.ContainsKey(pos))
                    {
                        farm.terrainFeatures[pos] = tf;
                    }
                    else
                    {
                        farm.terrainFeatures.Add(pos, tf);
                    }
                }

                SObject obj = getObject(tile.type, pos);
                if (obj != null)
                {
                    if (farm.Objects.ContainsKey(pos))
                    {
                        farm.Objects[pos] = obj;
                    }
                    else
                    {
                        farm.Objects.Add(pos, obj);
                    }
                }

                Building building = getBuilding(tile.type, pos);
                if (building != null)
                {
                    building.daysOfConstructionLeft.Value = 0;
                    farm.buildings.Add(building);
                }

                if (tile.type == "large-log")
                {
                    farm.addResourceClumpAndRemoveUnderlyingTerrain(602, 2, 2, pos);
                }

                if (tile.type == "large-stump")
                {
                    farm.addResourceClumpAndRemoveUnderlyingTerrain(600, 2, 2, pos);
                }


                if (tile.type == "large-rock")
                {
                    farm.addResourceClumpAndRemoveUnderlyingTerrain(752, 2, 2, pos);
                }

                if (!tile.type.StartsWith("large-") && building == null && obj == null && tf == null)
                {
                    Monitor.Log("Could not place tile: " + tile.type + " (unknown type)", LogLevel.Warn);
                }
            }
        }
コード例 #30
0
        /// <summary>Get the data to display for this subject.</summary>
        public override IEnumerable <ICustomField> GetData()
        {
            // get info
            Building building     = this.Target;
            bool     built        = !building.isUnderConstruction();
            int?     upgradeLevel = this.GetUpgradeLevel(building);

            // construction / upgrade
            if (!built || building.daysUntilUpgrade.Value > 0)
            {
                int   daysLeft  = building.isUnderConstruction() ? building.daysOfConstructionLeft.Value : building.daysUntilUpgrade.Value;
                SDate readyDate = SDate.Now().AddDays(daysLeft);
                yield return(new GenericField(I18n.Building_Construction(), I18n.Building_Construction_Summary(date: this.Stringify(readyDate))));
            }

            // owner
            Farmer owner = this.GetOwner();

            if (owner != null)
            {
                yield return(new LinkField(I18n.Building_Owner(), owner.Name, () => this.Codex.GetByEntity(owner)));
            }
            else if (building.indoors.Value is Cabin)
            {
                yield return(new GenericField(I18n.Building_Owner(), I18n.Building_Owner_None()));
            }

            // stable horse
            if (built && building is Stable stable)
            {
                Horse horse = Utility.findHorse(stable.HorseId);
                if (horse != null)
                {
                    yield return(new LinkField(I18n.Building_Horse(), horse.Name, () => this.Codex.GetByEntity(horse)));

                    yield return(new GenericField(I18n.Building_HorseLocation(), I18n.Building_HorseLocation_Summary(location: horse.currentLocation.Name, x: horse.getTileX(), y: horse.getTileY())));
                }
            }

            // animals
            if (built && building.indoors.Value is AnimalHouse animalHouse)
            {
                // animal counts
                yield return(new GenericField(I18n.Building_Animals(), I18n.Building_Animals_Summary(count: animalHouse.animalsThatLiveHere.Count, max: animalHouse.animalLimit.Value)));

                // feed trough
                if ((building is Barn || building is Coop) && upgradeLevel >= 2)
                {
                    yield return(new GenericField(I18n.Building_FeedTrough(), I18n.Building_FeedTrough_Automated()));
                }
                else
                {
                    this.GetFeedMetrics(animalHouse, out int totalFeedSpaces, out int filledFeedSpaces);
                    yield return(new GenericField(I18n.Building_FeedTrough(), I18n.Building_FeedTrough_Summary(filled: filledFeedSpaces, max: totalFeedSpaces)));
                }
            }

            // slimes
            if (built && building.indoors.Value is SlimeHutch slimeHutch)
            {
                // slime count
                int slimeCount = slimeHutch.characters.OfType <GreenSlime>().Count();
                yield return(new GenericField(I18n.Building_Slimes(), I18n.Building_Slimes_Summary(count: slimeCount, max: 20)));

                // water trough
                yield return(new GenericField(I18n.Building_WaterTrough(), I18n.Building_WaterTrough_Summary(filled: slimeHutch.waterSpots.Count(p => p), max: slimeHutch.waterSpots.Count)));
            }

            // upgrade level
            if (built)
            {
                var upgradeLevelSummary = this.GetUpgradeLevelSummary(building, upgradeLevel).ToArray();
                if (upgradeLevelSummary.Any())
                {
                    yield return(new CheckboxListField(I18n.Building_Upgrades(), upgradeLevelSummary));
                }
            }

            // specific buildings
            if (built)
            {
                switch (building)
                {
                // fish pond
                case FishPond pond:
                    if (pond.fishType.Value <= -1)
                    {
                        yield return(new GenericField(I18n.Building_FishPond_Population(), I18n.Building_FishPond_Population_Empty()));
                    }
                    else
                    {
                        // get fish population
                        SObject fish = pond.GetFishObject();
                        fish.Stack = pond.FishCount;
                        var pondData = pond.GetFishPondData();

                        // population field
                        {
                            string populationStr = $"{fish.DisplayName} ({I18n.Generic_Ratio(pond.FishCount, pond.maxOccupants.Value)})";
                            if (pond.FishCount < pond.maxOccupants.Value)
                            {
                                SDate nextSpawn = SDate.Now().AddDays(pondData.SpawnTime - pond.daysSinceSpawn.Value);
                                populationStr += Environment.NewLine + I18n.Building_FishPond_Population_NextSpawn(relativeDate: this.GetRelativeDateStr(nextSpawn));
                            }

                            yield return(new ItemIconField(this.GameHelper, I18n.Building_FishPond_Population(), fish, text: populationStr));
                        }

                        // output
                        yield return(new ItemIconField(this.GameHelper, I18n.Building_OutputReady(), pond.output.Value));

                        // drops
                        int chanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, pond.currentOccupants.Value / 10f) * 100);
                        yield return(new FishPondDropsField(this.GameHelper, I18n.Building_FishPond_Drops(), pond.currentOccupants.Value, pondData, preface: I18n.Building_FishPond_Drops_Preface(chance: chanceOfAnyDrop.ToString())));

                        // quests
                        if (pondData.PopulationGates?.Any(gate => gate.Key > pond.lastUnlockedPopulationGate.Value) == true)
                        {
                            yield return(new CheckboxListField(I18n.Building_FishPond_Quests(), this.GetPopulationGates(pond, pondData)));
                        }
                    }
                    break;

                // Junimo hut
                case JunimoHut hut:
                    yield return(new GenericField(I18n.Building_JunimoHarvestingEnabled(), I18n.Stringify(!hut.noHarvest.Value)));

                    yield return(new ItemIconListField(this.GameHelper, I18n.Building_OutputReady(), hut.output.Value?.GetItemsForPlayer(Game1.player.UniqueMultiplayerID), showStackSize: true));

                    break;

                // mill
                case Mill mill:
                    yield return(new ItemIconListField(this.GameHelper, I18n.Building_OutputProcessing(), mill.input.Value?.GetItemsForPlayer(Game1.player.UniqueMultiplayerID), showStackSize: true));

                    yield return(new ItemIconListField(this.GameHelper, I18n.Building_OutputReady(), mill.output.Value?.GetItemsForPlayer(Game1.player.UniqueMultiplayerID), showStackSize: true));

                    break;

                // silo
                case Building _ when building.buildingType.Value == "Silo":
                {
                    // hay summary
                    Farm farm      = Game1.getFarm();
                    int  siloCount = Utility.numSilos();
                    int  hayCount  = farm.piecesOfHay.Value;
                    int  maxHay    = Math.Max(farm.piecesOfHay.Value, siloCount * 240);
                    yield return(new GenericField(
                                     I18n.Building_StoredHay(),
                                     siloCount == 1
                                    ? I18n.Building_StoredHay_SummaryOneSilo(hayCount: hayCount, maxHay: maxHay)
                                    : I18n.Building_StoredHay_SummaryMultipleSilos(hayCount: hayCount, maxHay: maxHay, siloCount: siloCount)
                                     ));
                }
                break;
                }
            }
        }
        public static void CollectInput(Farm farm)
        {
            if (farm.ChickenHouses.Count == 0 &&
                farm.GrazingFields.Count == 0)
            {
                Console.WriteLine("*** Oops! You don't have any meat-producing facilities! ***");
                Console.WriteLine("*** Press return key to go back to main menu.");
                Console.ReadLine();
            }
            else
            {
                // Create list of facilities that can have eggs:
                List <Facility> FacilitiesThatHaveMeatAnimals = new List <Facility>();
                foreach (Facility facility in farm.GrazingFields)
                {
                    FacilitiesThatHaveMeatAnimals.Add(facility);
                }
                foreach (Facility facility in farm.ChickenHouses)
                {
                    FacilitiesThatHaveMeatAnimals.Add(facility);
                }

                // Show users options for facilities
                for (int i = 0; i < FacilitiesThatHaveMeatAnimals.Count; i++)
                {
                    var groupedAnimals = FacilitiesThatHaveMeatAnimals[i].Resources.GroupBy(
                        currentAnimal => currentAnimal.Type
                        );

                    var animalsString = "";
                    foreach (var group in groupedAnimals)
                    {
                        animalsString += group.Count() + " " + group.Key + ", ";
                    }
                    ;


                    Console.WriteLine($"{i + 1}: {FacilitiesThatHaveMeatAnimals[i].GetType().ToString().Split(".")[FacilitiesThatHaveMeatAnimals[i].GetType().ToString().Split(".").Count() - 1]} -- {animalsString} ");
                }


                Console.WriteLine();
                Console.WriteLine($"Which facility has the animals you want to process?");
                Console.Write("> ");

                int facilityChoiceNum = Int32.Parse(Console.ReadLine()) - 1;
                if (facilityChoiceNum <= FacilitiesThatHaveMeatAnimals.Count)
                {
                    var chosenFacility            = FacilitiesThatHaveMeatAnimals[facilityChoiceNum];
                    var chosenFacilityId          = chosenFacility.ShortId;
                    var chosenFacilityAnimalTypes = chosenFacility.Resources
                                                    .GroupBy(animal => animal.Type)
                                                    .Select(grp => grp.ToList())
                                                    .ToList();
                    Console.WriteLine("The following resource types are in that facility:");
                    for (int i = 0; i < chosenFacilityAnimalTypes.Count; i++)
                    {
                        Console.WriteLine($"{i + 1}: {chosenFacilityAnimalTypes[i].Count} x {chosenFacilityAnimalTypes[i][0].Type}");
                    }

                    Console.WriteLine();
                    Console.WriteLine("Which resource would you like to GRIND INTO MEAT?");
                    Console.Write("> ");


                    int animalTypeChoiceNum = Int32.Parse(Console.ReadLine()) - 1;

                    string  chosenAnimalType         = chosenFacilityAnimalTypes[animalTypeChoiceNum][0].Type;
                    dynamic resourceClassTemplate    = Activator.CreateInstance(chosenFacilityAnimalTypes[animalTypeChoiceNum][0].GetType());
                    double  meatConversionMultiplier = ((IMeatProducing)chosenFacilityAnimalTypes[animalTypeChoiceNum][0])._meatProduced;

                    if (animalTypeChoiceNum <= chosenFacilityAnimalTypes.Count)
                    {
                        Console.WriteLine($"How many of this type of resource would you like to GRIND INTO MEAT?");
                        Console.Write("> ");

                        int numResourcesToProcessNum = Int32.Parse(Console.ReadLine());

                        if (numResourcesToProcessNum <= chosenFacilityAnimalTypes[animalTypeChoiceNum].Count)
                        {
                            int MeatReturned = numResourcesToProcessNum * Convert.ToInt32(meatConversionMultiplier);

                            Console.WriteLine($"Are you sure you want to process these into {MeatReturned} pounds of meat? (y or n)");
                            Console.WriteLine("> ");

                            string yesOrNo = Console.ReadLine();
                            if (yesOrNo == "y")
                            {
                                Console.WriteLine($"You did what you had to do. You have compressed {numResourcesToProcessNum} {chosenAnimalType} into {MeatReturned} pounds of meat...");

                                try
                                {
                                    for (var i = 0; i <= numResourcesToProcessNum - 1; i++)
                                    {
                                        farm.GrazingFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                        .RemoveAt(farm.GrazingFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                                  .FindIndex(animal => animal.Type == resourceClassTemplate.Type));
                                    }
                                }
                                catch
                                {
                                }
                                try
                                {
                                    farm.PlowedFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                    .RemoveAt(farm.PlowedFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                              .FindIndex(animal => animal.Type == resourceClassTemplate.Type));
                                }
                                catch
                                {
                                }
                                try
                                {
                                    farm.NaturalFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                    .RemoveAt(farm.NaturalFields.Single(field => field.ShortId == chosenFacilityId).Resources
                                              .FindIndex(animal => animal.Type == resourceClassTemplate.Type));
                                }
                                catch
                                {
                                }
                                try
                                {
                                    farm.ChickenHouses.Single(field => field.ShortId == chosenFacilityId).Resources
                                    .RemoveAt(farm.ChickenHouses.Single(field => field.ShortId == chosenFacilityId).Resources
                                              .FindIndex(animal => animal.Type == resourceClassTemplate.Type));
                                }
                                catch
                                {
                                }
                                try
                                {
                                    farm.DuckHouses.Single(field => field.ShortId == chosenFacilityId).Resources
                                    .RemoveAt(farm.DuckHouses.Single(field => field.ShortId == chosenFacilityId).Resources
                                              .FindIndex(animal => animal.Type == resourceClassTemplate.Type));
                                }
                                catch
                                {
                                }
                            }
                            else
                            {
                                Console.WriteLine("You are truly merciful...");
                            }
                        }
                        else
                        {
                            Console.WriteLine("You dont have enough of that resource to compress into that many eggs....");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid choice, rerouting to main menu");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid choice, rerouting to main menu");
                }
            }
        }
コード例 #32
0
        protected override void FirstScan()
        {
            if (_who == AnimalsTaskId.None)
            {
                _who = _id;
            }
            else if (_who != _id)
            {
                return;
            }

            if (ObjectsNames.Count == 0)
            {
                PopulateObjectsNames();
            }

            _farm = Game1.locations.First(l => l is Farm) as Farm;

            // Checking animals left outside
            CheckAnimals(_farm);

            // ReSharper disable once PossibleNullReferenceException
            foreach (var building in _farm.buildings)
            {
                if (building.isUnderConstruction())
                {
                    continue;
                }

                switch (building.indoors.Value)
                {
                case AnimalHouse animalHouse:
                    // Check animals
                    CheckAnimals(animalHouse);

                    // Check for object in Coop
                    if (building is Coop)
                    {
                        CheckAnimalProductsInCoop(animalHouse);
                    }

                    // Check for hay
                    var count       = animalHouse.numberOfObjectsWithName("Hay");
                    var animalLimit = animalHouse.animalLimit.Value;
                    if (count < animalLimit)
                    {
                        MissingHay.Add(new Tuple <Building, int>(building, animalLimit - count));
                    }
                    break;

                case SlimeHutch slimeHutch:
                    // Check slime balls
                    foreach (var pair in building.indoors.Value.objects.Pairs)
                    {
                        if (pair.Value.ParentSheetIndex >= 56 && pair.Value.ParentSheetIndex <= 61)
                        {
                            AnimalProductsToCollect.Add(new TaskItem <SObject>(slimeHutch, pair.Key, pair.Value));
                        }
                    }
                    break;

                default:
                    break;
                }
            }

            CheckForTruffles(_farm);
        }
コード例 #33
0
        private void ControlEvents_KeyReleased(object sender, EventArgsKeyPressed e)
        {
            //Codes for my testing,,,,
            if (e.KeyPressed == Keys.Y)
            {
                if (!Context.IsWorldReady)
                {
                    return;
                }
                Farm farm     = Game1.getFarm();
                int  outty    = rnd.Next(0, 100);
                int  ToShroom = rnd.Next(1, this.MaxToShroom);
                //Make sure We can proceed.
                this.Monitor.Log($"Result: {outty} Change: {this.Config.ShroomChance}");
                if (outty > this.Config.ShroomChance)
                {
                    return;
                }
                if (Debugging)
                {
                    Monitor.Log("Made it passed line 54", LogLevel.Alert);
                }


                for (int i = 0; i < ToShroom; i++)
                {
                    //We go through each of the chances to create a shroom trr
                    if (farm.terrainFeatures.Count > 0)
                    {
                        if (Debugging)
                        {
                            Monitor.Log("Made it passed line 63", LogLevel.Alert);
                        }

                        TerrainFeature terrain = farm.terrainFeatures.ElementAt <KeyValuePair <Vector2, TerrainFeature> >(rnd.Next(farm.terrainFeatures.Count)).Value;

                        if (Debugging)
                        {
                            Monitor.Log("Made it passed line 67", LogLevel.Alert);
                        }
                        if (terrain is Tree && (terrain as Tree).growthStage >= 5 && !(terrain as Tree).tapped)
                        {
                            if (Debugging)
                            {
                                Monitor.Log("Made it passed line 71", LogLevel.Alert);
                            }
                            (terrain as Tree).treeType.Value = 7;
                            (terrain as Tree).loadSprite();

                            if (Debugging)
                            {
                                Monitor.Log("Made it passed line 76", LogLevel.Alert);
                            }
                        }
                    }
                }

                /*
                 * foreach (var location in Game1.locations)
                 * {
                 *  if (location.isFarm && (location.name.Contains("FarmExpan")))
                 *  {
                 *
                 *  }
                 * }*/
            }
            if (e.KeyPressed == Keys.F5)
            {
                this.Config       = Helper.ReadConfig <ModConfig>();
                this.ModEnabled   = this.Config.ModEnabled;
                this.ShroomChance = this.Config.ShroomChance;
                this.MaxToShroom  = this.Config.MaxRandomtoShroom;
                Monitor.Log($"Config reloaded", LogLevel.Info);
            }
            if (e.KeyPressed == Keys.NumPad8)
            {
                Farm farm = Game1.getFarm();
                //Go through and get rid of objects
                foreach (KeyValuePair <Vector2, SObject> pair in farm.objects)
                {
                    //farm.removeObject(pair.Key, false);
                    pair.Value.performRemoveAction(pair.Key, farm);
                }
            }
        }
コード例 #34
0
 // Note, this method can take *any* type (BASE CLASS or INHERITOR) of 'Farm', 
 // as 'FeedAnimals()' is defined as 'virtual' (i.e. overrideable) 'Farm' behaviour.  
 private void FeedTheAnimalsAt(Farm farm)
 {
     farm.FeedAnimals();
 }
コード例 #35
0
ファイル: CoreAssets.cs プロジェクト: danscava/SMAPI
        /*********
        ** Public methods
        *********/
        /// <summary>Initialise the core asset data.</summary>
        /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
        public CoreAssets(Func <string, string> getNormalisedPath)
        {
            this.GetNormalisedPath = getNormalisedPath;
            this.SingletonSetters  =
                new Dictionary <string, Action <SContentManager, string> >
            {
                // from Game1.loadContent
                ["LooseSprites\\daybg"]                       = (content, key) => Game1.daybg = content.Load <Texture2D>(key),
                ["LooseSprites\\nightbg"]                     = (content, key) => Game1.nightbg = content.Load <Texture2D>(key),
                ["Maps\\MenuTiles"]                           = (content, key) => Game1.menuTexture = content.Load <Texture2D>(key),
                ["LooseSprites\\Lighting\\lantern"]           = (content, key) => Game1.lantern = content.Load <Texture2D>(key),
                ["LooseSprites\\Lighting\\windowLight"]       = (content, key) => Game1.windowLight = content.Load <Texture2D>(key),
                ["LooseSprites\\Lighting\\sconceLight"]       = (content, key) => Game1.sconceLight = content.Load <Texture2D>(key),
                ["LooseSprites\\Lighting\\greenLight"]        = (content, key) => Game1.cauldronLight = content.Load <Texture2D>(key),
                ["LooseSprites\\Lighting\\indoorWindowLight"] = (content, key) => Game1.indoorWindowLight = content.Load <Texture2D>(key),
                ["LooseSprites\\shadow"]                      = (content, key) => Game1.shadowTexture = content.Load <Texture2D>(key),
                ["LooseSprites\\Cursors"]                     = (content, key) => Game1.mouseCursors = content.Load <Texture2D>(key),
                ["LooseSprites\\ControllerMaps"]              = (content, key) => Game1.controllerMaps = content.Load <Texture2D>(key),
                ["TileSheets\\animations"]                    = (content, key) => Game1.animations = content.Load <Texture2D>(key),
                ["Data\\Achievements"]                        = (content, key) => Game1.achievements = content.Load <Dictionary <int, string> >(key),
                ["Data\\NPCGiftTastes"]                       = (content, key) => Game1.NPCGiftTastes = content.Load <Dictionary <string, string> >(key),
                ["Fonts\\SpriteFont1"]                        = (content, key) => Game1.dialogueFont = content.Load <SpriteFont>(key),
                ["Fonts\\SmallFont"]                          = (content, key) => Game1.smallFont = content.Load <SpriteFont>(key),
                ["Fonts\\tinyFont"]                           = (content, key) => Game1.tinyFont = content.Load <SpriteFont>(key),
                ["Fonts\\tinyFontBorder"]                     = (content, key) => Game1.tinyFontBorder = content.Load <SpriteFont>(key),
                ["Maps\\springobjects"]                       = (content, key) => Game1.objectSpriteSheet = content.Load <Texture2D>(key),
                ["TileSheets\\crops"]                         = (content, key) => Game1.cropSpriteSheet = content.Load <Texture2D>(key),
                ["TileSheets\\emotes"]                        = (content, key) => Game1.emoteSpriteSheet = content.Load <Texture2D>(key),
                ["TileSheets\\debris"]                        = (content, key) => Game1.debrisSpriteSheet = content.Load <Texture2D>(key),
                ["TileSheets\\Craftables"]                    = (content, key) => Game1.bigCraftableSpriteSheet = content.Load <Texture2D>(key),
                ["TileSheets\\rain"]                          = (content, key) => Game1.rainTexture = content.Load <Texture2D>(key),
                ["TileSheets\\BuffsIcons"]                    = (content, key) => Game1.buffsIcons = content.Load <Texture2D>(key),
                ["Data\\ObjectInformation"]                   = (content, key) => Game1.objectInformation = content.Load <Dictionary <int, string> >(key),
                ["Data\\BigCraftablesInformation"]            = (content, key) => Game1.bigCraftablesInformation = content.Load <Dictionary <int, string> >(key),
                ["Characters\\Farmer\\hairstyles"]            = (content, key) => FarmerRenderer.hairStylesTexture = content.Load <Texture2D>(key),
                ["Characters\\Farmer\\shirts"]                = (content, key) => FarmerRenderer.shirtsTexture = content.Load <Texture2D>(key),
                ["Characters\\Farmer\\hats"]                  = (content, key) => FarmerRenderer.hatsTexture = content.Load <Texture2D>(key),
                ["Characters\\Farmer\\accessories"]           = (content, key) => FarmerRenderer.accessoriesTexture = content.Load <Texture2D>(key),
                ["TileSheets\\furniture"]                     = (content, key) => Furniture.furnitureTexture = content.Load <Texture2D>(key),
                ["LooseSprites\\font_bold"]                   = (content, key) => SpriteText.spriteTexture = content.Load <Texture2D>(key),
                ["LooseSprites\\font_colored"]                = (content, key) => SpriteText.coloredTexture = content.Load <Texture2D>(key),
                ["TileSheets\\weapons"]                       = (content, key) => Tool.weaponsTexture = content.Load <Texture2D>(key),
                ["TileSheets\\Projectiles"]                   = (content, key) => Projectile.projectileSheet = content.Load <Texture2D>(key),

                // from Game1.ResetToolSpriteSheet
                ["TileSheets\\tools"] = (content, key) => Game1.ResetToolSpriteSheet(),

                // from Bush
                ["TileSheets\\bushes"] = (content, key) => Bush.texture = content.Load <Texture2D>(key),

                // from Critter
                ["TileSheets\\critters"] = (content, key) => Critter.critterTexture = content.Load <Texture2D>(key),

                // from Farm
                ["Buildings\\houses"] = (content, key) =>
                {
                    Farm farm = Game1.getFarm();
                    if (farm != null)
                    {
                        farm.houseTextures = content.Load <Texture2D>(key);
                    }
                },

                // from Farmer
                ["Characters\\Farmer\\farmer_base"] = (content, key) =>
                {
                    if (Game1.player != null && Game1.player.isMale)
                    {
                        Game1.player.FarmerRenderer = new FarmerRenderer(content.Load <Texture2D>(key));
                    }
                },
                ["Characters\\Farmer\\farmer_girl_base"] = (content, key) =>
                {
                    if (Game1.player != null && !Game1.player.isMale)
                    {
                        Game1.player.FarmerRenderer = new FarmerRenderer(content.Load <Texture2D>(key));
                    }
                },

                // from Flooring
                ["TerrainFeatures\\Flooring"] = (content, key) => Flooring.floorsTexture = content.Load <Texture2D>(key),

                // from FruitTree
                ["TileSheets\\fruitTrees"] = (content, key) => FruitTree.texture = content.Load <Texture2D>(key),

                // from HoeDirt
                ["TerrainFeatures\\hoeDirt"]     = (content, key) => HoeDirt.lightTexture = content.Load <Texture2D>(key),
                ["TerrainFeatures\\hoeDirtDark"] = (content, key) => HoeDirt.darkTexture = content.Load <Texture2D>(key),
                ["TerrainFeatures\\hoeDirtSnow"] = (content, key) => HoeDirt.snowTexture = content.Load <Texture2D>(key),

                // from Wallpaper
                ["Maps\\walls_and_floors"] = (content, key) => Wallpaper.wallpaperTexture = content.Load <Texture2D>(key)
            }
            .ToDictionary(p => getNormalisedPath(p.Key), p => p.Value);
        }
        public static void CollectInput(Farm farm, IPlant plant)
        {
            Utils.Clear();

            try {
                for (int i = 1; i <= farm.PlowedFields.Count; i++)
                {
                    PlowedField field = farm.PlowedFields[i - 1];
                    if (field.Capacity > field.numOfPlants())
                    {
                        Console.WriteLine($"{i}. Plowed Field {field.shortId()} has {(field.numOfPlants() / 5)} rows of plants.");

                        // Print out the counts of each type of animal
                        var counts = field.Plants.GroupBy(plant => plant.Type)
                                     .Select(group => new PrintReport {
                            Name  = group.Key,
                            Count = group.Count()
                        });

                        foreach (PrintReport report in counts)
                        {
                            Console.WriteLine($"{report.Name}: {report.Count}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"{i}. Plowed Field {field.shortId()} is at capacity with {field.numOfPlants()} plants.");

                        // Print out the counts of each type of animal
                        var counts = field.Plants.GroupBy(plant => plant.Type)
                                     .Select(group => new PrintReport {
                            Name  = group.Key,
                            Count = group.Count()
                        });

                        foreach (PrintReport report in counts)
                        {
                            Console.WriteLine($"{report.Name}: {report.Count}");
                        }
                    }
                }

                Console.WriteLine();

                // How can I output the type of seed chosen here?
                Console.WriteLine($"Place the plant where?");

                Console.Write("> ");
                int choice = Int32.Parse(Console.ReadLine());

                farm.PlowedFields[choice - 1].AddResource(plant);
            } catch {
                Console.WriteLine("Please enter a valid selection.");
                Thread.Sleep(1000);
                CollectInput(farm, plant);
            }

            /*
             *  Couldn't get this to work. Can you?
             *  Stretch goal. Only if the app is fully functional.
             */
            // farm.PurchaseResource<IGrazing>(animal, choice);
        }
コード例 #37
0
        public static void Postfix()
        {
            int    farmIndex;
            Map    map;
            string mapAssetKey;

            if (Game1.whichFarm > 4)
            {
                if (Memory.loadedFarm == null)
                {
                    Memory.loadCustomFarmType(Game1.whichFarm);
                }

                for (farmIndex = 0; farmIndex < Game1.locations.Count; farmIndex++)
                {
                    if (Game1.locations[farmIndex].Name == "Farm")
                    {
                        break;
                    }
                }

                if (Memory.loadedFarm.farmMapType == fileType.raw)
                {
                    map = Memory.loadedFarm.contentpack.LoadAsset <Map>(Memory.loadedFarm.farmMapFile + ".tbin");
                }
                mapAssetKey = Memory.loadedFarm.contentpack.GetActualAssetKey(Memory.loadedFarm.farmMapFile + ((Memory.loadedFarm.farmMapType == fileType.raw) ? ".tbin" : ".xnb"));
                Game1.locations[farmIndex] = new Farm(mapAssetKey, "Farm");
            }

            Memory.farmMaps.Add(new additionalMap <Farm>("BaseFarm", "Farm", (Game1.whichFarm > 4) ? Memory.loadedFarm.farmMapType : fileType.xnb, "Farm", "Base Farm", Game1.getFarm()));

            if (Memory.isCustomFarmLoaded && Memory.loadedFarm.additionalMaps != null)
            {
                foreach (additionalMap <GameLocation> m in Memory.loadedFarm.additionalMaps)
                {
                    object newMap;

                    if (m.type == fileType.raw)
                    {
                        map = Memory.loadedFarm.contentpack.LoadAsset <Map>(m.FileName + ".tbin");
                    }

                    mapAssetKey = Memory.loadedFarm.contentpack.GetActualAssetKey(m.FileName + ((m.type == fileType.raw) ? ".tbin" : ".xnb"));

                    switch (m.mapType)
                    {
                    case "Farm":
                    case "FarmExpansion":
                    case "MTNFarmExtension":
                        newMap = new Farm(mapAssetKey, m.Location);
                        Game1.locations.Add((Farm)newMap);
                        //Game1.locations.Add(new FarmExtension(mapAssetKey, m.Location, newMap as Farm));
                        Memory.farmMaps.Add(new additionalMap <Farm>(m, Game1.locations.Last() as Farm));
                        break;

                    case "FarmCave":
                        newMap = new FarmCave(mapAssetKey, m.Location);
                        Game1.locations.Add((FarmCave)newMap);
                        break;

                    case "GameLocation":
                        newMap = new GameLocation(mapAssetKey, m.Location);
                        Game1.locations.Add((GameLocation)newMap);
                        break;

                    case "BuildableGameLocation":
                        newMap = new BuildableGameLocation(mapAssetKey, m.Location);
                        Game1.locations.Add((BuildableGameLocation)newMap);
                        break;

                    default:
                        newMap = new GameLocation(mapAssetKey, m.Location);
                        Game1.locations.Add((GameLocation)newMap);
                        break;
                    }
                    Memory.instance.Monitor.Log("Custom map loaded. Name: " + (newMap as GameLocation).Name + " Type: " + newMap.ToString());
                }
            }

            if (Memory.isCustomFarmLoaded && Memory.loadedFarm.overrideMaps != null)
            {
                int i;
                foreach (overrideMap m in Memory.loadedFarm.overrideMaps)
                {
                    if (m.type == fileType.raw)
                    {
                        map = Memory.loadedFarm.contentpack.LoadAsset <Map>(m.FileName + ".tbin");
                    }
                    mapAssetKey = Memory.loadedFarm.contentpack.GetActualAssetKey(m.FileName + ((m.type == fileType.raw) ? ".tbin" : ".xnb"));

                    for (i = 0; i < Game1.locations.Count; i++)
                    {
                        if (Game1.locations[i].Name == m.Location)
                        {
                            break;
                        }
                    }
                    if (i >= Game1.locations.Count)
                    {
                        Memory.instance.Monitor.Log(String.Format("Unable to replace {0}, map was not found. Skipping", m.Location), LogLevel.Warn);
                    }
                    else
                    {
                        switch (m.Location)
                        {
                        case "AdventureGuild":
                            Game1.locations[i] = new AdventureGuild(mapAssetKey, m.Location);
                            break;

                        case "BathHousePool":
                            Game1.locations[i] = new BathHousePool(mapAssetKey, m.Location);
                            break;

                        case "Beach":
                            Game1.locations[i] = new Beach(mapAssetKey, m.Location);
                            break;

                        case "BusStop":
                            Game1.locations[i] = new BusStop(mapAssetKey, m.Location);
                            break;

                        case "Club":
                            Game1.locations[i] = new Club(mapAssetKey, m.Location);
                            break;

                        case "Desert":
                            Game1.locations[i] = new Desert(mapAssetKey, m.Location);
                            break;

                        case "Forest":
                            Game1.locations[i] = new Forest(mapAssetKey, m.Location);
                            break;

                        case "FarmCave":
                            Game1.locations[i] = new FarmCave(mapAssetKey, m.Location);
                            break;

                        case "Mountain":
                            Game1.locations[i] = new Mountain(mapAssetKey, m.Location);
                            break;

                        case "Railroad":
                            Game1.locations[i] = new Railroad(mapAssetKey, m.Location);
                            break;

                        case "SeedShop":
                            Game1.locations[i] = new SeedShop(mapAssetKey, m.Location);
                            break;

                        case "Sewer":
                            Game1.locations[i] = new Sewer(mapAssetKey, m.Location);
                            break;

                        case "WizardHouse":
                            Game1.locations[i] = new WizardHouse(mapAssetKey, m.Location);
                            break;

                        case "Woods":
                            Game1.locations[i] = new Woods(mapAssetKey, m.Location);
                            break;

                        default:
                            Game1.locations[i] = new GameLocation(mapAssetKey, m.Location);
                            break;
                        }
                        Memory.instance.Monitor.Log("Map has been overridden with a custom map: " + m.Location);
                    }
                }
            }
        }
コード例 #38
0
        public static global::StardewValley.Object FormatAsAnimalAvailableForPurchase(Farm farm, string name, string displayName, string[] types, string[] buildings)
        {
            Locations.AnimalShop.RequiredBuildingIsBuilt(farm, buildings, out string type);

            // Divide the first price by two because of the weird functionality
            // in Object.salePrice(). Need to use ceiling even though it may
            // exclude the lowest type if the lowest price is an odd number.
            int price = (int)Math.Ceiling(Characters.FarmAnimal.GetCheapestPrice(types.ToList()) / 2f);

            global::StardewValley.Object obj = new global::StardewValley.Object(Locations.AnimalShop.PurchaseAnimalStockParentSheetIndex, Locations.AnimalShop.PurchaseAnimalStockQuantity, false, price)
            {
                Type        = type,
                displayName = displayName
            };

            // MUST do this outside of the block because it gets overridden in
            // the constructor
            obj.Name = name;

            return(obj);
        }
コード例 #39
0
ファイル: FarmTask.cs プロジェクト: scorvi/dwarfcorp
 public FarmTask(Farm farmToWork)
 {
     FarmToWork = farmToWork;
     Name = "Work " + FarmToWork.ID;
     Priority = PriorityType.Low;
 }
コード例 #40
-1
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Black;
            Console.BackgroundColor = ConsoleColor.DarkGreen;

            Farm Trestlebridge = new Farm();

            while (true)
            {
                DisplayBanner();
                Console.WriteLine("1. Create Facility");
                Console.WriteLine("2. Purchase Animals");
                Console.WriteLine("3. Purchase Seeds");
                Console.WriteLine("4. Display Farm Status");
                Console.WriteLine("5. Exit");
                Console.WriteLine();

                Console.WriteLine("Choose a FARMS option");
                Console.Write("> ");
                string option = Console.ReadLine();

                if (option == "1")
                {
                    DisplayBanner();
                    CreateFacility.CollectInput(Trestlebridge);
                    Console.WriteLine("Press return key to go back to main menu.");
                    Console.ReadLine();
                }
                else if (option == "2")
                {
                    DisplayBanner();
                    PurchaseStock.CollectInput(Trestlebridge);
                    Console.WriteLine("Press return key to go back to main menu.");
                    Console.ReadLine();
                }
                else if (option == "3")
                {
                    DisplayBanner();
                    PurchaseSeeds.CollectInput(Trestlebridge);
                    Console.WriteLine("Press return key to go back to main menu.");
                    Console.ReadLine();
                }
                else if (option == "4")
                {
                    DisplayBanner();
                    Console.WriteLine(Trestlebridge);
                    Console.WriteLine("\n\n\n");
                    Console.WriteLine("Press return key to go back to main menu.");
                    Console.ReadLine();
                }
                else if (option == "5")
                {
                    Console.WriteLine("Today is a great day for farming");
                    break;
                }
                else
                {
                    Console.WriteLine($"Invalid option: {option}");
                }
            }
        }