public override void Tick() { for (int i = 0; i < Find.Maps.Count; i++) { if (Find.Maps[i].lordManager.lords.Any(x => x.LordJob.GetType() == typeof(LordJob_AssaultColony))) { if (activeRaid == false) { activeRaid = true; if (!PlayerIsEnemyOfMankind && this.PatronFaction != null) { this.PatronFactionAssaultTick(this.PatronFaction); } } } } if (this.PlanetaryGovernor != null && this.PlanetaryGovernor.Dead) { this.PlanetaryGovernor = Find.WorldPawns.AllPawnsAlive.Where(x => x.Faction == Faction.OfPlayer).RandomElement(); string deadDesc = "GovernorDiedDesc".Translate(new object[] { PlanetaryGovernor.LabelCap, PlanetaryGovernor.filth }); Find.LetterStack.ReceiveLetter("LetterLabelGovernorDied".Translate(), deadDesc, LetterType.BadUrgent, null); } if (GenLocalDate.HourOfDay(Find.VisibleMap) == 4) { if (this.DaysToTitheCollection > 0) { this.DaysToTitheCollection--; } if (!this.currentTithes.NullOrEmpty() && this.DaysToTitheCollection == 0 && !TitheCollectionActive && this.AcknowledgedByImperium && this.PlanetaryGovernor != null) { InitializeTitheCollection(); } CalculateColonyCorruption(); EldarTicksDaily(); CorruptionTicksDaily(); } }
public static void ChangePriority(Pawn pawn, WorkTypeDef worktype, int diff, int hour, bool recache = true) { if (hour < 0) { hour = GenLocalDate.HourOfDay(pawn); } bool noChangeZeroPriority = Settings.Get().ignoreZeroSubPriorities&& GetMaxPriority(pawn, worktype, hour) != 0; foreach (WorkGiverDef workgiver in worktype.WorkGivers()) { ChangePriority(pawn, workgiver, diff, hour, false, noChangeZeroPriority); } if (recache) { PriorityManager.Get[pawn].Recache(worktype); } }
public override void CompTick() { base.CompTick(); if (Active && IsCheapIntervalTick) { GrowPlants(); } if (Active && Props.shouldSprinkleMotes) { if (GenLocalDate.HourOfDay(base.parent) == Props.sprinkleHour && !CurrentlySprinklingMotes && (GenTicks.TicksAbs - LastSprinkledMotesTick) >= GenDate.TicksPerHour * 23) { StartSprinklingMotes(); } else if (CurrentlySprinklingMotes) { SprinkleMotes(); } } }
public override void Tick() { base.Tick(); if (!LovePartnerRelationUtility.LovePartnerRelationExists(this.pawn, this.partner)) { this.pawn.health.RemoveHediff(this); } else if (Find.TickManager.TicksAbs >= this.day && GenLocalDate.HourOfDay(this.pawn) == this.hour) { if (ShouldStartDate(pawn, partner) && ShouldStartDate(partner, pawn)) { pawn.jobs.StopAll(); partner.jobs.StopAll(); if (pawn.GetLord() != null) { pawn.GetLord().Notify_PawnLost(pawn, PawnLostCondition.ForcedToJoinOtherLord); } if (partner.GetLord() != null) { partner.GetLord().Notify_PawnLost(partner, PawnLostCondition.ForcedToJoinOtherLord); } if (pawn.Awake() && partner.Awake()) { LordMaker.MakeNewLord(this.pawn.Faction, new LordJob_Date(this.pawn, this.partner), this.pawn.Map, new Pawn[] { this.pawn, this.partner }); } else if (pawn.Awake()) { this.pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MissedDate, this.partner); } else if (partner.Awake()) { this.partner.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MissedDate, this.pawn); } } else { this.pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.DateCancelled); this.partner.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.DateCancelled); } this.pawn.health.RemoveHediff(this); } }
public override void MapComponentTick() { base.MapComponentTick(); // check if an hour passed every second, staggering out maps if ((Find.TickManager.TicksGame + GetHashCode()) % 60 == 0 && GenLocalDate.HourOfDay(map) != currentHour) { // update our current hour currentHour = GenLocalDate.HourOfDay(map); Logger.Debug("forcing priority refresh for " + currentHour.FormatHour()); // make pawns update their priorities foreach (Pawn pawn in map.mapPawns.FreeColonistsSpawned) { pawn.workSettings.Notify_UseWorkPrioritiesChanged(); } } }
//generate PredictableSeed for Verse.Rand public static int PredictableSeed() { int seed = 0; try { Map map = Find.CurrentMap; //int seedHourOfDay = GenLocalDate.HourOfDay(map); //int seedDayOfYear = GenLocalDate.DayOfYear(map); //int seedYear = GenLocalDate.Year(map); seed = (GenLocalDate.HourOfDay(map) + GenLocalDate.DayOfYear(map)) * GenLocalDate.Year(map); //int seed = (seedHourOfDay + seedDayOfYear) * seedYear; //Log.Warning("seedHourOfDay: " + seedHourOfDay + "\nseedDayOfYear: " + seedDayOfYear + "\nseedYear: " + seedYear + "\n" + seed); } catch { seed = Rand.Int; } return(seed); }
public static void IncrementPriority(this WorkTypeDef worktype, Pawn pawn, int hour = -1, List <int> hours = null, bool playSound = true) { // get default hour if not specified if (hour < 0) { hour = GenLocalDate.HourOfDay(pawn); } // get and increment priority int priority = pawn.GetPriority(worktype, hour); pawn.SetPriority(worktype, priority + 1, hours); // play sounds if (Settings.playSounds && playSound && priority == 0) { SoundDefOf.AmountIncrement.PlayOneShotOnCamera(); } if (Settings.playSounds && playSound && priority > 0) { SoundDefOf.AmountDecrement.PlayOneShotOnCamera(); } }
public static void SetPriority(this Pawn pawn, WorkGiverDef workgiver, int priority, int hour, bool recache = true) { if (hour < 0) { hour = GenLocalDate.HourOfDay(pawn); } if (priority > Settings.maxPriority) { priority = 0; } if (priority < 0) { priority = Settings.maxPriority; } Logger.Trace($"Setting {pawn.LabelShort}'s {workgiver.defName} priority for {hour} to {priority}"); PriorityManager.Set[pawn][workgiver][hour] = priority; if (recache) { PriorityManager.Get[pawn].InvalidateCache(workgiver); } }
//TODO Finding a good way to Cache pawn.workSettings may increase performence public override Job TryGiveJob() { Job result = null; if (!(cachedSleepTimeList.Contains(GenLocalDate.HourOfDay(this).ToString()))) { Pawn pawn = MakeDrone(); GenSpawn.Spawn(pawn, Position, Map); pawn.workSettings = new Pawn_WorkSettings(pawn); pawn.workSettings.EnableAndInitialize(); pawn.workSettings.DisableAll(); //Set the workSettings based upon the settings foreach (WorkTypeDef def in WorkSettings.Keys) { if (WorkSettings[def]) { pawn.workSettings.SetPriority(def, 3); } else { pawn.workSettings.SetPriority(def, 0); } } result = TryIssueJobPackageDrone(pawn, true).Job; if (result == null) { result = TryIssueJobPackageDrone(pawn, false).Job; } pawn.Destroy(); Notify_DroneGained(); } return(result); }
public static void DecrementPriority(this WorkGiverDef workgiver, Pawn pawn, int hour, List <int> hours, bool playSound = true) { // get default hour if not specified if (hour < 0) { hour = GenLocalDate.HourOfDay(pawn); } // get and decrement priority int priority = pawn.GetPriority(workgiver, hour); pawn.SetPriority(workgiver, priority - 1, hours); // play sounds if (Settings.Get().playSounds&& playSound && priority > 1) { SoundDefOf.AmountIncrement.PlayOneShotOnCamera(); } if (Settings.Get().playSounds&& playSound && priority == 1) { SoundDefOf.AmountDecrement.PlayOneShotOnCamera(); } }
public override void CompTick() { base.CompTick(); var gainedEnergy = DesiredPowerOutput; AddEnergy(gainedEnergy * CompPower.WattsToWattDaysPerTick); if (compGlowerExtended.compGlower != null) { DrawPower(Mathf.Min(Props.selfCharging * CompPower.WattsToWattDaysPerTick, storedEnergy)); } if (compGlowerExtended != null) { var localHour = GenLocalDate.HourOfDay(this.parent.Map); if (localHour >= 8 && localHour <= 19) { if (compGlowerExtended.compGlower != null) { compGlowerExtended.RemoveGlower(); } } else { if (storedEnergy <= 0) { if (compGlowerExtended.compGlower != null) { compGlowerExtended.RemoveGlower(); } } else if (compGlowerExtended.compGlower == null) { compGlowerExtended.UpdateGlower(compGlowerExtended.currentColorInd); } } } }
public override void Tick(int currentTick) { //Constituent tick if (currentTick % GenDate.TicksPerHour * 2 == 0) { Map playerFactionMap = Find.WorldObjects.FactionBases.Find(b => b.Faction.IsPlayer).Map; IEnumerable <Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake() select p); if (constituents.Count() > 0) { Pawn potentialConstituent = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2)); IEnumerable <Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile && m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake() select m); if (potentialConstituent != null && activeMayors.Count() > 0) { Pawn mayor = activeMayors.RandomElement(); //There should only be one. PsychologyPawn psychologyConstituent = potentialConstituent as PsychologyPawn; IntVec3 gather = default(IntVec3); bool foundBed = false; if (mayor.ownership != null && mayor.ownership.OwnedBed != null) { gather = mayor.ownership.OwnedBed.Position; foundBed = true; } if ((psychologyConstituent == null || Rand.Value < (1f - psychologyConstituent.psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (foundBed || RCellFinder.TryFindPartySpot(mayor, out gather))) { List <Pawn> pawns = new List <Pawn>(); pawns.Add(mayor); pawns.Add(potentialConstituent); Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < 0.4f)), mayor.Map, pawns); if (!foundBed) { mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom); } } } } } //Election tick if (currentTick % (GenDate.TicksPerDay / 4f) == 0) { foreach (FactionBase factionBase in Find.WorldObjects.FactionBases) { //If the base isn't owned or named by the player, no election can be held. if (!factionBase.Faction.IsPlayer || !factionBase.namedByPlayer) { continue; } //Self-explanatory. if (!PsychologyBase.ActivateElections()) { continue; } //If the base is not at least a year old, no election will be held. if ((Find.TickManager.TicksGame - factionBase.creationGameTicks) / GenDate.TicksPerYear < 1) { continue; } //A base must have at least 7 people in it to hold an election. if (factionBase.Map.mapPawns.FreeColonistsSpawnedCount < 7) { continue; } //If an election is already being held, don't start a new one. if (factionBase.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || factionBase.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null) { continue; } //Elections are held in the fall and during the day. if (GenLocalDate.Season(factionBase.Map) != Season.Fall || (GenLocalDate.HourOfDay(factionBase.Map) < 7 || GenLocalDate.HourOfDay(factionBase.Map) > 20)) { continue; } //If an election has already been completed this year, don't start a new one. IEnumerable <Pawn> activeMayors = (from m in factionBase.Map.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == factionBase.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(factionBase.Map.Tile) select m); if (activeMayors.Count() > 0) { continue; } //Try to space out the elections so they don't all proc at once. if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfSeason(factionBase.Map.Tile)) > 1) { continue; } IncidentParms parms = new IncidentParms(); parms.target = factionBase.Map; parms.faction = factionBase.Faction; FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms); Find.Storyteller.TryFire(fi); } } }
void TickAction() { var fadeOff = Tools.PheromoneFadeoff(); var agitatedFadeoff = fadeOff / 4; var checkSmashableFadeoff = agitatedFadeoff / 2; var zombie = (Zombie)pawn; if (zombie.state == ZombieState.Emerging) { return; } var map = zombie.Map; if (zombie.Dead || zombie.Destroyed) { EndJobWith(JobCondition.InterruptForced); return; } if (zombie.state == ZombieState.ShouldDie) { EndJobWith(JobCondition.InterruptForced); zombie.Kill(null); return; } if (ZombieSettings.Values.zombiesDieVeryEasily) { if (zombie.health.hediffSet.GetHediffs <Hediff_Injury>().Any()) { zombie.Kill(null); return; } } if (zombie.Downed) { if (ZombieSettings.Values.zombiesDieVeryEasily || ZombieSettings.Values.doubleTapRequired == false) { zombie.Kill(null); return; } var walkCapacity = PawnCapacityUtility.CalculateCapacityLevel(zombie.health.hediffSet, PawnCapacityDefOf.Moving); var missingBrain = zombie.health.hediffSet.GetBrain() == null; if (walkCapacity < 0.25f || missingBrain) { zombie.Kill(null); return; } var injuries = zombie.health.hediffSet.GetHediffs <Hediff_Injury>(); foreach (var injury in injuries) { if (ZombieSettings.Values.zombiesDieVeryEasily) { zombie.Kill(null); return; } if (injury.IsOld() == false) { injury.Heal(injury.Severity + 0.5f); break; } } if (zombie.Downed) { return; } } // handling invalid destinations // if (destination.x == 0 && destination.z == 0) { destination = IntVec3.Invalid; } if (zombie.HasValidDestination(destination)) { return; } // if we are near targets then attack them // var enemy = CanAttack(); if (enemy != null) { destination = enemy.Position; zombie.state = ZombieState.Tracking; if (Constants.USE_SOUND) { var info = SoundInfo.InMap(enemy); SoundDef.Named("ZombieHit").PlayOneShot(info); } AttackThing(enemy, JobDefOf.AttackMelee); return; } // eat a downed or dead pawn // if (eatTarget == null) { eatTarget = CanIngest(out eatTargetIsCorpse); if (eatTarget != null) { eatTargetDied = eatTarget.Dead; } } if (eatTarget != null) { if (eatDelayCounter == 0) { if (eatTarget != lastEatTarget) { lastEatTarget = eatTarget; zombie.Drawer.rotator.FaceCell(eatTarget.Position); var zombieLeaner = zombie.Drawer.leaner as ZombieLeaner; if (zombieLeaner != null) { zombieLeaner.extraOffset = (eatTarget.Position.ToVector3() - zombie.Position.ToVector3()) * 0.5f; } Tools.CastThoughtBubble(pawn, Constants.EATING); } CastEatingSound(); } eatDelayCounter++; if (eatDelayCounter <= EatDelay) { return; } eatDelayCounter = 0; var bodyPartRecord = FirstEatablePart(eatTarget); if (bodyPartRecord != null) { var hediff_MissingPart = (Hediff_MissingPart)HediffMaker.MakeHediff(HediffDefOf.MissingBodyPart, eatTarget, bodyPartRecord); hediff_MissingPart.lastInjury = HediffDefOf.Bite; hediff_MissingPart.IsFresh = true; eatTarget.health.AddHediff(hediff_MissingPart, null, null); if (eatTargetIsCorpse == false && eatTargetDied == false && eatTarget.Dead) { Tools.DoWithAllZombies(map, z => { if (z.jobs != null) { var driver = z.jobs.curDriver as JobDriver_Stumble; if (driver != null && driver.eatTarget == eatTarget) { driver.eatTargetDied = true; driver.eatTargetIsCorpse = true; } } }); if (PawnUtility.ShouldSendNotificationAbout(eatTarget) && eatTarget.RaceProps.Humanlike) { Messages.Message("MessageEatenByPredator".Translate(new object[] { eatTarget.LabelShort, zombie.LabelIndefinite() }).CapitalizeFirst(), zombie, MessageSound.Negative); } eatTarget.Strip(); } return; } else { var corpse = map.thingGrid .ThingsListAt(eatTarget.Position) .OfType <Corpse>() .FirstOrDefault(c => c.InnerPawn == eatTarget); if (corpse != null) { corpse.Destroy(DestroyMode.Vanish); } Tools.DoWithAllZombies(map, z => { if (z.jobs != null) { var driver = z.jobs.curDriver as JobDriver_Stumble; if (driver != null && driver.eatTarget == eatTarget) { driver.eatTarget = null; driver.lastEatTarget = null; driver.eatDelayCounter = 0; } } }); } } else { var zombieLeaner = zombie.Drawer.leaner as ZombieLeaner; if (zombieLeaner != null) { zombieLeaner.extraOffset = Vector3.zero; } } var basePos = zombie.Position; // calculate possible moves, sort by pheromone value and take top 3 // then choose the one with the lowest zombie count // also, emit a circle of timestamps when discovering a pheromone // trace so nearby zombies pick it up too (leads to a chain reaction) // var grid = zombie.Map.GetGrid(); var possibleTrackingMoves = new List <IntVec3>(); var currentTicks = Tools.Ticks(); var timeDelta = long.MaxValue; for (int i = 0; i < 8; i++) { var pos = basePos + GenAdj.AdjacentCells[i]; if (currentTicks - grid.Get(pos, false).timestamp < fadeOff && zombie.HasValidDestination(pos)) { possibleTrackingMoves.Add(pos); } } if (possibleTrackingMoves.Count > 0) { possibleTrackingMoves.Sort((p1, p2) => SortByTimestamp(grid, p1, p2)); possibleTrackingMoves = possibleTrackingMoves.Take(Constants.NUMBER_OF_TOP_MOVEMENT_PICKS).ToList(); possibleTrackingMoves = possibleTrackingMoves.OrderBy(p => grid.Get(p, false).zombieCount).ToList(); var nextMove = possibleTrackingMoves.First(); timeDelta = currentTicks - grid.Get(nextMove, false).timestamp; destination = nextMove; if (zombie.state == ZombieState.Wandering) { Tools.ChainReact(zombie.Map, basePos, nextMove); if (timeDelta <= agitatedFadeoff) { CastBrainzThought(); } } zombie.state = ZombieState.Tracking; } if (destination.IsValid == false) { zombie.state = ZombieState.Wandering; } bool checkSmashable = timeDelta >= checkSmashableFadeoff; if (ZombieSettings.Values.smashOnlyWhenAgitated) { checkSmashable &= zombie.state == ZombieState.Tracking; } if (destination.IsValid == false || checkSmashable) { var building = CanSmash(); if (building != null) { destination = building.Position; if (Constants.USE_SOUND) { var info = SoundInfo.InMap(enemy); SoundDef.Named("ZombieHit").PlayOneShot(info); } AttackThing(building, JobDefOf.AttackStatic); return; } } if (destination.IsValid == false) { var hour = GenLocalDate.HourOfDay(Find.VisibleMap); // check for day/night and dust/dawn // var moveTowardsCenter = false; if (map.areaManager.Home[basePos] == false) { if (hour < 12) { hour += 24; } if (hour > Constants.HOUR_START_OF_NIGHT && hour < Constants.HOUR_END_OF_NIGHT) { moveTowardsCenter = true; } else if (hour >= Constants.HOUR_START_OF_DUSK && hour <= Constants.HOUR_START_OF_NIGHT) { moveTowardsCenter = Rand.RangeInclusive(hour, Constants.HOUR_START_OF_NIGHT) == Constants.HOUR_START_OF_NIGHT; } else if (hour >= Constants.HOUR_END_OF_NIGHT && hour <= Constants.HOUR_START_OF_DAWN) { moveTowardsCenter = Rand.RangeInclusive(Constants.HOUR_END_OF_NIGHT, hour) == Constants.HOUR_END_OF_NIGHT; } } var possibleMoves = new List <IntVec3>(); for (int i = 0; i < 8; i++) { var pos = basePos + GenAdj.AdjacentCells[i]; if (zombie.HasValidDestination(pos)) { possibleMoves.Add(pos); } } if (possibleMoves.Count > 0) { // during night, zombies drift towards the colonies center // if (moveTowardsCenter) { var center = zombie.wanderDestination.IsValid ? zombie.wanderDestination : map.Center; possibleMoves.Sort((p1, p2) => SortByDirection(center, p1, p2)); possibleMoves = possibleMoves.Take(Constants.NUMBER_OF_TOP_MOVEMENT_PICKS).ToList(); possibleMoves = possibleMoves.OrderBy(p => grid.Get(p, false).zombieCount).ToList(); destination = possibleMoves.First(); } else { // otherwise they sometimes stand or walk towards a random direction // if (Rand.Chance(Constants.STANDING_STILL_CHANCE)) { var n = possibleMoves.Count(); destination = possibleMoves[Constants.random.Next(n)]; } } } } // if we have a valid destination, go there // if (destination.IsValid) { MoveToCell(destination); } }
public override void Tick(int currentTick) { //Performance reporting tick if (EnablePerformanceTesting() && currentTick % GenDate.TicksPerDay == 0 && PerformanceSetup.performanceTotals.Keys.Count > 0) { Dictionary <string, float> averages = PerformanceSetup.performanceTotals.ToDictionary(x => x.Key, x => (float)x.Value / (float)PerformanceSetup.performanceCalls[x.Key]); int topAmt = Math.Min(10, averages.Count); List <KeyValuePair <string, float> > avgTicks = (from avg in averages orderby avg.Value descending select avg).Take(topAmt).ToList(); List <KeyValuePair <string, float> > topTicks = (from avg in averages orderby avg.Value * PerformanceSetup.performanceCalls[avg.Key] descending select avg).Take(topAmt).ToList(); StringBuilder avgString = new StringBuilder(); foreach (KeyValuePair <string, float> t in avgTicks) { avgString.AppendLine(t.Key + " (" + t.Value + ")"); } StringBuilder topString = new StringBuilder(); foreach (KeyValuePair <string, float> t in topTicks) { topString.AppendLine(t.Key + " (" + avgTicks.Find(x => x.Key == t.Key).Value + ")"); } Log.Message("Psychology :: Performance Report :: Top " + topAmt + " average tick consumers:\n" + avgString.ToString() + "\nTop " + topAmt + " weighted tick consumers: " + topString.ToString()); } //Constituent tick if (currentTick % GenDate.TicksPerHour * 2 == 0) { Map playerFactionMap = Find.WorldObjects.SettlementBases.Find(b => b.Faction.IsPlayer).Map; IEnumerable <Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetLord() == null && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake() select p); if (constituents.Count() > 0) { Pawn potentialConstituent = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2)); IEnumerable <Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile && m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake() && m.GetLord() == null select m); if (potentialConstituent != null && !potentialConstituent.Downed && !potentialConstituent.Drafted && potentialConstituent.health.summaryHealth.SummaryHealthPercent >= 1f && potentialConstituent.GetTimeAssignment() != TimeAssignmentDefOf.Work && activeMayors.Count() > 0) { Pawn mayor = activeMayors.RandomElement(); //There should only be one. IntVec3 gather = default(IntVec3); String found = null; if (mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable != null) { gather = mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable.parent.Position; found = "office"; } else if (mayor.ownership != null && mayor.ownership.OwnedBed != null) { gather = mayor.ownership.OwnedBed.Position; found = "bed"; } if (PsycheHelper.PsychologyEnabled(potentialConstituent) && Rand.Chance((1f - PsycheHelper.Comp(potentialConstituent).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (found != null || RCellFinder.TryFindPartySpot(mayor, out gather)) && (!mayor.Drafted && !mayor.Downed && mayor.health.summaryHealth.SummaryHealthPercent >= 1f && mayor.GetTimeAssignment() != TimeAssignmentDefOf.Work && (mayor.CurJob == null || mayor.CurJob.def != JobDefOf.TendPatient))) { List <Pawn> pawns = new List <Pawn>(); pawns.Add(mayor); pawns.Add(potentialConstituent); Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < (potentialConstituent.mindState.mentalBreaker.BreakThresholdMinor * 1.25f))), mayor.Map, pawns); mayor.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced); potentialConstituent.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced); if (found == "bed") { mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoOffice); } else if (found == null) { mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom); } } } } } //Election tick if (currentTick % (GenDate.TicksPerDay / 4f) == 0) { foreach (Settlement settlement in Find.WorldObjects.Settlements) { //Self-explanatory. if (!PsychologyBase.ActivateElections()) { continue; } //If the base isn't owned or named by the player, no election can be held. if (!settlement.Faction.IsPlayer || !settlement.namedByPlayer) { continue; } //If the base is not at least a year old, no election will be held. if ((Find.TickManager.TicksGame - settlement.creationGameTicks) / GenDate.TicksPerYear < 1) { continue; } //A base must have at least 7 people in it to hold an election. if (settlement.Map.mapPawns.FreeColonistsSpawnedCount < 7) { continue; } //If an election is already being held, don't start a new one. if (settlement.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || settlement.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null) { continue; } //Elections are held in Septober (because I guess some maps don't have fall?) and during the day. if (GenDate.Quadrum(Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(settlement.Tile).x) != Quadrum.Septober || (GenLocalDate.HourOfDay(settlement.Map) < 7 || GenLocalDate.HourOfDay(settlement.Map) > 20)) { continue; } //If an election has already been completed this year, don't start a new one. IEnumerable <Pawn> activeMayors = (from m in settlement.Map.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == settlement.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(settlement.Map.Tile) select m); if (activeMayors.Count() > 0) { continue; } //Try to space out the elections so they don't all proc at once. if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfQuadrum(settlement.Map.Tile)) > 1) { continue; } IncidentParms parms = new IncidentParms(); parms.target = settlement.Map; parms.faction = settlement.Faction; FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms); Find.Storyteller.TryFire(fi); } } }
public static int ZombiesForNewIncident(Map map) { var tickManager = map.GetComponent <TickManager>(); var info = tickManager.incidentInfo; var ticksNow = GenTicks.TicksAbs; ZRdebug.capableColonists = Tools.CapableColonists(map); ZRdebug.daysBeforeZombies = ZombieSettings.Values.daysBeforeZombiesCome; ZRdebug.totalColonistCount = map.mapPawns.FreeHumanlikesSpawnedOfFaction(Faction.OfPlayer).Count(); ZRdebug.minimumCapableColonists = (ZRdebug.totalColonistCount + 1) / 3; ZRdebug.daysPassed = GenDate.DaysPassedFloat; ZRdebug.spawnMode = ZombieSettings.Values.spawnWhenType.ToString(); ZRdebug.storytellerDifficulty = Find.Storyteller.difficulty.difficulty; ZRdebug.currentZombieCount = tickManager.AllZombies().Count(); ZRdebug.numberOfZombiesPerColonist = ZombieSettings.Values.baseNumberOfZombiesinEvent; ZRdebug.maxBaseLevelZombies = tickManager.GetMaxZombieCount(); ZRdebug.extendedCount = 0; ZRdebug.maxNumberOfZombies = ZombieSettings.Values.maximumNumberOfZombies; ZRdebug.maxAdditionalZombies = 0; ZRdebug.calculatedZombies = 0; ZRdebug.incidentSize = 0; ZRdebug.rampUpDays = GenMath.LerpDouble(1, 5, 40, 0, Math.Max(1, ZRdebug.storytellerDifficulty)); ZRdebug.scaleFactor = Tools.Boxed(GenMath.LerpDouble(ZRdebug.daysBeforeZombies, ZRdebug.daysBeforeZombies + ZRdebug.rampUpDays, 0.2f, 1f, ZRdebug.daysPassed), 0.2f, 1f); ZRdebug.dayStretchFactor = 0; ZRdebug.deltaDays = 0; ZRdebug.skipReason = ""; // zombie free days if (ZRdebug.daysPassed <= ZRdebug.daysBeforeZombies) { ZRdebug.skipReason = "waiting for zombies"; return(0); } // outside night period if (ZombieSettings.Values.spawnWhenType == SpawnWhenType.WhenDark) { var hour = GenLocalDate.HourOfDay(map); if (hour < 12) { hour += 24; } if (hour < Constants.HOUR_START_OF_NIGHT || hour > Constants.HOUR_END_OF_NIGHT) { ZRdebug.skipReason = "outside night period"; return(0); } } // too few capable colonists (only in difficulty lower than Intense) if (ZRdebug.storytellerDifficulty < DifficultyDefOf.Hard.difficulty) { if (ZRdebug.capableColonists <= ZRdebug.minimumCapableColonists) { ZRdebug.skipReason = "too few capable colonists"; return(0); } } // not yet time for next incident if (ticksNow < info.NextIncident) { ZRdebug.skipReason = "wait " + (info.NextIncident - ticksNow).ToStringTicksToPeriod(); return(0); } // too little new zombies if (Rand.Chance(1f / 24f) && Find.Storyteller.difficulty.allowBigThreats) { ZRdebug.extendedCount = ZRdebug.maxNumberOfZombies - ZRdebug.maxBaseLevelZombies; if (ZRdebug.extendedCount > 0) { ZRdebug.extendedCount = Rand.RangeInclusive(0, ZRdebug.extendedCount); ZRdebug.maxBaseLevelZombies += ZRdebug.extendedCount; } } ZRdebug.maxAdditionalZombies = Math.Max(0, ZRdebug.maxBaseLevelZombies - ZRdebug.currentZombieCount); ZRdebug.calculatedZombies = ZRdebug.capableColonists * ZRdebug.numberOfZombiesPerColonist; ZRdebug.incidentSize = Math.Min(ZRdebug.maxAdditionalZombies, ZRdebug.calculatedZombies); if (ZRdebug.incidentSize == 0) { ZRdebug.skipReason = "empty incident"; return(0); } // ramp it up ZRdebug.scaleFactor *= (0.75f + Rand.Value / 2f); ZRdebug.scaleFactor = Tools.Boxed(ZRdebug.scaleFactor, 0f, 1f); ZRdebug.incidentSize = Math.Max(1, (int)(ZRdebug.incidentSize * ZRdebug.scaleFactor + 0.5f)); // success ZRdebug.dayStretchFactor = 1f + ZRdebug.incidentSize / 150f; ZRdebug.deltaDays = Rand.Range(1.5f * ZRdebug.dayStretchFactor, 4f * ZRdebug.dayStretchFactor); info.Update(ZRdebug.deltaDays); ZRdebug.skipReason = "-"; return(ZRdebug.incidentSize); }
public override float GetPriority(Pawn pawn) { Need_Rest restNeed = pawn.needs.rest; if (restNeed == null) { return(0f); } TimeAssignmentDef timeAssignmentDef; if (pawn.RaceProps.Humanlike) { timeAssignmentDef = ((pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything); } else { int hourOfDay = GenLocalDate.HourOfDay(pawn); int napStart = Rand.RangeInclusive(10, 14); int napEnd = Rand.RangeInclusive(15, 18); if (hourOfDay < 6 || hourOfDay > 22 || hourOfDay > napStart && napEnd < 18) { timeAssignmentDef = TimeAssignmentDefOf.Sleep; } else { timeAssignmentDef = TimeAssignmentDefOf.Anything; } } float restLevel = restNeed.CurLevel; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { if (restLevel < 0.3f) { return(8f); } return(0f); } else { if (timeAssignmentDef == TimeAssignmentDefOf.Work) { return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { if (restLevel < 0.3f) { return(8f); } return(0f); } else { // should be only work, sleep and joy if (timeAssignmentDef != TimeAssignmentDefOf.Sleep) { throw new NotImplementedException(); } // neither work nor joy stuck, so we're in sleep (nap) mode. if (restLevel < 0.9f) { return(8f); } return(0f); } } }
internal static float _GetPriority(this JobGiver_GetRest j, Pawn pawn) { Need_Rest rest = pawn.needs.rest; if (rest == null) { return(0f); } if (rest.CurCategory < j.MinCategory()) { return(0f); } if (Find.TickManager.TicksGame < pawn.mindState.canSleepTick) { return(0f); } Lord lord = pawn.GetLord(); if (lord != null && !lord.CurLordToil.AllowSatisfyLongNeeds) { return(0f); } TimeAssignmentDef timeAssignmentDef; if (pawn.RaceProps.Humanlike) { timeAssignmentDef = ((pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything); } else { int num = GenLocalDate.HourOfDay(pawn); if (num < 7 || num > 21) { timeAssignmentDef = TimeAssignmentDefOf.Sleep; } else { timeAssignmentDef = TimeAssignmentDefOf.Anything; } } float curLevel = rest.CurLevel; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { if (pawn.RaceProps.Humanlike && pawn.story.traits.HasTrait(TraitDefOfPsychology.Insomniac)) { if (curLevel < 0.3f) { return(1f); } return(0f); } else { if (curLevel < 0.3f) { return(8f); } return(0f); } } else { if (timeAssignmentDef == TimeAssignmentDefOf.Work) { return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { if (pawn.RaceProps.Humanlike && pawn.story.traits.HasTrait(TraitDefOfPsychology.Insomniac)) { if (curLevel < 0.3f) { return(3f); } return(0f); } else { if (curLevel < 0.3f) { return(8f); } return(0f); } } else { if (timeAssignmentDef != TimeAssignmentDefOf.Sleep) { throw new NotImplementedException(); } if (pawn.RaceProps.Humanlike && pawn.story.traits.HasTrait(TraitDefOfPsychology.Insomniac)) { if (curLevel < 0.75f) { return(3f); } return(0f); } else { if (curLevel < 0.75f) { return(8f); } return(0f); } } } }
static bool Prefix(HungerCategory ___minCategory, float ___maxLevelPercentage, ref float __result, Pawn pawn) { //Log.Message("1"); Need_Food food = pawn.needs.food; if (food == null) { __result = 0f; return(false); } //Log.Message("2"); if (pawn.needs.food.CurCategory < HungerCategory.Starving && FoodUtility.ShouldBeFedBySomeone(pawn)) { __result = 0f; return(false); } //Log.Message("3"); if (food.CurCategory < ___minCategory) { __result = 0f; return(false); } //Log.Message("4"); if (food.CurLevelPercentage > ___maxLevelPercentage) { __result = 0f; return(false); } //Log.Message("5"); if (pawn.RaceProps.Humanlike) { if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat + ModSetting.eatThreshold) { if (pawn.timetable == null) { if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat) { __result = 9.5f; } else { __result = 0f; } return(false); } //Log.Message("6"); TimeAssignmentDef timeAssignmentDef = (pawn.timetable == null) ? TimeAssignmentDefOf.Anything : pawn.timetable.CurrentAssignment; if (timeAssignmentDef != TimeAssignmentDefDinner.DinnerDef) { //Log.Message("7"); if (pawn.timetable.GetAssignment((GenLocalDate.HourOfDay(pawn) + 1) % 24) == TimeAssignmentDefDinner.DinnerDef && food.CurLevelPercentage > pawn.RaceProps.FoodLevelPercentageWantEat * 0.48f) {//下一小时是dinner时间并且饥饿度百分比>0.45就不吃饭 __result = 0f; return(false); } if (pawn.timetable.GetAssignment((GenLocalDate.HourOfDay(pawn) + 2) % 24) == TimeAssignmentDefDinner.DinnerDef && food.CurLevelPercentage > pawn.RaceProps.FoodLevelPercentageWantEat * 0.8f) {//下2小时是dinner时间并且饥饿度百分比>0.8就不吃饭 __result = 0f; return(false); } //Log.Message("8"); if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat) { __result = 9.5f; } else { __result = 0f; } return(false); } if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat) { __result = 9.5f; } else { __result = 7.25f; } return(false); } else { __result = 0; } //Log.Message("{0} food priority = {1}".Translate(pawn.Label, __result)); } else if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat) { __result = 9.5f; } else { __result = 0f; } return(false); }
public ChestbursterPawn() { SpawnXenoAtTick = Find.TickManager.TicksGame + overrideXenoSpawnDelay ?? GameTime.RandomTickNextNight(Find.TickManager.TicksGame, GenLocalDate.HourOfDay(this)); Log.Message("Will spawn xeno at " + SpawnXenoAtTick + " (now its " + Find.TickManager.TicksGame + ")"); XenoLifecycle.Instance().Register(this); }
public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { PawnRelationDef pawnRelation = RelationshipUtility.MostAdvancedRelationshipBetween(initiator, recipient); if (!AttractionUtility.QuickCheck(initiator, recipient)) { return(0f); } if (GradualRomanceMod.SeductionMode == GradualRomanceMod.SeductionModeSetting.NoSeduction) { return(0f); } else if (GradualRomanceMod.SeductionMode == GradualRomanceMod.SeductionModeSetting.OnlyRelationship) { if (pawnRelation == null || !RelationshipUtility.IsSexualRelationship(pawnRelation)) { return(0f); } } else if (GradualRomanceMod.SeductionMode == GradualRomanceMod.SeductionModeSetting.RelationshipAndNonColonists) { if (pawnRelation == null && recipient.IsColonist) { return(0f); } if (pawnRelation != null && !RelationshipUtility.IsSexualRelationship(pawnRelation) && recipient.IsColonist) { return(0f); } } //shouldn't seduce if you can't move if (initiator.health.capacities.GetLevel(PawnCapacityDefOf.Consciousness) <= 0.5f || initiator.health.capacities.GetLevel(PawnCapacityDefOf.Moving) <= 0.25f) { return(0f); } if (recipient.health.capacities.GetLevel(PawnCapacityDefOf.Consciousness) <= 0.5f || recipient.health.capacities.GetLevel(PawnCapacityDefOf.Moving) <= 0.25f) { return(0f); } //shouldn't seduce while working TimeAssignmentDef initiatorAssignment = initiator.timetable.GetAssignment(GenLocalDate.HourOfDay(initiator.Map)); TimeAssignmentDef recipientAssignment = recipient.timetable.GetAssignment(GenLocalDate.HourOfDay(recipient.Map)); if (initiatorAssignment != TimeAssignmentDefOf.Joy || initiatorAssignment != TimeAssignmentDefOf.Anything) { return(0f); } if (recipientAssignment != TimeAssignmentDefOf.Joy || recipientAssignment != TimeAssignmentDefOf.Anything) { return(0f); } EmptyReasons(); AttractionFactorDef whoCares; initiatorAttraction = AttractionUtility.CalculateAttraction(initiator, recipient, false, false, out veryLowInitiatorReasons, out lowInitiatorReasons, out highInitiatorReasons, out veryHighInitiatorReasons, out whoCares); float tensionFactor = 1.33f * RelationshipUtility.LevelOfSexualTension(initiator, recipient); tensionFactor = Mathf.Max(1f, tensionFactor); lastInitiator = initiator; lastRecipient = recipient; return(GradualRomanceMod.BaseSeductionChance * initiatorAttraction * tensionFactor * AttractionUtility.PropensityToSeduce(initiator)); }
private static bool Prefix(HungerCategory ___minCategory, float ___maxLevelPercentage, ref float __result, Pawn pawn) { var food = pawn.needs.food; if (food == null) { __result = 0f; return(false); } if (pawn.needs.food.CurCategory < HungerCategory.Starving && FoodUtility.ShouldBeFedBySomeone(pawn)) { __result = 0f; return(false); } if (food.CurCategory < ___minCategory) { __result = 0f; return(false); } if (food.CurLevelPercentage > ___maxLevelPercentage) { __result = 0f; return(false); } if (pawn.RaceProps.Humanlike) { if (food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat + ModSetting.eatThreshold) { if (pawn.timetable == null) { __result = food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat ? 9.5f : 0f; return(false); } var timeAssignmentDef = pawn.timetable == null ? TimeAssignmentDefOf.Anything : pawn.timetable.CurrentAssignment; if (timeAssignmentDef == TimeAssignmentDefDinner.DinnerDef) { __result = food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat ? 9.5f : 7.25f; return(false); } if (pawn.timetable.GetAssignment((GenLocalDate.HourOfDay(pawn) + 1) % 24) == TimeAssignmentDefDinner.DinnerDef && food.CurLevelPercentage > pawn.RaceProps.FoodLevelPercentageWantEat * 0.48f) { __result = 0f; return(false); } if (pawn.timetable.GetAssignment((GenLocalDate.HourOfDay(pawn) + 2) % 24) == TimeAssignmentDefDinner.DinnerDef && food.CurLevelPercentage > pawn.RaceProps.FoodLevelPercentageWantEat * 0.8f) { __result = 0f; return(false); } __result = food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat ? 9.5f : 0f; return(false); } __result = 0f; } else { __result = food.CurLevelPercentage < pawn.RaceProps.FoodLevelPercentageWantEat ? 9.5f : 0f; } return(false); }
// Token: 0x0600002B RID: 43 RVA: 0x00002EAC File Offset: 0x000010AC public bool IsGoodAndSafeTimeForPerformance() { return(GenLocalDate.HourOfDay(Map) >= 13 && GenLocalDate.HourOfDay(Map) <= 21 && Map.dangerWatcher.DangerRating == StoryDanger.None && Map.mapPawns.FreeColonistsSpawnedCount >= 4); }
public override void MapComponentTick() { if (this.map.Biome != Util_CaveBiome.CaveBiomeDef) { return; } if (Find.TickManager.TicksGame >= nextLigthCheckTick) { nextLigthCheckTick = Find.TickManager.TicksGame + lightCheckPeriodInTicks; int hour = GenLocalDate.HourOfDay(map); if ((hour >= sunriseBeginHour) && (hour < sunriseEndHour)) { // Sunrise. int currentDayTick = Find.TickManager.TicksAbs % GenDate.TicksPerDay; int ticksSinceSunriseBegin = currentDayTick - sunriseBeginHourInTicks; float sunriseProgress = (float)ticksSinceSunriseBegin / (float)sunriseDurationInTicks; float caveWellLigthRadius = Mathf.Lerp(lightRadiusCaveWellMin, lightRadiusCaveWellMax, sunriseProgress); List <Thing> caveWellsList = map.listerThings.ThingsOfDef(Util_CaveBiome.CaveWellDef); foreach (Thing caveWell in caveWellsList) { SetGlowRadius(caveWell, caveWellLigthRadius); } } else if ((hour >= sunsetBeginHour) && (hour < sunsetEndHour)) { // Sunset. int currentDayTick = Find.TickManager.TicksAbs % GenDate.TicksPerDay; int ticksSinceSunsetBegin = currentDayTick - sunsetBeginHourInTicks; float sunsetProgress = 1f - ((float)ticksSinceSunsetBegin / (float)sunriseDurationInTicks); float caveWellLigthRadius = Mathf.Lerp(lightRadiusCaveWellMin, lightRadiusCaveWellMax, sunsetProgress); List <Thing> caveWellsList = map.listerThings.ThingsOfDef(Util_CaveBiome.CaveWellDef); foreach (Thing caveWell in caveWellsList) { SetGlowRadius(caveWell, caveWellLigthRadius); } } if ((MapComponent_CaveWellLight.plantsMessageHasBeenSent == false) && (hour >= sunriseBeginHour + 1)) { Find.LetterStack.ReceiveLetter("Cave plants", "In caves, most cave plants can be useful so look around!\n- some plants like giant leafs can be cooked,\n- others like cave vine are hard enough to be used like wood,\n- and some like devil's tongue provide useful fibrous material.\n\nBeware, though! Caves are a hard place to live and some plants may be dangerous.", LetterType.Good); MapComponent_CaveWellLight.plantsMessageHasBeenSent = true; } if ((MapComponent_CaveWellLight.growingMessageHasBeenSent == false) && (hour >= sunriseBeginHour + 2)) { if (MapGenerator.PlayerStartSpot.IsValid && (MapGenerator.PlayerStartSpot != IntVec3.Zero)) // Checking PlayerStartSpot validity will still raise an error message if it is invalid. { Find.LetterStack.ReceiveLetter("Growing in cave", "The sun cannot directly light the cave tunnels. You can however grow some plants in cave wells. Cave wells are natural openings to the surface.", LetterType.Good, new RimWorld.Planet.GlobalTargetInfo(MapGenerator.PlayerStartSpot, this.map)); } else { Find.LetterStack.ReceiveLetter("Growing in cave", "The sun cannot directly light the cave tunnels. You can however grow some plants in cave wells. Cave wells are natural openings to the surface.", LetterType.Good); } MapComponent_CaveWellLight.growingMessageHasBeenSent = true; } } }
public bool CurrentAssignment(Map map) => times[GenLocalDate.HourOfDay(map)];
public override float GetPriority(Pawn pawn) { Need_Rest rest = pawn.needs.rest; if (rest == null) { return(0f); } if (rest.CurCategory < minCategory) { return(0f); } if (Find.TickManager.TicksGame < pawn.mindState.canSleepTick) { return(0f); } Lord lord = pawn.GetLord(); if (lord != null && !lord.CurLordToil.AllowSatisfyLongNeeds) { return(0f); } TimeAssignmentDef timeAssignmentDef; if (pawn.RaceProps.Humanlike) { timeAssignmentDef = ((pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything); } else { int num = GenLocalDate.HourOfDay(pawn); if (num < 7 || num > 21) { timeAssignmentDef = TimeAssignmentDefOf.Sleep; } else { timeAssignmentDef = TimeAssignmentDefOf.Anything; } } float curLevel = rest.CurLevel; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { if (curLevel < 0.3f) { return(8f); } return(0f); } else { if (timeAssignmentDef == TimeAssignmentDefOf.Work) { return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { if (curLevel < 0.3f) { return(8f); } return(0f); } else { if (timeAssignmentDef != TimeAssignmentDefOf.Sleep) { throw new NotImplementedException(); } if (curLevel < RestUtility.FallAsleepMaxLevel(pawn)) { return(8f); } return(0f); } } }
private void DoTimeBar(Rect rect) { // set up rects Rect bar = TimeBarRect; Rect buttons = new Rect(rect.xMin, bar.yMin + bar.height / 3f, bar.xMin - rect.xMin, bar.height * 2 / 3f); Rect button = new Rect(buttons.xMax - buttons.height * 2f, buttons.yMin, buttons.height, buttons.height); // split the available area into rects. bottom 2/3's are used for 'buttons', with text for times. float hourWidth = bar.width / GenDate.HoursPerDay; float barheight = bar.height * 2 / 3f; float timeIndicatorSize = bar.height * 2 / 3f; float lastLabelPosition = 0f; Rect hourRect = new Rect(bar.xMin, bar.yMax - barheight, hourWidth, barheight); // draw buttons TooltipHandler.TipRegion(button, "WorkTab.SelectWholeDayTip".Translate()); if (Widgets.ButtonImage(button, PrioritiesWholeDay, Color.white, GenUI.MouseoverColor)) { SelectWholeDay(); } button.x -= button.height + Constants.Margin; TooltipHandler.TipRegion(button, "WorkTab.SelectCurrentHourTip".Translate()); if (Widgets.ButtonImage(button, Now, Color.white, GenUI.MouseoverColor)) { AddSelectedHour(GenLocalDate.HourOfDay(Find.VisibleMap), true); } // draw first tick GUI.color = Color.grey; Widgets.DrawLineVertical(hourRect.xMin, hourRect.yMin + hourRect.height * 1 / 2f, hourRect.height * 1 / 2f); // draw horizontal line ( y - 1 because canvas gets clipped on bottom ) Widgets.DrawLineHorizontal(bar.xMin, bar.yMax - 1, bar.width); GUI.color = Color.white; // label and rect string label; Rect labelRect; for (int hour = 0; hour < GenDate.HoursPerDay; hour++) { bool selected = SelectedHours.Contains(hour); bool focused = hour == VisibleHour; // print major tick GUI.color = Color.grey; Widgets.DrawLineVertical(hourRect.xMax, hourRect.yMin + hourRect.height * 1 / 2f, hourRect.height * 1 / 2f); // print minor ticks Widgets.DrawLineVertical(hourRect.xMin + hourRect.width * 1 / 4f, hourRect.yMin + hourRect.height * 3 / 4f, hourRect.height * 1 / 4f); Widgets.DrawLineVertical(hourRect.xMin + hourRect.width * 2 / 4f, hourRect.yMin + hourRect.height * 3 / 4f, hourRect.height * 1 / 4f); Widgets.DrawLineVertical(hourRect.xMin + hourRect.width * 3 / 4f, hourRect.yMin + hourRect.height * 3 / 4f, hourRect.height * 1 / 4f); GUI.color = Color.white; // create and draw labelrect - but only if the last label isn't too close if (hourRect.xMin - lastLabelPosition > MinTimeBarLabelSpacing) { label = hour.FormatHour(); labelRect = new Rect(0f, bar.yMin + bar.height * 1 / 3f, label.NoWrapWidth(), bar.height * 2 / 3f); labelRect.x = hourRect.xMin - labelRect.width / 2f; UIUtilities.Label(labelRect, label, Color.grey, GameFont.Tiny, TextAnchor.UpperCenter); lastLabelPosition = labelRect.xMax; } // draw hour rect with mouseover + interactions Widgets.DrawHighlightIfMouseover(hourRect); // set/remove focus (LMB and any other MB respectively) if (Mouse.IsOver(hourRect)) { if (Input.GetMouseButton(0)) { AddSelectedHour(hour, Event.current.shift); } if (Input.GetMouseButton(1)) { RemoveSelectedHour(hour); } // handle tooltip var selectedString = selected ? "WorkTab.Selected".Translate() : "WorkTab.NotSelected".Translate(); var interactionString = ""; if (selected) { interactionString += "WorkTab.RightClickToDeselect".Translate(); if (focused) { interactionString += "\n" + "WorkTab.ClickToFocus".Translate(); } } else { interactionString += "WorkTab.ClickToSelect".Translate(); } TooltipHandler.TipRegion(hourRect, "WorkTab.SchedulerHourTip".Translate(hour.FormatHour(), (hour + 1 % GenDate.HoursPerDay).FormatHour(), selectedString, interactionString)); } // if this is currently the 'main' timeslot, and not the actual time, draw an eye if (focused && hour != GenLocalDate.HourOfDay(Find.VisibleMap)) { Rect eyeRect = new Rect(hourRect.center.x - timeIndicatorSize * 1 / 2f, hourRect.yMax - timeIndicatorSize - hourRect.height * 1 / 6f, timeIndicatorSize, timeIndicatorSize); GUI.DrawTexture(eyeRect, PinEye); } // also highlight all selected timeslots if (selected) { Widgets.DrawHighlightSelected(hourRect); } // advance rect hourRect.x += hourRect.width; } // draw final label label = 0.FormatHour(); labelRect = new Rect(0f, bar.yMin + bar.height * 1 / 3f, label.NoWrapWidth(), bar.height * 2 / 3f); labelRect.x = hourRect.xMin - labelRect.width / 2f; UIUtilities.Label(labelRect, label, Color.grey, GameFont.Tiny, TextAnchor.UpperCenter); // draw current time indicator float curTimeX = GenLocalDate.DayPercent(Find.VisibleMap) * bar.width; Rect curTimeRect = new Rect(bar.xMin + curTimeX - timeIndicatorSize * 1 / 2f, hourRect.yMax - timeIndicatorSize - hourRect.height * 1 / 6f, timeIndicatorSize, timeIndicatorSize); GUI.DrawTexture(curTimeRect, PinClock); }
public static IEnumerable <int> getTimeSpan(this Pawn me, string command) { if (command.Contains(Times.now.ToString())) { yield return(GenLocalDate.HourOfDay(me)); } if (command.Contains(Times.dawn.ToString())) { yield return(5); yield return(6); yield return(7); yield return(8); } if (command.Contains(Times.morning.ToString())) { yield return(18); yield return(19); yield return(20); yield return(21); } if (command.Contains(Times.noon.ToString())) { yield return(11); yield return(12); yield return(13); } if (command.Contains(Times.evening.ToString())) { yield return(18); yield return(19); yield return(20); yield return(21); } if (command.Contains(Times.midnight.ToString())) { yield return(23); yield return(0); yield return(1); yield return(2); } if (command.Contains(Times.day.ToString())) { for (int i = 1; i < 16; i++) { yield return((i + 8) % 24); } } if (command.Contains(Times.night.ToString())) { for (int i = 1; i < 16; i++) { yield return((i + 16) % 24); } } if (command.Contains(Times.always.ToString())) { for (int i = 0; i < 24; i++) { yield return(i); } } }
public override float GetPriority(Pawn pawn) { Need_Rest rest = pawn.needs.rest; if (rest == null) { return(0f); } if ((int)rest.CurCategory < (int)minCategory) { return(0f); } if (rest.CurLevelPercentage > maxLevelPercentage) { return(0f); } if (Find.TickManager.TicksGame < pawn.mindState.canSleepTick) { return(0f); } Lord lord = pawn.GetLord(); if (lord != null && !lord.CurLordToil.AllowSatisfyLongNeeds) { return(0f); } int num = GenLocalDate.HourOfDay(pawn); TimeAssignmentDef timeAssignmentDef = ((num < 6 || num > 21) ? TimeAssignmentDefOf.Anything : TimeAssignmentDefOf.Sleep); float curLevel = rest.CurLevel; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { if (curLevel < 0.3f) { return(8f); } return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Work) { return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Meditate) { if (curLevel < 0.16f) { return(8f); } return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { if (curLevel < 0.3f) { return(8f); } return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) { if (curLevel < RestUtility.FallAsleepMaxLevel(pawn)) { return(8f); } return(0f); } throw new NotImplementedException(); }
public override float GetPriority(Pawn pawn) { Hediff chiHD = pawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_ChiHD); CompAbilityUserMight comp = pawn.GetComp <CompAbilityUserMight>(); if (chiHD == null) { return(0f); } if (comp == null) { return(0f); } if ((int)chiHD.Severity > 80) { return(0f); } if (Find.TickManager.TicksGame < comp.allowMeditateTick) { return(0f); } TimeAssignmentDef timeAssignmentDef; if (pawn.RaceProps.Humanlike) { timeAssignmentDef = (pawn.timetable != null) ? pawn.timetable.CurrentAssignment : TimeAssignmentDefOf.Anything; } else { int num = GenLocalDate.HourOfDay(pawn); timeAssignmentDef = (num >= 7 && num <= 21) ? TimeAssignmentDefOf.Anything : TimeAssignmentDefOf.Sleep; } float curLevel = chiHD.Severity; if (timeAssignmentDef == TimeAssignmentDefOf.Anything) { if (curLevel < 30.0f) { return(8f); } else if (curLevel < 70.0f) { return(4f); } return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Work) { return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Joy) { if (curLevel < 70f) { return(8f); } return(0f); } if (timeAssignmentDef == TimeAssignmentDefOf.Sleep) { if (curLevel < 50 && verVal >= 3) { return(8f); } else if (curLevel < 70 && verVal >= 2) { return(6f); } return(0f); } throw new NotImplementedException(); }
public static bool ZombiesForNewIncident(TickManager tickManager) { var info = tickManager.incidentInfo; if (info == null) { return(false); } if (tickManager.incidentInfo == null) { tickManager.incidentInfo = new IncidentInfo(); } if (tickManager.incidentInfo.parameters == null) { tickManager.incidentInfo.parameters = new IncidentParameters(); } var parameters = tickManager.incidentInfo.parameters; parameters.capableColonists = Tools.CapableColonists(tickManager.map); parameters.daysBeforeZombies = ZombieSettings.Values.daysBeforeZombiesCome; parameters.totalColonistCount = tickManager.map.mapPawns.FreeHumanlikesSpawnedOfFaction(Faction.OfPlayer).Count(); parameters.minimumCapableColonists = (parameters.totalColonistCount + 1) / 3; parameters.daysPassed = GenDate.DaysPassedFloat; parameters.spawnMode = ZombieSettings.Values.spawnWhenType.ToString(); parameters.storytellerDifficulty = Tools.StoryTellerDifficulty; parameters.currentZombieCount = tickManager.AllZombies().Count(); parameters.numberOfZombiesPerColonist = ZombieSettings.Values.baseNumberOfZombiesinEvent; parameters.colonyMultiplier = ZombieSettings.Values.colonyMultiplier; parameters.maxBaseLevelZombies = tickManager.GetMaxZombieCount() + ZombieGenerator.ZombiesSpawning; parameters.extendedCount = 0; parameters.maxNumberOfZombies = ZombieSettings.Values.maximumNumberOfZombies; parameters.maxAdditionalZombies = 0; parameters.calculatedZombies = 0; parameters.incidentSize = 0; parameters.rampUpDays = GenMath.LerpDouble(1, 5, 40, 0, Math.Max(1, Tools.StoryTellerDifficulty)); //parameters.scaleFactor = Tools.Boxed(GenMath.LerpDouble(parameters.daysBeforeZombies, parameters.daysBeforeZombies + parameters.rampUpDays, 0.2f, 1f, GenDate.DaysPassedFloat), 0.2f, 1f); //parameters.daysStretched = 0; parameters.deltaDays = 0; parameters.skipReason = "-"; // zombie free days if (parameters.daysPassed <= parameters.daysBeforeZombies) { parameters.skipReason = "waiting for zombies"; return(false); } // outside night period if (ZombieSettings.Values.spawnWhenType == SpawnWhenType.WhenDark) { var hour = GenLocalDate.HourOfDay(tickManager.map); if (hour < 12) { hour += 24; } if (hour < Constants.HOUR_START_OF_NIGHT || hour > Constants.HOUR_END_OF_NIGHT) { parameters.skipReason = "outside night period"; return(false); } } // too few capable colonists (only in difficulty lower than Intense) if (parameters.storytellerDifficulty < DifficultyDefOf.Rough.difficulty) { if (parameters.capableColonists < parameters.minimumCapableColonists) { parameters.skipReason = "too few capable colonists"; return(false); } } if (parameters.daysStretched == 0) { var stretchFactor = 1f + parameters.incidentSize / 150f; parameters.daysStretched = Rand.Range(1.5f * stretchFactor, 4f * stretchFactor); } parameters.deltaDays = parameters.daysStretched + ZombieSettings.Values.extraDaysBetweenEvents; // not yet time for next incident var ticksNow = GenTicks.TicksAbs; var ticksNextIncident = tickManager.incidentInfo.NextIncident(); if (ticksNow < ticksNextIncident) { parameters.skipReason = "wait " + (ticksNextIncident - ticksNow).ToStringTicksToPeriod(); return(false); } // too little new zombies if (Rand.Chance(1f / 24f) && Find.Storyteller.difficulty.allowBigThreats) { parameters.extendedCount = parameters.maxNumberOfZombies - parameters.maxBaseLevelZombies; if (parameters.extendedCount > 0) { parameters.extendedCount = Rand.RangeInclusive(0, parameters.extendedCount); parameters.maxBaseLevelZombies += parameters.extendedCount; } } parameters.maxAdditionalZombies = Math.Max(0, parameters.maxBaseLevelZombies - parameters.currentZombieCount); parameters.calculatedZombies = (int)(parameters.capableColonists * parameters.numberOfZombiesPerColonist * parameters.colonyMultiplier); parameters.incidentSize = Math.Min(parameters.maxAdditionalZombies, parameters.calculatedZombies); if (parameters.incidentSize == 0) { parameters.skipReason = "empty incident"; return(false); } // ramp it up if (parameters.scaleFactor == 0) { parameters.scaleFactor = Tools.Boxed(GenMath.LerpDouble(parameters.daysBeforeZombies, parameters.daysBeforeZombies + parameters.rampUpDays, 0.2f, 1f, GenDate.DaysPassedFloat), 0.2f, 1f); } parameters.scaleFactor *= (0.75f + Rand.Value / 2f); parameters.scaleFactor = Tools.Boxed(parameters.scaleFactor, 0f, 1f); parameters.incidentSize = Math.Max(1, (int)(parameters.incidentSize * parameters.scaleFactor + 0.5f)); // success var stretchFactor2 = 1f + parameters.incidentSize / 150f; parameters.daysStretched = Rand.Range(1.5f * stretchFactor2, 4f * stretchFactor2); parameters.deltaDays = parameters.daysStretched + ZombieSettings.Values.extraDaysBetweenEvents; tickManager.incidentInfo.Update(); return(true); }