public GameObject Branch(params object[] args) { int amount = 10; Transform container = root.transform; Trait t = new Trait(); t.Apply (trait); // container.GetComponent<Joint> ().trait = t; // container.name = "ROOT"; int[] dictName = new int[1]; for (int i = 0; i < args.Length; i++) { if(args[i].GetType() == typeof(int)) amount = (int)args[i]; if(args[i].GetType() == typeof(Trait)) t = (Trait)args[i]; if (args [i].GetType () == typeof(Transform)) { container = (Transform)args [i]; // Debug.Log ("groot"); } if(args[i].GetType() == typeof(int[])) dictName = (int[])args[i]; } t.joints = amount; // GameObject j = TREEUtils.JointFactory(t); // j.transform.parent = container.transform; return RecursiveAdd (amount, 0, container, t, dictName); }
public void AssignTrait(Trait newTrait) { assignedTrait=newTrait; nameText.text=newTrait.name; GetComponent<Button>().onClick.RemoveAllListeners(); if (assignedTrait.GetType().BaseType==typeof(Trait)) GetComponent<Button>().image.color=Color.white; else { Skill assignedSkill=assignedTrait as Skill; if (assignedSkill.learned) GetComponent<Button>().image.color=Color.white; else { if (InventoryScreenHandler.mainISHandler.selectedMember.skillpoints<1) GetComponent<Button>().image.color=Color.gray; else { GetComponent<Button>().image.color=Color.green; GetComponent<Button>().onClick.AddListener( ()=> { //if (InventoryScreenHandler.mainISHandler.selectedMember.skillpoints>=1) { //Order is important InventoryScreenHandler.mainISHandler.selectedMember.ActivateSkill(assignedSkill); InventoryScreenHandler.mainISHandler.selectedMember.skillpoints--; InventoryScreenHandler.mainISHandler.RefreshInventoryItems(); } }); } } } }
public void AddOrRemoveTrait(Trait trait) { if (others.Contains (trait)) { others.Remove(trait); } else others.Add (trait); }
public Armor(string name, string type, int value, string armortype) { this.name = name; this.type = type; this.value = value; this.armortype = armortype; this.trait = new Trait(); }
public Armor(Armor armor) { this.name = armor.name; this.type = armor.type; this.value = armor.value; this.armortype = armor.armortype; this.trait = armor.trait; }
public Armor(string name, string type, int value, string armortype, Trait trait) { this.name = name; this.type = type; this.value = value; this.armortype = armortype; this.trait = trait; }
public void AddTrait(Trait trait) { if (!HasTrait(trait)) { TraitLeveler tl = new TraitLeveler(); tl.trait = trait; traits.Add(tl); } }
private void RecuAddNodeFromXML(XmlNode node, HModelNode parent, bool multiplayer) { Debug.Log (node["ID"].InnerText); Trait t = new Trait(Convert.ToUInt32(node["ID"].InnerText), node["NAME"].InnerText, Convert.ToDouble(node["LEARNINGRATE"].InnerText), multiplayer); HModelNode tmp = new HModelNode(t, parent); foreach (XmlNode subTrait in node.SelectNodes("/CHILDREN/*")) { RecuAddNodeFromXML(subTrait, tmp, multiplayer); } }
public static Trait FromTraitList (ListOfTraits NameOfTrait){ Trait trait = new Trait(); switch (NameOfTrait){ case ListOfTraits.Coward: trait = new Trait(){ }; break; } return trait; }
public void generate(params string[] gene) { genome = GenomeUtils.fixGenome (gene); Genome g = GenomeUtils.getGenome (new Genome (), genome); Trait t = new Trait(); t.Apply (trait); GameObject tempRoot = makeJoint (t);// TREEUtils.JointFactory(t); tempRoot.transform.parent = transform; for (int i = 0; i < g.rads[0]; i++) { // Trait t = new Trait (); // t.Apply (trait); t.jointScale = g.length [0]; GameObject thisRoot = Branch ((int)g.joints [0]-1,tempRoot.transform, t); thisRoot.transform.Rotate( new Vector3 (0, i * 360 / g.rads [0], g.angles [0])); tempRoot.GetComponent<Joint> ().limbs.Add (thisRoot); if(g.joints.Length>1) recursiveBranch (g, 1, thisRoot); } }
static void SetPrimaryTrait(HumanFF worker, Trait traitType) { int level = UnityEngine.Random.Range(70, 90); SetTrait(worker, traitType); }
public ExposedTraitEntry(Trait trait) { def = trait.def; degree = trait.Degree; }
public virtual void Inherit(Trait trait1, Trait trait2) { }
public void ModifyTrait(Trait t) { }
public DataType AddTrait(TypeVariable t, Trait tr) { GetTypeTraits(t).Add(tr); return(null); }
public GameObject makeJoint(Trait t) { if (!defaultJointExists) return TREEUtils.JointFactory (t); else { GameObject G = Instantiate (defaultJoint); G.name = "joint_" + t.id; // G.AddComponent<Joint> (); Joint J = G.GetComponent<Joint> (); J.setTrait (t); J.setScale (t.jointScale); J.joint = t.id; return G; } }
public static TraitDegreeData GetDegreeDate(Trait Trait) { var degreedata = Trait.def.degreeDatas?.Where(x => x.degree == Trait.Degree).SingleOrDefault(); return(degreedata); }
public TailLossAction(TailLoss trait, Trait tailTrait, Carnivorous carnivorous) : base(trait) { this.TailTrait = tailTrait; this.Carnivorous = carnivorous; }
public Armor() { value = 5; type = "none"; trait = new Trait(); }
protected override void DrawPanelContent(State state) { CustomPawn currentPawn = state.CurrentPawn; tipCache.CheckPawn(currentPawn); if (currentPawn.TraitCount > Constraints.MaxVanillaTraits) { Warning = "EdB.PC.Panel.Traits.Warning.TooManyTraits".Translate(); } else { Warning = null; } base.DrawPanelContent(state); Action clickAction = null; float cursor = 0; GUI.color = Color.white; GUI.BeginGroup(RectScrollFrame); try { if (currentPawn.Traits.Count() == 0) { GUI.color = Style.ColorText; Widgets.Label(RectScrollView.InsetBy(6, 0, 0, 0), "EdB.PC.Panel.Traits.None".Translate()); } GUI.color = Color.white; scrollView.Begin(RectScrollView); int index = 0; foreach (Trait trait in currentPawn.Traits) { if (index >= fields.Count) { fields.Add(new Field()); } Field field = fields[index]; GUI.color = Style.ColorPanelBackgroundItem; Rect traitRect = new Rect(0, cursor, SizeTrait.x - (scrollView.ScrollbarsVisible ? 16 : 0), SizeTrait.y); GUI.DrawTexture(traitRect, BaseContent.WhiteTex); GUI.color = Color.white; Rect fieldRect = new Rect(SizeFieldPadding.x, cursor + SizeFieldPadding.y, SizeField.x, SizeField.y); if (scrollView.ScrollbarsVisible) { fieldRect.width = fieldRect.width - 16; } field.Rect = fieldRect; Rect fieldClickRect = fieldRect; fieldClickRect.width = fieldClickRect.width - 36; field.ClickRect = fieldClickRect; if (trait != null) { field.Label = trait.LabelCap; field.Tip = GetTraitTip(trait, currentPawn); } else { field.Label = null; field.Tip = null; } Trait localTrait = trait; int localIndex = index; field.ClickAction = () => { Trait originalTrait = localTrait; Trait selectedTrait = originalTrait; ComputeDisallowedTraits(currentPawn, originalTrait); Dialog_Options <Trait> dialog = new Dialog_Options <Trait>(providerTraits.Traits) { NameFunc = (Trait t) => { return(t.LabelCap); }, DescriptionFunc = (Trait t) => { return(GetTraitTip(t, currentPawn)); }, SelectedFunc = (Trait t) => { if ((selectedTrait == null || t == null) && selectedTrait != t) { return(false); } return(selectedTrait.def == t.def && selectedTrait.Label == t.Label); }, SelectAction = (Trait t) => { selectedTrait = t; }, EnabledFunc = (Trait t) => { return(!disallowedTraitDefs.Contains(t.def)); }, CloseAction = () => { TraitUpdated(localIndex, selectedTrait); }, NoneSelectedFunc = () => { return(selectedTrait == null); }, SelectNoneAction = () => { selectedTrait = null; } }; Find.WindowStack.Add(dialog); }; field.PreviousAction = () => { var capturedIndex = index; clickAction = () => { SelectPreviousTrait(currentPawn, capturedIndex); }; }; field.NextAction = () => { var capturedIndex = index; clickAction = () => { SelectNextTrait(currentPawn, capturedIndex); }; }; field.Draw(); // Remove trait button. Rect deleteRect = new Rect(field.Rect.xMax - 32, field.Rect.y + field.Rect.HalfHeight() - 6, 12, 12); if (deleteRect.Contains(Event.current.mousePosition)) { GUI.color = Style.ColorButtonHighlight; } else { GUI.color = Style.ColorButton; } GUI.DrawTexture(deleteRect, Textures.TextureButtonDelete); if (Widgets.ButtonInvisible(deleteRect, false)) { SoundDefOf.Tick_Tiny.PlayOneShotOnCamera(); traitsToRemove.Add(trait); } index++; cursor += SizeTrait.y + SizeTraitMargin.y; } cursor -= SizeTraitMargin.y; } finally { scrollView.End(cursor); GUI.EndGroup(); } tipCache.MakeReady(); GUI.color = Color.white; if (clickAction != null) { clickAction(); clickAction = null; } // Randomize traits button. Rect randomizeRect = new Rect(PanelRect.width - 32, 9, 22, 22); if (randomizeRect.Contains(Event.current.mousePosition)) { GUI.color = Style.ColorButtonHighlight; } else { GUI.color = Style.ColorButton; } GUI.DrawTexture(randomizeRect, Textures.TextureButtonRandom); if (Widgets.ButtonInvisible(randomizeRect, false)) { SoundDefOf.Tick_Low.PlayOneShotOnCamera(); tipCache.Invalidate(); TraitsRandomized(); } // Add trait button. Rect addRect = new Rect(randomizeRect.x - 24, 12, 16, 16); Style.SetGUIColorForButton(addRect); int traitCount = state.CurrentPawn.Traits.Count(); bool addButtonEnabled = (state.CurrentPawn != null && traitCount < Constraints.MaxTraits); if (!addButtonEnabled) { GUI.color = Style.ColorButtonDisabled; } GUI.DrawTexture(addRect, Textures.TextureButtonAdd); if (addButtonEnabled && Widgets.ButtonInvisible(addRect, false)) { ComputeDisallowedTraits(currentPawn, null); SoundDefOf.Tick_Low.PlayOneShotOnCamera(); Trait selectedTrait = null; Dialog_Options <Trait> dialog = new Dialog_Options <Trait>(providerTraits.Traits) { ConfirmButtonLabel = "EdB.PC.Common.Add".Translate(), NameFunc = (Trait t) => { return(t.LabelCap); }, DescriptionFunc = (Trait t) => { return(GetTraitTip(t, state.CurrentPawn)); }, SelectedFunc = (Trait t) => { return(selectedTrait == t); }, SelectAction = (Trait t) => { selectedTrait = t; }, EnabledFunc = (Trait t) => { return(!disallowedTraitDefs.Contains(t.def)); }, CloseAction = () => { if (selectedTrait != null) { TraitAdded(selectedTrait); tipCache.Invalidate(); } } }; Find.WindowStack.Add(dialog); } if (traitsToRemove.Count > 0) { foreach (var trait in traitsToRemove) { TraitRemoved(trait); } traitsToRemove.Clear(); tipCache.Invalidate(); } }
public float CheckTrait(string name, bool status) { Trait trait = traitList.Find(t => t.name == name && t.status == status); return((trait != null) ? trait.bonus : 0f); }
// // Methods // public void DoBirthSpawn(Pawn mother, Pawn father, float chance_successful = 1.0f) { if (mother == null) { Log.Error("No mother defined"); return; } if (father == null) { Log.Warning("No father defined"); } float birthing_quality = mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("GivingBirth")).TryGetComp <HediffComp_TendDuration> ().tendQuality; mother.health.AddHediff(HediffDef.Named("PostPregnancy"), null, null); mother.health.AddHediff(HediffDef.Named("Lactating"), ChildrenUtility.GetPawnBodyPart(pawn, "Torso"), null); int num = (mother.RaceProps.litterSizeCurve == null) ? 1 : Mathf.RoundToInt(Rand.ByCurve(mother.RaceProps.litterSizeCurve, 300)); if (num < 1) { num = 1; } // Make sure the pawn looks like mommy and daddy float skin_whiteness = Rand.Range(0, 1); // Pool of "genetic traits" the baby can inherit List <Trait> traitpool = new List <Trait>(); if (mother.RaceProps.Humanlike) { // Add mom's traits to the pool foreach (Trait momtrait in mother.story.traits.allTraits) { traitpool.Add(momtrait); } if (father != null) { // Add dad's traits to the pool foreach (Trait dadtrait in father.story.traits.allTraits) { traitpool.Add(dadtrait); } // Blend skin colour between mom and dad skin_whiteness = Rand.Range(mother.story.melanin, father.story.melanin); } else { // If dad doesn't exist, just use mom's skin colour skin_whiteness = mother.story.melanin; } // Clear out any traits that aren't genetic from the list if (traitpool.Count > 0) { foreach (Trait trait in traitpool.ToArray()) { bool is_genetic = false; foreach (TraitDef gentrait in genetic_traits) { if (gentrait.defName == trait.def.defName) { is_genetic = true; } } if (!is_genetic) { traitpool.Remove(trait); } } } } // Surname passing string last_name = null; if (mother.RaceProps.Humanlike) { if (father == null) { last_name = NameTriple.FromString(mother.Name.ToStringFull).Last; } else { last_name = NameTriple.FromString(father.Name.ToStringFull).Last; } //Log.Message ("Debug: Newborn is born to the " + last_name + " family."); } //PawnGenerationRequest request = new PawnGenerationRequest (mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, mother.Map, false, true, false, false, true, false, 1, false, true, true, null, 0, 0, null, skin_whiteness, last_name); PawnGenerationRequest request = new PawnGenerationRequest(mother.kindDef, mother.Faction, PawnGenerationContext.NonPlayer, mother.Map.Tile, false, true, false, false, false, false, 1, false, true, true, false, false, null, 0, 0, null, skin_whiteness, last_name); Pawn baby = null; for (int i = 0; i < num; i++) { baby = PawnGenerator.GeneratePawn(request); if (PawnUtility.TrySpawnHatchedOrBornPawn(baby, mother)) { if (baby.playerSettings != null && mother.playerSettings != null) { baby.playerSettings.AreaRestriction = mother.playerSettings.AreaRestriction; } if (baby.RaceProps.IsFlesh) { baby.relations.AddDirectRelation(PawnRelationDefOf.Parent, mother); if (father != null) { baby.relations.AddDirectRelation(PawnRelationDefOf.Parent, father); } } // Good until otherwise proven bad bool successful_birth = true; var disabledBaby = BackstoryDatabase.allBackstories ["CustomBackstory_NA_Childhood_Disabled"]; if (disabledBaby != null) { baby.story.childhood = disabledBaby; } else { Log.Error("Couldn't find the required Backstory: CustomBackstory_NA_Childhood_Disabled!"); baby.story.childhood = null; } baby.story.adulthood = null; baby.workSettings.Disable(WorkTypeDefOf.Hunting); //hushes up the "has no ranged weapon" alert // remove all traits baby.story.traits.allTraits.Clear(); // Add some genetic traits if (traitpool.Count > 0) { for (int j = 0; j != 2; j++) { Trait gentrait = traitpool.RandomElement(); if (!baby.story.traits.HasTrait(gentrait.def)) { baby.story.traits.GainTrait(gentrait); } } } // Move the baby in front of the mother, rather than on top if (mother.CurrentBed() != null) { baby.Position = baby.Position + new IntVec3(0, 0, 1).RotatedBy(mother.CurrentBed().Rotation); } // else // baby.Position = baby.Position + new IntVec3 (0, 0, 1).RotatedBy (mother.Rotation); // The baby died from bad chance of success if (Rand.Value > chance_successful || chance_successful == 0) { successful_birth = false; } // Birth defects via drugs or alcohol if (mother.health.hediffSet.HasHediff(HediffDef.Named("BirthDefectTracker"))) { Hediff_BirthDefectTracker tracker = (Hediff_BirthDefectTracker)mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("BirthDefectTracker")); // The baby died in utero from chemical affect if (tracker.stillbirth) { successful_birth = false; } // The baby lived! So far, anyways else { // Should the baby get fetal alcohol syndrome? if (tracker.fetal_alcohol) { baby.health.AddHediff(HediffDef.Named("FetalAlcoholSyndrome")); } // If the mother got high while pregnant, crongrats retard // now your baby is addicted to crack if (tracker.drug_addictions.Count > 0) { foreach (HediffDef addiction in tracker.drug_addictions) { baby.health.AddHediff(addiction, null, null); } } } } if (father != null) { // Inbred? if (mother.relations.FamilyByBlood.Contains <Pawn> (father)) { // 50% chance to get a birth defect from inbreeding if (Rand.Range(0, 1) == 1) { GiveRandomBirthDefect(baby); if (baby.health.hediffSet.HasHediff(HediffDef.Named("DefectStillborn"))) { successful_birth = false; } } } if (successful_birth == true) { // The father is happy the baby was born //father.needs.mood.thoughts.memories.TryGainMemoryThought (ThoughtDef.Named ("PartnerGaveBirth")); father.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("PartnerGaveBirth")); } } // The baby was born! Yay! if (successful_birth == true) { // Send a message that the baby was born if (mother.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("HumanPregnancy")).Visible&& PawnUtility.ShouldSendNotificationAbout(mother)) { //Messages.Message ("MessageGaveBirth".Translate (new object[] {mother.LabelIndefinite ()}).CapitalizeFirst (), mother, MessageSound.Benefit); Find.LetterStack.ReceiveLetter("LabelGaveBirth".Translate(new object[] { baby.LabelIndefinite() }), "MessageHumanBirth".Translate(new object[] { mother.LabelIndefinite(), baby.Name.ToStringShort }), LetterDefOf.Good, baby, null); } // Try to give PPD. If not, give "New baby" thought float chance = 0.2f; if (mother.story.traits.HasTrait(TraitDefOf.Psychopath)) { chance -= 1; } if (mother.story.traits.HasTrait(TraitDef.Named("Nerves"))) { chance -= 0.2f * mother.story.traits.GetTrait(TraitDef.Named("Nerves")).Degree; } else if (mother.story.traits.HasTrait(TraitDef.Named("NaturalMood"))) { if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == 2) { chance -= 1; } if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == -2) { chance += 0.6f; } // For some reason this is broken /*} else if (mother.story.traits.HasTrait (TraitDef.Named ("Neurotic"))) { * if (mother.story.traits.GetTrait (TraitDef.Named ("Neurotic")).Degree == 1) { * chance += 0.2f; * } else * chance += 0.4f;*/ } // Because for whatever dumb reason the Math class doesn't have a Clamp method if (chance < 0) { chance = 0; } if (chance > 1) { chance = 1; } Log.Message("Debugging: Chance of PPD is " + chance * 100 + "%"); // Try to give PPD if (Rand.Value < chance) { mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("PostPartumDepression"), null); bool verybad = false; if (mother.story.traits.HasTrait(TraitDef.Named("NaturalMood"))) { if (mother.story.traits.GetTrait(TraitDef.Named("NaturalMood")).Degree == -2) { verybad = true; } } else if (mother.story.traits.HasTrait(TraitDef.Named("Neurotic"))) { if (mother.story.traits.GetTrait(TraitDef.Named("Neurotic")).Degree == 2) { verybad = true; } } // This pawn gets an exceptionally bad case of PPD if (verybad) { foreach (Thought_Memory thought in mother.needs.mood.thoughts.memories.Memories) { if (thought.def.defName == "PostPartumDepression") { thought.SetForcedStage(thought.CurStageIndex + 1); } } } } else { // If we didn't get PPD, then the pawn gets a mood buff if (mother.health.hediffSet.HasHediff(HediffDef.Named("GaveBirthFlag")) == false) { mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("IGaveBirthFirstTime")); } else { mother.needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("IGaveBirth")); } } } // The birth was not successful if (successful_birth == false) { bool aborted = false; if (chance_successful < 0f) { aborted = true; } if (baby != null) { Miscarry(baby, aborted); } } } else { Find.WorldPawns.PassToWorld(baby, PawnDiscardDecideMode.Discard); } } if (mother.Spawned) { // Spawn guck FilthMaker.MakeFilth(mother.Position, mother.Map, ThingDefOf.FilthAmnioticFluid, mother.LabelIndefinite(), 5); if (mother.caller != null) { mother.caller.DoCall(); } if (baby != null) { if (baby.caller != null) { baby.caller.DoCall(); } } Log.Message("Birth quality = " + birthing_quality); // Possible tearing from pregnancy if (birthing_quality < 0.75f) { if (birthing_quality < Rand.Value) { // Add a tear from giving birth if (birthing_quality < Rand.Value) { mother.health.AddHediff(HediffDef.Named("PregnancyTearMajor"), ChildrenUtility.GetPawnBodyPart(mother, "Torso"), null); } else { mother.health.AddHediff(HediffDef.Named("PregnancyTear"), ChildrenUtility.GetPawnBodyPart(mother, "Torso"), null); } } } } pawn.health.RemoveHediff(pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("GivingBirth"))); pawn.health.RemoveHediff(this); }
public void AddBehaviour(Trait trait) { behaviour.Add(trait); }
public Usable(string n, string t, Trait trait) { name = n; type = t; behaviour.Add(trait); }
public SimDescription CreateNewSim(SimDescription mom, SimDescription dad, CASAgeGenderFlags ages, CASAgeGenderFlags genders, CASAgeGenderFlags species, bool updateGenealogy) { if (dad == null) { dad = GetSim(CASAgeGenderFlags.Male, species, mom); if (dad == null) { dad = GetSim(CASAgeGenderFlags.Female, species, mom); if (dad == null) { return(null); } } } CASAgeGenderFlags gender = (CASAgeGenderFlags)RandomUtil.SelectOneRandomBit((uint)(genders)); CASAgeGenderFlags age = (CASAgeGenderFlags)RandomUtil.SelectOneRandomBit((uint)(ages)); if (dad.CelebrityManager == null) { dad.Fixup(); } if (mom.CelebrityManager == null) { mom.Fixup(); } SimDescription newSim = null; try { if (mom.Species == CASAgeGenderFlags.Human) { newSim = Genetics.MakeDescendant(dad, mom, age, gender, 100, new Random(), false, updateGenealogy, true, GetGeneticWorld(), false); newSim.HomeWorld = GameUtils.GetCurrentWorld(); } else { newSim = GeneticsPet.MakePetDescendant(dad, mom, age, gender, mom.Species, new Random(), updateGenealogy, GeneticsPet.SetName.SetNameNonInteractive, 0, OccultTypes.None); } } catch (Exception e) { Common.Exception(dad, mom, e); } if (newSim == null) { return(null); } if (!updateGenealogy) { FacialBlends.RandomizeBlends(mStats.AddStat, newSim, new Vector2(0f, 0f), true, Manager.GetValue <MutationUnsetRangeOption <TManager>, Vector2>(), true, Manager.GetValue <AllowAlienHouseholdOption <TManager>, bool>()); } List <OccultTypes> occults = new List <OccultTypes>(); occults.AddRange(OccultTypeHelper.CreateList(mom.OccultManager.CurrentOccultTypes, true)); occults.AddRange(OccultTypeHelper.CreateList(dad.OccultManager.CurrentOccultTypes, true)); if (updateGenealogy) { Manager.Sims.ApplyOccultChance(Manager, newSim, occults, Manager.GetValue <ChanceOfHybridOption <TManager>, int>(), Manager.GetValue <MaximumOccultOption <TManager>, int>()); } else if (species == CASAgeGenderFlags.Human) { int maxCelebrityLevel = Manager.GetValue <MaxCelebrityLevelOption <TManager>, int>(); if (maxCelebrityLevel >= 0) { newSim.CelebrityManager.mOwner = newSim; Skill scienceSkill = SkillManager.GetStaticSkill(SkillNames.Science); if (scienceSkill != null) { scienceSkill.mNonPersistableData.SkillCategory |= SkillCategory.Hidden; } try { newSim.CelebrityManager.ForceSetLevel((uint)RandomUtil.GetInt(maxCelebrityLevel)); } finally { if (scienceSkill != null) { scienceSkill.mNonPersistableData.SkillCategory &= ~SkillCategory.Hidden; } } } occults.AddRange(Manager.GetValue <ImmigrantOccultOption <TManager>, List <OccultTypes> >()); if (occults.Count > 0) { if (RandomUtil.RandomChance(Manager.GetValue <ChanceOfOccultOption <TManager>, int>())) { OccultTypeHelper.Add(newSim, RandomUtil.GetRandomObjectFromList(occults), false, false); } } } Manager.Sims.ApplyOccultChance(Manager, newSim, occults, Manager.GetValue <ChanceOfHybridOption <TManager>, int>(), Manager.GetValue <MaximumOccultOption <TManager>, int>()); OccultTypeHelper.ValidateOccult(newSim, null); OccultTypeHelper.TestAndRebuildWerewolfOutfit(newSim); newSim.FirstName = Manager.Sims.EnsureUniqueName(newSim); List <Trait> traits = new List <Trait>(newSim.TraitManager.List); foreach (Trait trait in traits) { if (trait.IsHidden) { newSim.TraitManager.RemoveElement(trait.Guid); } } List <Trait> choices = AgingManager.GetValidTraits(newSim, true, true, true); if (choices.Count > 0) { while (!newSim.TraitManager.TraitsMaxed()) { Trait choice = RandomUtil.GetRandomObjectFromList <Trait>(choices); if (!newSim.TraitManager.AddElement(choice.Guid)) { break; } } } if (SimFromBinEvents.OnGeneticSkinBlend != null) { SimFromBinEvents.OnGeneticSkinBlend(mStats, newSim, mom, dad, Manager); } FixInvisibleTask.Perform(newSim, true); if (SimFromBinEvents.OnSimFromBinUpdate != null) { SimFromBinEvents.OnSimFromBinUpdate(mStats, newSim, mom, dad, Manager); } INameTakeOption nameTake = Manager.GetOption <NameTakeOption <TManager> >(); if ((!updateGenealogy) && (nameTake != null)) { bool wasEither; newSim.LastName = Manager.Sims.HandleName(nameTake, mom, dad, out wasEither); } else if (mom != null) { newSim.LastName = mom.LastName; } else if (dad != null) { newSim.LastName = dad.LastName; } if (!updateGenealogy && Manager.GetValue <CustomNamesOnlyOption <TManager>, bool>()) { newSim.LastName = LastNameListBooter.GetRandomName(!Manager.GetValue <CustomNamesOnlyOption <TManager>, bool>(), newSim.Species, newSim.IsFemale); } return(newSim); }
protected override bool TryCastShot() { bool result = false; if (this.currentTarget != null && base.CasterPawn != null) { if(this.currentTarget.Thing != null && this.currentTarget.Thing is Pawn) { Pawn victim = this.currentTarget.Thing as Pawn; if(victim.Faction != null && victim.RaceProps.Humanlike && victim.story != null && victim.story.traits != null && victim.story.traits.allTraits.Count > 0 && !TM_Calc.IsUndead(victim)) { if (Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, victim, true))) { Thing orb = ThingMaker.MakeThing(TorannMagicDefOf.TM_Artifact_OrbOfSouls_Full, null); GenPlace.TryPlaceThing(orb, this.CasterPawn.Position, this.CasterPawn.Map, ThingPlaceMode.Near); CompEnchantedItem orbComp = orb.TryGetComp<CompEnchantedItem>(); if (victim.Faction == this.CasterPawn.Faction) { if (orbComp != null) { orbComp.SoulOrbTraits = new List<Trait>(); orbComp.SoulOrbTraits.Clear(); List<Trait> allTraits = victim.story.traits.allTraits; int iterations = Mathf.Max(allTraits.Count, 1); for (int i = 0; i < iterations; i++) { Trait transferTrait = allTraits.RandomElement(); orbComp.SoulOrbTraits.AddDistinct(transferTrait); RemoveTrait(victim, allTraits, transferTrait.def); result = true; } if(Rand.Chance(.6f)) { victim.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk); } else if(Rand.Chance(.2f)) { victim.Kill(null, null); } } else { Log.Message("no comp found for orb of souls"); } } else { if (orbComp != null) { orbComp.SoulOrbTraits = new List<Trait>(); orbComp.SoulOrbTraits.Clear(); List<Trait> allTraits = victim.story.traits.allTraits; int iterations = Mathf.Max(allTraits.Count, 1); for (int i = 0; i < iterations; i++) { Trait transferTrait = allTraits.RandomElement(); orbComp.SoulOrbTraits.AddDistinct(transferTrait); RemoveTrait(victim, allTraits, transferTrait.def); Effects(victim.Position); result = true; } if (result) { if (Rand.Chance(.15f)) { victim.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk); int relationChange = Rand.RangeInclusive(-30, -20); this.CasterPawn.Faction.TryAffectGoodwillWith(victim.Faction, relationChange, true, true, "offensive use of magic", null); } else { victim.Kill(null, null); int relationChange = Rand.RangeInclusive(-50, -30); this.CasterPawn.Faction.TryAffectGoodwillWith(victim.Faction, relationChange, true, true, "offensive use of magic", null); } } } else { Log.Message("no comp found for orb of souls"); } } } else { MoteMaker.ThrowText(victim.DrawPos, victim.Map, "TM_ResistedSpell".Translate(), -1); } } else { //invalid target Messages.Message("TM_InvalidTarget".Translate( this.CasterPawn.LabelShort, this.verbProps.label ), MessageTypeDefOf.RejectInput); } } else { //invalid target Messages.Message("TM_InvalidTarget".Translate( this.CasterPawn.LabelShort, this.verbProps.label ), MessageTypeDefOf.RejectInput); } } else { Log.Warning("failed to TryCastShot"); } this.burstShotsLeft = 0; //this.ability.TicksUntilCasting = (int)base.UseAbilityProps.SecondsToRecharge * 60; PostCastShot(result); return false; }
private static PropertyChangedBase WrapTraitIntoModel(Trait trait, GenesisContext context) { var ordinal = trait as OrdinalTrait; if (ordinal != null) return new OrdinalTraitViewModel(ordinal); var nominal = trait as NominalTrait; if (nominal != null) { return new NominalTraitViewModel(nominal, context); } throw new NotSupportedException("Unknown trait type."); }
protected override bool TryExecuteWorker(IncidentParms parms) { if (Settings.disableSkyMindSecurityStuff) { return(false); } Pawn victim; string title = "ATPP_LetterFactionRansomware".Translate(); int nbConnectedClients = Utils.GCATPP.getNbThingsConnected(); int nbUnsecurisedClients = nbConnectedClients - Utils.GCATPP.getNbSlotSecurisedAvailable(); //Déduction faction ennemis au hasard Faction faction = Find.FactionManager.RandomEnemyFaction(); LetterDef letter = LetterDefOf.ThreatBig; //Si pas de config insécurisé alors on dégage if (nbUnsecurisedClients < 0) { return(false); } victim = Utils.GCATPP.getRandomSkyMindUser(); if (victim == null) { return(false); } CompSurrogateOwner cso = victim.TryGetComp <CompSurrogateOwner>(); if (cso == null) { return(false); } cso.clearRansomwareVar(); string msg; string ransomMsg; int fee; //Bad traits added if (Rand.Chance(0.5f)) { ISet <TraitDef> tr = Utils.RansomAddedBadTraits.ToHashSet(); //Purge des traits deja possédé par la victime ET incompatibles avec ceux present for (int i = 0; i < Utils.RansomAddedBadTraits.Count; i++) { TraitDef t = Utils.RansomAddedBadTraits[i]; for (int i1 = 0; i1 < victim.story.traits.allTraits.Count; i1++) { Trait t2 = victim.story.traits.allTraits[i1]; if (t2.def == t || (t.conflictingTraits != null && t.conflictingTraits.Contains(t2.def))) { tr.Remove(t2.def); break; } } } //Selection trait aleatoire ajouté cso.ransomwareTraitAdded = tr.RandomElement(); victim.story.traits.GainTrait(new Trait(cso.ransomwareTraitAdded, 0, true)); fee = Rand.Range(Settings.ransomwareMinSilverToPayForBasTrait, Settings.ransomwareMaxSilverToPayForBasTrait); string traitLabel = ""; if (cso.ransomwareTraitAdded.degreeDatas != null && cso.ransomwareTraitAdded.degreeDatas.First() != null) { traitLabel = cso.ransomwareTraitAdded.degreeDatas.First().label; } //Log.Message("=======>"+cso.ransomwareTraitAdded.defName); msg = "ATPP_LetterFactionRansomwareBadTraitDownloadedDesc".Translate(faction.Name, victim.LabelShortCap, traitLabel); ransomMsg = "ATPP_RansomNeedPayRansomDownloadedTrait".Translate(faction.Name, traitLabel, victim.LabelShortCap, fee); } else { //Skill enlevé SkillDef find = null; SkillRecord sel = null; int v = -1; //Check tu plus gros skill de la victime for (int i = 0; i < victim.skills.skills.Count; i++) { SkillRecord s = victim.skills.skills[i]; if (s.levelInt >= v) { v = s.levelInt; find = s.def; sel = s; } } //APplication effet négatif sel.levelInt = 0; //Sauvegarde infos de skill pour restauration cso.ransomwareSkillStolen = find; cso.ransomwareSkillValue = v; fee = v * Settings.ransomwareSilverToPayToRestoreSkillPerLevel; msg = "ATPP_LetterFactionRansomwareSkillStolenDesc".Translate(faction.Name, cso.ransomwareSkillStolen.LabelCap, victim.LabelShortCap); ransomMsg = "ATPP_RansomNeedPayRansomCorruptedSKill".Translate(faction.Name, cso.ransomwareSkillStolen.LabelCap, victim.LabelShortCap, fee); } Find.LetterStack.ReceiveLetter(title, msg, letter, (LookTargets)victim, null, null); ChoiceLetter_RansomwareDemand ransom = (ChoiceLetter_RansomwareDemand)LetterMaker.MakeLetter(DefDatabase <LetterDef> .GetNamed("ATPP_CLPayRansomwareRansom")); ransom.label = "ATPP_RansomNeedPayRansomTitle".Translate(); ransom.text = ransomMsg; ransom.faction = faction; ransom.victim = victim; ransom.radioMode = true; ransom.StartTimeout(60000); ransom.fee = fee; Find.LetterStack.ReceiveLetter(ransom, null); return(true); }
void AddStuffToChief(Chief leader, string Name, string Surname, Trait trait, Abilities one, Abilities two, Abilities three,int atk, int def,int inte,int spd) { leader.SetName(Name); leader.SetSurname(Surname); leader.SetTrait(trait); leader.SetAbilityOne(one); leader.SetAbilityTwo(two); leader.SetAbilityThree(three); leader.SetAttack(atk); leader.SetDefense(def); leader.SetIntelligence(inte); leader.SetSpeed(spd); }
public HModelNode FindNode(Trait trait) { //return RecuFindNode(trait, root); foreach (HModelNode n in HModelNode.collection) { if (n.HasTrait(trait)) return n; } return null; }
public static bool IsBlacklisted(Trait t) { return(BlackList?.Contains(t.def.defName) ?? false); }
private HModelNode RecuFindNode(Trait trait, HModelNode node) { if (node.HasTrait(trait)) return node; HModelNode tmp = null; foreach (HModelNode n in node.children) tmp = RecuFindNode(trait, n); return tmp != null? tmp : null; }
/// <summary> /// Read in a trait, which are like object properties. /// </summary> /// <returns>A trait.</returns> private Trait ReadTrait() { Trait t = null; Multiname traitName = this.code.GetMultiname((int)this.abcdtr.ReadU30()); int traitCode = this.abcdtr.ReadUI8(); TraitKind kind = (TraitKind)(traitCode & 0xF); switch (kind) { case TraitKind.Slot: case TraitKind.Const: SlotTrait st = new SlotTrait(); st.Name = traitName; st.Kind = kind; st.SlotID = this.abcdtr.ReadU30(); st.TypeName = this.code.GetMultiname((int)this.abcdtr.ReadU30()); uint vindex = this.abcdtr.ReadU30(); if (vindex != 0) { st.ValKind = (ConstantKind)this.abcdtr.ReadUI8(); switch (st.ValKind) { case ConstantKind.ConInt: st.Val = this.code.IntConsts[vindex]; break; case ConstantKind.ConUInt: st.Val = this.code.UIntConsts[vindex]; break; case ConstantKind.ConDouble: st.Val = this.code.DoubleConsts[vindex]; break; case ConstantKind.ConUtf8: st.Val = this.code.StringConsts[vindex]; break; case ConstantKind.ConTrue: case ConstantKind.ConFalse: case ConstantKind.ConNull: case ConstantKind.ConUndefined: break; case ConstantKind.ConNamespace: case ConstantKind.ConPackageNamespace: case ConstantKind.ConPackageInternalNs: case ConstantKind.ConProtectedNamespace: case ConstantKind.ConExplicitNamespace: case ConstantKind.ConStaticProtectedNs: case ConstantKind.ConPrivateNs: st.Val = this.code.GetNamespace((int)vindex); break; default: throw new SWFModellerException( SWFModellerError.Internal, "Unsupported constant kind: " + st.ValKind.ToString()); } } t = st; break; case TraitKind.Class: ClassTrait ct = new ClassTrait(); ct.Name = traitName; ct.Kind = kind; ct.SlotID = this.abcdtr.ReadU30(); this.LateResolutions.Add(ct, (int)this.abcdtr.ReadU30()); /* We'll resolve the class ref later. */ t = ct; break; case TraitKind.Function: FunctionTrait ft = new FunctionTrait(); ft.Name = traitName; ft.Kind = kind; ft.SlotID = this.abcdtr.ReadU30(); ft.Fn = this.code.GetMethod((int)this.abcdtr.ReadU30()); t = ft; break; case TraitKind.Method: case TraitKind.Getter: case TraitKind.Setter: default: MethodTrait mt = new MethodTrait(); mt.Name = traitName; mt.Kind = kind; uint dispID = this.abcdtr.ReadU30(); if (dispID != 0) { mt.OverriddenMethod = this.code.GetMethod((int)dispID); } mt.Fn = this.code.GetMethod((int)this.abcdtr.ReadU30()); t = mt; break; } return(t); }
public HModelNode(Trait trait, HModelNode parent) { this.trait = trait; this.parent = parent; HModelNode.collection.Add(this); }
private Pawn MakePawnWithRawXml(string xml) { try { XmlDocument document = new XmlDocument(); document.LoadXml(xml); //Debug.Message("Pawn xml: {0}", xml); XmlNode root = document.FirstChild; string pawnKind = root.SelectSingleNode("kind").InnerText; PawnKindDef kindDef = PawnKindDef.Named(pawnKind); if (kindDef == null) { kindDef = PawnKindDefOf.AncientSoldier; } Pawn p = PawnGenerator.GeneratePawn(kindDef, rp.faction); // ==== NAME AND AGE ==== Name name = null; var nameNode = root.SelectSingleNode("name"); var attrFirst = nameNode.Attributes.GetNamedItem("first"); var attrLast = nameNode.Attributes.GetNamedItem("last"); var attrNick = nameNode.Attributes.GetNamedItem("nick"); if (attrFirst != null && attrLast != null) { name = new NameTriple(attrFirst.Value, attrNick?.Value ?? "", attrLast.Value); } else { name = new NameSingle(attrFirst?.Value ?? "Unknown"); } p.Name = name; //Debug.Message("got name"); string gender = root.SelectSingleNode("gender")?.InnerText; if (gender == "Male") { p.gender = Gender.Male; } else if (gender == "Female") { p.gender = Gender.Female; } string bioAgeString = root.SelectSingleNode("biologicalAge")?.InnerText; string chronoAgeString = root.SelectSingleNode("chronologicalAge")?.InnerText; if (bioAgeString != null && chronoAgeString != null) { long result = 0; Int64.TryParse(bioAgeString, out result); p.ageTracker.AgeBiologicalTicks = result; Int64.TryParse(chronoAgeString, out result); p.ageTracker.AgeChronologicalTicks = result + 3600000 * (-blueprint.dateShift); //+dateShift for dates, -dateShift for ages } //Debug.Message("got age"); // ==== STORY AND APPEARANCE ==== var storyNode = root.SelectSingleNode("saveable[@Class='Pawn_StoryTracker']"); if (storyNode != null) { Backstory bs = null; string childhoodDef = storyNode.SelectSingleNode("childhood")?.InnerText; if (BackstoryDatabase.TryGetWithIdentifier(childhoodDef, out bs)) { p.story.childhood = bs; } string adulthoodDef = storyNode.SelectSingleNode("adulthood")?.InnerText; if (BackstoryDatabase.TryGetWithIdentifier(adulthoodDef, out bs)) { p.story.adulthood = bs; } string bodyTypeDefName = storyNode.SelectSingleNode("bodyType")?.InnerText; if (bodyTypeDefName != null) { BodyTypeDef def = DefDatabase <BodyTypeDef> .GetNamedSilentFail(bodyTypeDefName); if (def != null) { p.story.bodyType = def; } try { string crownTypeName = storyNode.SelectSingleNode("crownType")?.InnerText; p.story.crownType = (CrownType)Enum.Parse(typeof(CrownType), crownTypeName); } catch (Exception) { } string hairDefName = storyNode.SelectSingleNode("hairDef")?.InnerText; HairDef hairDef = DefDatabase <HairDef> .GetNamedSilentFail(hairDefName); if (hairDef != null) { p.story.hairDef = hairDef; } float melanin = 0; if (float.TryParse(storyNode.SelectSingleNode("melanin")?.InnerText, out melanin)) { p.story.melanin = melanin; } string hairColorString = storyNode.SelectSingleNode("hairColor")?.InnerText; Color hairColor = (Color)ParseHelper.FromString(hairColorString, typeof(Color)); if (hairColor != null) { p.story.hairColor = hairColor; } } XmlNodeList traitsList = storyNode.SelectNodes("traits/allTraits/li"); if (traitsList != null) { p.story.traits.allTraits.RemoveAll(_ => true); foreach (XmlNode traitNode in traitsList) { string traitDefName = traitNode.SelectSingleNode("def")?.InnerText; int traitDegree = 0; int.TryParse(traitNode.SelectSingleNode("degree")?.InnerText, out traitDegree); TraitDef traitDef = DefDatabase <TraitDef> .GetNamedSilentFail(traitDefName); if (traitDef == null) { continue; } Trait t = new Trait(traitDef, traitDegree); if (t == null) { continue; } p.story.traits.allTraits.Add(t); } } } // ==== SKILLS ==== var skills = root.SelectSingleNode("saveable[@Class='Pawn_SkillTracker']"); if (skills != null) { XmlNodeList skillsList = storyNode.SelectNodes("skills/li"); foreach (XmlNode skillNode in skillsList) { string skillDefName = skillNode.SelectSingleNode("def")?.InnerText; int level = 0; int.TryParse(skillNode.SelectSingleNode("level")?.InnerText, out level); float xp = 0; float.TryParse(skillNode.SelectSingleNode("xpSinceLastLevel")?.InnerText, out xp); SkillDef skillDef = DefDatabase <SkillDef> .GetNamedSilentFail(skillDefName); if (skillDef == null) { continue; } SkillRecord skillRecord = p.skills.GetSkill(skillDef); if (skillRecord == null) { skillRecord = new SkillRecord(p, skillDef); } skillRecord.Level = level; skillRecord.xpSinceLastLevel = xp; try { string passionTypeName = skillNode.SelectSingleNode("passion")?.InnerText; if (passionTypeName != null) { skillRecord.passion = (Passion)Enum.Parse(typeof(Passion), passionTypeName); } } catch (Exception) { } } } //Debug.Message("got traits and skills"); // ==== HEALTH ==== var healthNode = root.SelectSingleNode("saveable[@Class='Pawn_HealthTracker']"); if (healthNode != null) { XmlNode healthState = healthNode.SelectSingleNode("healthState"); if (healthState?.InnerText == "Dead") { p.health.SetDead(); } XmlNodeList hediffsList = healthNode.SelectNodes("hediffSet/hediffs/li"); if (hediffsList != null) { Scribe.mode = LoadSaveMode.LoadingVars; p.health?.hediffSet?.hediffs?.RemoveAll(_ => true); //probably should pre-analyze hediffs prior to instantiating foreach (XmlNode hediffNode in hediffsList) { var sourceNode = hediffNode.SelectSingleNode("source"); var source = sourceNode?.InnerText; //Debug.Message("Source is {0} in hediff {1}", source, hediffNode.OuterXml); if (source != null) { ThingDef sourceThingDef = DefDatabase <ThingDef> .GetNamedSilentFail(source); //Debug.Message("Found non-null source node: {0}. Def: {1}", sourceNode.OuterXml, sourceThingDef); if (sourceThingDef == null) { hediffNode.RemoveChild(sourceNode); //Debug.Message("def not found, removing node, result: {0}", hediffNode.OuterXml); //continue; //skip hediffs with unknown source //} else { //Debug.Message("def found: {0}", sourceThingDef); } } try { Hediff hediff = ScribeExtractor.SaveableFromNode <Hediff>(hediffNode, null); if (hediff != null) { if (hediff.source != null && hediff.Part != null) { p.health.AddHediff(hediff); } } } catch (Exception) { } } Scribe.mode = LoadSaveMode.Inactive; } } //Debug.Message("got health"); // ==== APPAREL ==== var apparelNode = root.SelectSingleNode("apparel"); if (apparelNode != null) { XmlNodeList apparelList = apparelNode.SelectNodes("item"); foreach (XmlNode item in apparelList) { string defName = item.Attributes?.GetNamedItem("def")?.Value; string stuffDefName = item.Attributes?.GetNamedItem("stuffDef")?.Value; ThingDef stuffDef = null; ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(defName); if (stuffDefName != null) { stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(stuffDefName); } if (thingDef != null) { Apparel apparel = (Apparel)ThingMaker.MakeThing(thingDef, stuffDef); apparel.HitPoints = Rand.Range(1, (int)(apparel.MaxHitPoints * 0.6)); if (apparel is Apparel) { p.apparel.Wear(apparel, false); } } } } return(p); } catch (Exception e) { return(PawnGenerator.GeneratePawn(PawnKindDefOf.AncientSoldier, rp.faction)); } }
public bool HasTrait(Trait trait) { return this.trait == trait; }
protected override bool TryExecuteWorker(IncidentParms parms) { if (!settings.Active) { return(false); } if (tribalFaction == null) { return(false); } if (tribalFaction.PlayerRelationKind != FactionRelationKind.Hostile) { return(false); } Map map = (Map)parms.target; parms.points = StorytellerUtility.DefaultThreatPointsNow(map) * 1.2f; PawnGroupMakerParms pawnGroupMakerParms = new PawnGroupMakerParms { faction = tribalFaction, points = parms.points, generateFightersOnly = true, groupKind = PawnGroupKindDefOf.Combat, raidStrategy = RaidStrategyDefOf.ImmediateAttack, forceOneIncap = true }; List <Pawn> pawns = PawnGroupMakerUtility.GeneratePawns(pawnGroupMakerParms).ToList(); if (pawns.Count == 0) { return(false); } LordJob lordJob = new LordJob_AssaultColony(tribalFaction, canKidnap: true, canTimeoutOrFlee: false); Lord lord = LordMaker.MakeNewLord(tribalFaction, lordJob, map); lord.numPawnsLostViolently = int.MaxValue; foreach (var pawn in pawns) { if (CellFinder.TryFindRandomEdgeCellWith((IntVec3 c) => !c.Roofed(map) && c.Walkable(map) && c.Standable(map), map, 0f, out IntVec3 pos)) { GenSpawn.Spawn(pawn, pos, map); pawn.health.AddHediff(HediffDefOfLocal.ThirstHumanMeat); if (!pawn.story.traits.HasTrait(TraitDefOf.Cannibal)) { Trait t = new Trait(TraitDefOf.Cannibal); pawn.story.traits.GainTrait(t); } lord.AddPawn(pawn); } } SendStandardLetter(parms, null); Find.TickManager.slower.SignalForceNormalSpeedShort(); Find.StoryWatcher.statsRecord.numRaidsEnemy++; return(true); }
public bool HasTrait(Trait trait) { return(color.Equals(trait) || format.Equals(trait)); }
internal PersonalityTraits(BoundedNumber badGood, BoundedNumber falseHonest, BoundedNumber timidPowerful, Trait traits) { Bad_Good = badGood; False_Honest = falseHonest; Timid_Powerful = timidPowerful; Traits = traits; }
public RegexTraitPair(string regex, string name, string value) { Regex = regex; Trait = new Trait(name, value); }
public void UpdateTraitInfo(Trait trait) { traitNameLabel.text = trait.name; traitDescLabel.text = trait.description; }
public void UpdateDNAByTrait(Trait trait) { //Debug.Log (trait); if (trait == null) return; foreach (TraitModifier tm in trait.GetComponents<TraitModifier>()) { //Debug.Log (tm); if (tm as FloatTraitModifier != null) UpdateDNAByFloatTrait((FloatTraitModifier)tm); if(tm as BoolTraitModifier != null) UpdateDNAByBoolTrait((BoolTraitModifier)tm); if (tm as AlimentationTraitModifier != null) alimentation = ((AlimentationTraitModifier)tm).GetValue(); } }
public CustomPawn LoadPawn(SaveRecordPawnV4 record) { PawnKindDef pawnKindDef = null; if (record.pawnKindDef != null) { pawnKindDef = DefDatabase <PawnKindDef> .GetNamedSilentFail(record.pawnKindDef); if (pawnKindDef == null) { Log.Warning("Prepare Carefully could not find the pawn kind definition for the saved character: \"" + record.pawnKindDef + "\""); return(null); } } ThingDef pawnThingDef = ThingDefOf.Human; if (record.thingDef != null) { ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.thingDef); if (thingDef != null) { pawnThingDef = thingDef; } } PawnGenerationRequestWrapper generationRequest = new PawnGenerationRequestWrapper() { FixedBiologicalAge = record.biologicalAge, FixedChronologicalAge = record.chronologicalAge, FixedGender = record.gender }; if (pawnKindDef != null) { generationRequest.KindDef = pawnKindDef; } Pawn source = PawnGenerator.GeneratePawn(generationRequest.Request); if (source.health != null) { source.health.Reset(); } CustomPawn pawn = new CustomPawn(source); if (record.id == null) { pawn.GenerateId(); } else { pawn.Id = record.id; } if (record.type != null) { try { pawn.Type = (CustomPawnType)Enum.Parse(typeof(CustomPawnType), record.type); } catch (Exception) { pawn.Type = CustomPawnType.Colonist; } } else { pawn.Type = CustomPawnType.Colonist; } pawn.Gender = record.gender; if (record.age > 0) { pawn.ChronologicalAge = record.age; pawn.BiologicalAge = record.age; } if (record.chronologicalAge > 0) { pawn.ChronologicalAge = record.chronologicalAge; } if (record.biologicalAge > 0) { pawn.BiologicalAge = record.biologicalAge; } pawn.FirstName = record.firstName; pawn.NickName = record.nickName; pawn.LastName = record.lastName; if (record.originalFactionDef != null) { pawn.OriginalFactionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.originalFactionDef); } pawn.OriginalKindDef = pawnKindDef; if (pawn.Type == CustomPawnType.World) { if (record.faction != null) { if (record.faction.def != null) { FactionDef factionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.faction.def); if (factionDef != null) { bool randomFaction = false; if (record.faction.index != null) { CustomFaction customFaction = null; if (!record.faction.leader) { customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionByIndex(factionDef, record.faction.index.Value); } else { customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionWithLeaderOptionByIndex(factionDef, record.faction.index.Value); } if (customFaction != null) { pawn.Faction = customFaction; } else { Log.Warning("Prepare Carefully could not place at least one preset character into a saved faction because there were not enough available factions of that type in the world"); randomFaction = true; } } else { randomFaction = true; } if (randomFaction) { CustomFaction customFaction = PrepareCarefully.Instance.Providers.Factions.FindRandomCustomFactionByDef(factionDef); if (customFaction != null) { pawn.Faction = customFaction; } } } else { Log.Warning("Prepare Carefully could not place at least one preset character into a saved faction because that faction is not available in the world"); } } } } HairDef h = FindHairDef(record.hairDef); if (h != null) { pawn.HairDef = h; } else { Log.Warning("Could not load hair definition \"" + record.hairDef + "\""); Failed = true; } pawn.HeadGraphicPath = record.headGraphicPath; if (pawn.Pawn.story != null) { pawn.Pawn.story.hairColor = record.hairColor; } if (record.melanin >= 0.0f) { pawn.MelaninLevel = record.melanin; } else { pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor); } // Set the skin color for Alien Races and alien comp values. if (pawn.AlienRace != null) { pawn.SkinColor = record.skinColor; if (record.alien != null) { ThingComp alienComp = ProviderAlienRaces.FindAlienCompForPawn(pawn.Pawn); if (alienComp != null) { ProviderAlienRaces.SetCrownTypeOnComp(alienComp, record.alien.crownType); ProviderAlienRaces.SetSkinColorOnComp(alienComp, record.alien.skinColor); ProviderAlienRaces.SetSkinColorSecondOnComp(alienComp, record.alien.skinColorSecond); ProviderAlienRaces.SetHairColorSecondOnComp(alienComp, record.alien.hairColorSecond); } } } Backstory backstory = FindBackstory(record.childhood); if (backstory != null) { pawn.Childhood = backstory; } else { Log.Warning("Could not load childhood backstory definition \"" + record.childhood + "\""); Failed = true; } if (record.adulthood != null) { backstory = FindBackstory(record.adulthood); if (backstory != null) { pawn.Adulthood = backstory; } else { Log.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\""); Failed = true; } } BodyTypeDef bodyType = null; try { bodyType = DefDatabase <BodyTypeDef> .GetNamedSilentFail(record.bodyType); } catch (Exception) { } if (bodyType == null) { if (pawn.Adulthood != null) { bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender); } else { bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender); } } if (bodyType != null) { pawn.BodyType = bodyType; } pawn.ClearTraits(); for (int i = 0; i < record.traitNames.Count; i++) { string traitName = record.traitNames[i]; Trait trait = FindTrait(traitName, record.traitDegrees[i]); if (trait != null) { pawn.AddTrait(trait); } else { Log.Warning("Could not load trait definition \"" + traitName + "\""); Failed = true; } } foreach (var skill in record.skills) { SkillDef def = FindSkillDef(pawn.Pawn, skill.name); if (def == null) { Log.Warning("Could not load skill definition \"" + skill.name + "\" from saved preset"); Failed = true; continue; } pawn.currentPassions[def] = skill.passion; pawn.originalPassions[def] = skill.passion; pawn.SetOriginalSkillLevel(def, skill.value); pawn.SetUnmodifiedSkillLevel(def, skill.value); } foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn)) { if (layer.Apparel) { pawn.SetSelectedApparel(layer, null); pawn.SetSelectedStuff(layer, null); } } List <PawnLayer> apparelLayers = PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn).FindAll((layer) => { return(layer.Apparel); }); foreach (var apparelRecord in record.apparel) { // Find the pawn layer for the saved apparel record. PawnLayer layer = apparelLayers.FirstOrDefault((apparelLayer) => { return(apparelLayer.Name == apparelRecord.layer); }); if (layer == null) { Log.Warning("Could not find a matching pawn layer for the saved apparel \"" + apparelRecord.layer + "\""); Failed = true; continue; } if (apparelRecord.apparel.NullOrEmpty()) { Log.Warning("Saved apparel entry for layer \"" + apparelRecord.layer + "\" had an empty apparel def"); Failed = true; continue; } // Set the defaults. pawn.SetSelectedApparel(layer, null); pawn.SetSelectedStuff(layer, null); pawn.SetColor(layer, Color.white); ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.apparel); if (def == null) { Log.Warning("Could not load thing definition for apparel \"" + apparelRecord.apparel + "\""); Failed = true; continue; } ThingDef stuffDef = null; if (!string.IsNullOrEmpty(apparelRecord.stuff)) { stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.stuff); if (stuffDef == null) { Log.Warning("Could not load stuff definition \"" + apparelRecord.stuff + "\" for apparel \"" + apparelRecord.apparel + "\""); Failed = true; continue; } } pawn.SetSelectedApparel(layer, def); pawn.SetSelectedStuff(layer, stuffDef); pawn.SetColor(layer, apparelRecord.color); } OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn); for (int i = 0; i < record.implants.Count; i++) { SaveRecordImplantV3 implantRecord = record.implants[i]; UniqueBodyPart uniqueBodyPart = healthOptions.FindBodyPartByName(implantRecord.bodyPart, implantRecord.bodyPartIndex != null ? implantRecord.bodyPartIndex.Value : 0); if (uniqueBodyPart == null) { uniqueBodyPart = FindReplacementBodyPart(healthOptions, implantRecord.bodyPart); } if (uniqueBodyPart == null) { Log.Warning("Prepare Carefully could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\"" + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : "")); Failed = true; continue; } BodyPartRecord bodyPart = uniqueBodyPart.Record; if (implantRecord.recipe != null) { RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe); if (recipeDef == null) { Log.Warning("Prepare Carefully could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\""); Failed = true; continue; } bool found = false; foreach (var p in recipeDef.appliedOnFixedBodyParts) { if (p.defName.Equals(bodyPart.def.defName)) { found = true; break; } } if (!found) { Log.Warning("Prepare carefully could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\". Recipe does not support that part."); Failed = true; continue; } Implant implant = new Implant(); implant.BodyPartRecord = bodyPart; implant.recipe = recipeDef; implant.label = implant.Label; pawn.AddImplant(implant); } } foreach (var injuryRecord in record.injuries) { HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef); if (def == null) { Log.Warning("Prepare Carefully could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\""); Failed = true; continue; } InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def); if (option == null) { Log.Warning("Prepare Carefully could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\""); Failed = true; continue; } BodyPartRecord bodyPart = null; if (injuryRecord.bodyPart != null) { UniqueBodyPart uniquePart = healthOptions.FindBodyPartByName(injuryRecord.bodyPart, injuryRecord.bodyPartIndex != null ? injuryRecord.bodyPartIndex.Value : 0); if (uniquePart == null) { uniquePart = FindReplacementBodyPart(healthOptions, injuryRecord.bodyPart); } if (uniquePart == null) { Log.Warning("Prepare Carefully could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\"" + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : "")); Failed = true; continue; } bodyPart = uniquePart.Record; } Injury injury = new Injury(); injury.Option = option; injury.BodyPartRecord = bodyPart; if (injuryRecord.severity != null) { injury.Severity = injuryRecord.Severity; } if (injuryRecord.painFactor != null) { injury.PainFactor = injuryRecord.PainFactor; } pawn.AddInjury(injury); } pawn.CopySkillsAndPassionsToPawn(); pawn.ClearPawnCaches(); return(pawn); }
public static GameObject JointFactory(Trait t) { GameObject G = new GameObject (); G.name = "joint_"+t.id; G.AddComponent<Joint> (); Joint J = G.GetComponent<Joint> (); J.Construct (t); J.joint = t.id; return G; }
public CustomPawn LoadPawn(SaveRecordPawnV3 record) { // TODO: Ahlpa 14 Evaluate Pawn source = new Randomizer().GenerateColonist(); //Pawn source = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, Faction.OfPlayer); CustomPawn pawn = new CustomPawn(source); pawn.Gender = record.gender; if (record.age > 0) { pawn.ChronologicalAge = record.age; pawn.BiologicalAge = record.age; } if (record.chronologicalAge > 0) { pawn.ChronologicalAge = record.chronologicalAge; } if (record.biologicalAge > 0) { pawn.BiologicalAge = record.biologicalAge; } pawn.FirstName = record.firstName; pawn.NickName = record.nickName; pawn.LastName = record.lastName; HairDef h = FindHairDef(record.hairDef); if (h != null) { pawn.HairDef = h; } else { Log.Warning("Could not load hair definition \"" + record.hairDef + "\""); Failed = true; } pawn.HeadGraphicPath = record.headGraphicPath; pawn.SetColor(PawnLayers.Hair, record.hairColor); pawn.SetColor(PawnLayers.HeadType, record.skinColor); Backstory backstory = FindBackstory(record.childhood); if (backstory != null) { pawn.Childhood = backstory; } else { Log.Warning("Could not load childhood backstory definition \"" + record.childhood + "\""); Failed = true; } backstory = FindBackstory(record.adulthood); if (backstory != null) { pawn.Adulthood = backstory; } else { Log.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\""); Failed = true; } int traitCount = pawn.Traits.Count(); for (int i = 0; i < traitCount; i++) { pawn.ClearTrait(i); } for (int i = 0; i < record.traitNames.Count; i++) { string traitName = record.traitNames[i]; if (i >= traitCount) { break; } Trait trait = FindTrait(traitName, record.traitDegrees[i]); if (trait != null) { pawn.SetTrait(i, trait); } else { Log.Warning("Could not load trait definition \"" + traitName + "\""); Failed = true; } } for (int i = 0; i < record.skillNames.Count; i++) { string name = record.skillNames[i]; SkillDef def = FindSkillDef(pawn.Pawn, name); if (def == null) { Log.Warning("Could not load skill definition \"" + name + "\""); Failed = true; continue; } pawn.currentPassions[def] = record.passions[i]; pawn.originalPassions[def] = record.passions[i]; pawn.SetOriginalSkillLevel(def, record.skillValues[i]); pawn.SetUnmodifiedSkillLevel(def, record.skillValues[i]); } if (record.originalPassions != null && record.originalPassions.Count == record.skillNames.Count) { for (int i = 0; i < record.skillNames.Count; i++) { string name = record.skillNames[i]; SkillDef def = FindSkillDef(pawn.Pawn, name); if (def == null) { Log.Warning("Could not load skill definition \"" + name + "\""); Failed = true; continue; } //pawn.originalPassions[def] = record.originalPassions[i]; } } for (int i = 0; i < PawnLayers.Count; i++) { if (PawnLayers.IsApparelLayer(i)) { pawn.SetSelectedApparel(i, null); pawn.SetSelectedStuff(i, null); } } for (int i = 0; i < record.apparelLayers.Count; i++) { int layer = record.apparelLayers[i]; ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(record.apparel[i]); if (def == null) { Log.Warning("Could not load thing definition for apparel \"" + record.apparel[i] + "\""); Failed = true; continue; } ThingDef stuffDef = null; if (!string.IsNullOrEmpty(record.apparelStuff[i])) { stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.apparelStuff[i]); if (stuffDef == null) { Log.Warning("Could not load stuff definition \"" + record.apparelStuff[i] + "\" for apparel \"" + record.apparel[i] + "\""); Failed = true; continue; } } pawn.SetSelectedApparel(layer, def); pawn.SetSelectedStuff(layer, stuffDef); pawn.SetColor(layer, record.apparelColors[i]); } for (int i = 0; i < record.implants.Count; i++) { SaveRecordImplantV3 implantRecord = record.implants[i]; BodyPartRecord bodyPart = PrepareCarefully.Instance.HealthManager.ImplantManager.FindReplaceableBodyPartByName(implantRecord.bodyPart); if (bodyPart == null) { Log.Warning("Could not find replaceable body part definition \"" + implantRecord.bodyPart + "\""); Failed = true; continue; } if (implantRecord.recipe != null) { RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe); if (recipeDef == null) { Log.Warning("Could not find recipe definition \"" + implantRecord.recipe + "\""); Failed = true; continue; } bool found = false; foreach (var p in recipeDef.appliedOnFixedBodyParts) { if (p.defName.Equals(bodyPart.def.defName)) { found = true; break; } } if (!found) { Log.Warning("Body part \"" + bodyPart.def.defName + "\" does not match recipe used to replace it"); Failed = true; continue; } Implant implant = new Implant(); implant.BodyPartRecord = bodyPart; implant.recipe = recipeDef; implant.label = implant.Label; pawn.AddImplant(implant); } } foreach (var injuryRecord in record.injuries) { HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef); if (def == null) { Log.Warning("Could not find hediff definition \"" + injuryRecord.hediffDef + "\""); Failed = true; continue; } InjuryOption option = PrepareCarefully.Instance.HealthManager.InjuryManager.FindOptionByHediffDef(def); if (option == null) { Log.Warning("Could not find injury option for \"" + injuryRecord.hediffDef + "\""); Failed = true; continue; } BodyPartRecord bodyPart = null; if (injuryRecord.bodyPart != null) { bodyPart = PrepareCarefully.Instance.HealthManager.FirstBodyPartRecord(injuryRecord.bodyPart); if (bodyPart == null) { Log.Warning("Could not find body part \"" + injuryRecord.bodyPart + "\""); Failed = true; continue; } } Injury injury = new Injury(); injury.Option = option; injury.BodyPartRecord = bodyPart; if (injuryRecord.severity != null) { injury.Severity = injuryRecord.Severity; } pawn.AddInjury(injury); } pawn.RandomInjuries = record.randomInjuries; pawn.RandomRelations = record.randomRelations; pawn.ClearCachedAbilities(); pawn.ClearCachedLifeStage(); return(pawn); }
public CheckForTrait(IGame game, ICardInPlay target, Trait trait) : base(game) { this.Target = target; this.Trait = trait; }
public static bool PossessTrait(Unit _unit, Trait _trait) { return(_unit.type.traits.Contains(_trait)); }
public void UpdateTrait(Trait trait, float observedValue) { HModelNode leaf = FindNode(trait); leaf.UpdateTrait(observedValue); }
public bool HasTrait(Trait trait) { return(traits.Contains(trait)); }
public uint GetNodeValue(Trait trait) { return FindNode(trait).GetTraitValueAsUInt(); }
public ITextBuilder Trait(Trait trait) { this.traits.Add(trait); return this; }
public string DuplicantSkillString(Skill skill) { string text = string.Empty; MinionIdentity minionIdentity = skillsScreen.CurrentlySelectedMinion as MinionIdentity; if ((UnityEngine.Object)minionIdentity != (UnityEngine.Object)null) { MinionResume component = minionIdentity.GetComponent <MinionResume>(); if ((UnityEngine.Object)component == (UnityEngine.Object)null) { return(string.Empty); } LocString cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.CAN_MASTER; if (!component.HasMasteredSkill(skill.Id)) { MinionResume.SkillMasteryConditions[] skillMasteryConditions = component.GetSkillMasteryConditions(skill.Id); if (!component.CanMasterSkill(skillMasteryConditions)) { bool flag = false; text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.CANNOT_MASTER; text += string.Format(cAN_MASTER, minionIdentity.GetProperName(), skill.Name); if (Array.Exists(skillMasteryConditions, (MinionResume.SkillMasteryConditions element) => element == MinionResume.SkillMasteryConditions.UnableToLearn)) { flag = true; Trait trait = null; string choreGroupID = Db.Get().SkillGroups.Get(skill.skillGroup).choreGroupID; if (!string.IsNullOrEmpty(choreGroupID)) { Traits component2 = minionIdentity.GetComponent <Traits>(); foreach (Trait trait2 in component2.TraitList) { if (trait2.disabledChoreGroups != null) { ChoreGroup[] disabledChoreGroups = trait2.disabledChoreGroups; foreach (ChoreGroup choreGroup in disabledChoreGroups) { if (choreGroup.Id == choreGroupID && trait == null) { trait = trait2; } } } } } text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.PREVENTED_BY_TRAIT; text += string.Format(cAN_MASTER, trait.Name); } if (!flag && Array.Exists(skillMasteryConditions, (MinionResume.SkillMasteryConditions element) => element == MinionResume.SkillMasteryConditions.MissingPreviousSkill)) { text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.REQUIRES_PREVIOUS_SKILLS; text += string.Format(cAN_MASTER); } if (!flag && Array.Exists(skillMasteryConditions, (MinionResume.SkillMasteryConditions element) => element == MinionResume.SkillMasteryConditions.NeedsSkillPoints)) { text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.REQUIRES_MORE_SKILL_POINTS; text += string.Format(cAN_MASTER); } } else { if (Array.Exists(skillMasteryConditions, (MinionResume.SkillMasteryConditions element) => element == MinionResume.SkillMasteryConditions.StressWarning)) { text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.STRESS_WARNING_MESSAGE; text += string.Format(cAN_MASTER, skill.Name, minionIdentity.GetProperName()); } if (Array.Exists(skillMasteryConditions, (MinionResume.SkillMasteryConditions element) => element == MinionResume.SkillMasteryConditions.SkillAptitude)) { text += "\n"; cAN_MASTER = UI.SKILLS_SCREEN.ASSIGNMENT_REQUIREMENTS.MASTERY.SKILL_APTITUDE; text += string.Format(cAN_MASTER, minionIdentity.GetProperName(), skill.Name); } } } } return(text); }
private static void GiveRandomTraitsTo(Pawn pawn) { if (pawn.story == null) return; int num = Rand.RangeInclusive(2, 3); while (pawn.story.traits.allTraits.Count < num) { TraitDef newTraitDef = DefDatabase<TraitDef>.AllDefsListForReading.RandomElementByWeight((TraitDef tr) => tr.commonality); if (!pawn.story.traits.HasTrait(newTraitDef)) { if (!pawn.story.traits.allTraits.Any((Trait tr) => newTraitDef.ConflictsWith(tr)) && (newTraitDef.conflictingTraits == null || !newTraitDef.conflictingTraits.Any((TraitDef tr) => pawn.story.traits.HasTrait(tr)))) { if (newTraitDef.requiredWorkTypes == null || !pawn.story.OneOfWorkTypesIsDisabled(newTraitDef.requiredWorkTypes)) { if (!pawn.story.WorkTagIsDisabled(newTraitDef.requiredWorkTags)) { Trait trait = new Trait(newTraitDef); trait.degree = PawnGenerator.RandomTraitDegree(trait.def); if (pawn.mindState.breaker.HardBreakThreshold + trait.OffsetOfStat(StatDefOf.MentalBreakThreshold) <= 40f) { pawn.story.traits.GainTrait(trait); } } } } } } }
public string GetDetails(IMiniSimDescription me) { Common.StringBuilder msg = new Common.StringBuilder(); try { msg += GetHeader(me); SimDescription simDesc = me as SimDescription; MiniSimDescription miniDesc = me as MiniSimDescription; if (simDesc != null) { if (!simDesc.AgingEnabled) { msg += Common.Localize("Status:AgingDisabled", me.IsFemale); } msg += Common.NewLine + Common.LocalizeEAString("Ui/Caption/HUD/KnownInfoDialog:" + simDesc.Zodiac.ToString()); } else if (miniDesc != null) { if (!miniDesc.mbAgingEnabled) { msg += Common.Localize("Status:AgingDisabled", me.IsFemale); } } SimDescription.DeathType deathType = SimDescription.DeathType.None; if (simDesc != null) { deathType = simDesc.DeathStyle; } else if (miniDesc != null) { deathType = miniDesc.mDeathStyle; } if (deathType != SimDescription.DeathType.None) { msg += Common.Localize("Status:Death", me.IsFemale) + Urnstones.GetLocalizedString(me.IsFemale, deathType); } List <OccultTypes> occultTypes = new List <OccultTypes>(); OccultTypes primaryOccult = OccultTypes.None; if (simDesc != null) { if (simDesc.OccultManager != null) { foreach (OccultTypes type in Enum.GetValues(typeof(OccultTypes))) { if (type == OccultTypes.None) { continue; } if (simDesc.OccultManager.HasOccultType(type)) { occultTypes.Add(type); } } } if (simDesc.SupernaturalData != null) { primaryOccult = simDesc.SupernaturalData.OccultType; } } else if (miniDesc != null) { if (miniDesc.IsVampire) { occultTypes.Add(OccultTypes.Vampire); } if (miniDesc.IsFrankenstein) { occultTypes.Add(OccultTypes.Frankenstein); } if (miniDesc.IsMummy) { occultTypes.Add(OccultTypes.Mummy); } if (miniDesc.IsUnicorn) { occultTypes.Add(OccultTypes.Unicorn); } if (miniDesc.IsGenie) { occultTypes.Add(OccultTypes.Unicorn); } if (miniDesc.IsWerewolf) { occultTypes.Add(OccultTypes.Werewolf); } if (miniDesc.IsWitch) { occultTypes.Add(OccultTypes.Witch); } if (miniDesc.IsFairy) { occultTypes.Add(OccultTypes.Fairy); } } foreach (OccultTypes type in occultTypes) { string isPrimary = null; if (primaryOccult == type) { isPrimary = " (+)"; } msg += Common.Localize("Status:Occult", me.IsFemale, new object[] { OccultTypeHelper.GetLocalizedName(type) + isPrimary }); } if (simDesc != null) { if (simDesc.LotHome != null) { msg += Common.Localize("Status:TypeResidentV2", me.IsFemale); } else if (simDesc.Household == null) { msg += Common.Localize("Status:TypeOutOfTowner", me.IsFemale); } else if (simDesc.AssignedRole != null) { msg += Common.Localize("Status:TypeService", me.IsFemale, new object[] { Roles.GetLocalizedName(simDesc.AssignedRole) }); } else if (simDesc.Household.IsServiceNpcHousehold) { if (SimTypes.InServicePool(simDesc)) { msg += Common.Localize("Status:TypeService", me.IsFemale, new object[] { Common.LocalizeEAString("Ui/Caption/Services/Service:" + simDesc.CreatedByService.ServiceType.ToString()) }); } else { msg += Common.Localize("Status:TypeOutOfTowner", me.IsFemale); } } else if (simDesc.Household.IsTouristHousehold) { msg += Common.Localize("Status:TypeTourist", me.IsFemale); } else if (simDesc.Household.IsTravelHousehold) { msg += Common.Localize("Status:TypeTravel", me.IsFemale); } else { msg += Common.Localize("Status:TypeHomeless", me.IsFemale); } } else if (miniDesc != null) { msg += Common.Localize("Status:TypeOutOfTowner", me.IsFemale); } string worldName = me.HomeWorld.ToString(); if (!Enum.IsDefined(typeof(WorldName), me.HomeWorld)) { worldName = ((ulong)me.HomeWorld).ToString(); } string homeWorld = Common.LocalizeEAString("Ui/Caption/Global/WorldName/EP01:" + worldName);// Sims3.UI.Responder.Instance.HudModel.LocationName(me.HomeWorld); if ((!string.IsNullOrEmpty(homeWorld)) && (homeWorld != "Ui/Caption/Global/WorldName/EP01:" + worldName)) { msg += Common.Localize("Status:HomeWorld", me.IsFemale, new object[] { homeWorld }); } if (simDesc != null) { msg += Common.Localize("Status:Favorites", me.IsFemale, new object[] { CASCharacter.GetFavoriteColor(simDesc.FavoriteColor), CASCharacter.GetFavoriteFood(simDesc.FavoriteFood), CASCharacter.GetFavoriteMusic(simDesc.FavoriteMusic) }); string LTWName = LifetimeWants.GetName(simDesc); if (!string.IsNullOrEmpty(LTWName)) { msg += Common.Localize("Status:LTW", me.IsFemale, new object[] { LTWName, Common.Localize("YesNo:" + simDesc.HasCompletedLifetimeWish.ToString()) }); } else { msg += Common.Localize("Status:NoLTW", me.IsFemale); } msg += Common.Localize("Status:LifetimeReward", me.IsFemale, new object[] { simDesc.LifetimeHappiness, simDesc.SpendableHappiness }); if (simDesc.CreatedSim != null) { if (simDesc.LotHome == simDesc.CreatedSim.LotCurrent) { msg += Common.Localize("Status:LocationHome", me.IsFemale); } else if ((simDesc.CreatedSim.LotCurrent != null) && (!simDesc.CreatedSim.LotCurrent.IsWorldLot)) { msg += Common.Localize("Status:LocationAt", me.IsFemale, new object[] { simDesc.CreatedSim.LotCurrent.Name }); } else { msg += Common.Localize("Status:LocationTransit", me.IsFemale); } msg += Common.Localize("Status:Mood" + simDesc.CreatedSim.MoodManager.MoodFlavor.ToString(), me.IsFemale); if (simDesc.CreatedSim.Autonomy != null) { if (simDesc.CreatedSim.Autonomy.AllowedToRunMetaAutonomy) { msg += Common.Localize("Status:Autonomous", me.IsFemale); } foreach (Situation situation in simDesc.CreatedSim.Autonomy.SituationComponent.Situations) { msg += Common.Localize("Status:Situation", me.IsFemale, new object[] { situation.ToString() }); } } } else { msg += Common.Localize("Status:LocationOutOfTown", me.IsFemale); } } string traits = null; int traitCount = 0; if (simDesc != null) { if (simDesc.TraitManager != null) { foreach (Trait trait in simDesc.TraitManager.List) { if (trait.IsReward) { continue; } traits += Common.NewLine + trait.TraitName(me.IsFemale); traitCount++; } } } else if (miniDesc != null) { if (miniDesc.Traits != null) { foreach (TraitNames traitName in miniDesc.Traits) { Trait trait = TraitManager.GetTraitFromDictionary(traitName); if (trait == null) { continue; } if (trait.IsReward) { continue; } traits += Common.NewLine + trait.TraitName(me.IsFemale); traitCount++; } } } if (traitCount > 10) { msg += Common.Localize("Status:TraitsOverTen", me.IsFemale, new object[] { traitCount }); } else if (traitCount > 0) { msg += Common.Localize("Status:Traits", me.IsFemale, new object[] { traits }); } } catch (Exception e) { Common.Exception(me.FullName, e); msg += Common.NewLine + "END OF LINE"; } return(msg.ToString()); }
protected TraitLeveler GetTraitLeveler(Trait trait) { foreach (TraitLeveler tl in traits) { if (tl.trait.GetName() == trait.GetName()) return tl; } return null; }
public static void Post_GeneratePawn(PawnGenerationRequest request, ref Pawn __result) { if (__result != null && __result.def == AdeptusThingDefOf.OG_Alien_Eldar) { if (__result.story == null) { return; } Pawn_StoryTracker storyTracker = __result.story; Backstory adulthood = storyTracker.adulthood; bool adult = adulthood != null; if (storyTracker.childhood.spawnCategories.Contains("Ork_Base_Child")) { } else if (storyTracker.childhood.spawnCategories.Contains("Ork_Odd_Child")) { } else if (storyTracker.childhood.spawnCategories.Contains("Eldar_Craftworld_Psyker")) { if (!storyTracker.traits.HasTrait(TraitDefOf.PsychicSensitivity)) { Trait trait = new Trait(TraitDefOf.PsychicSensitivity, 1); if (storyTracker.adulthood != null) { if (storyTracker.adulthood.identifier.Contains("_Farseer")) { trait = new Trait(TraitDefOf.PsychicSensitivity, 2); } else if (storyTracker.adulthood.identifier.Contains("_Warlock")) { Rand.PushState(); trait = new Trait(TraitDefOf.PsychicSensitivity, Rand.RangeInclusive(1, 2)); Rand.PopState(); } } __result.story.traits.GainTrait(trait); } if (AdeptusIntergrationUtility.enabled_Royalty) { if (!__result.health.hediffSet.HasHediff(HediffDefOf.PsychicAmplifier)) { Hediff_Psylink _Psylink = HediffMaker.MakeHediff(HediffDefOf.PsychicAmplifier, __result, __result.RaceProps.body.AllParts.FirstOrDefault(x => x.def == BodyPartDefOf.Brain)) as Hediff_Psylink; _Psylink.suppressPostAddLetter = true; __result.health.AddHediff(_Psylink); } if (storyTracker.adulthood.identifier.Contains("_Farseer")) { Rand.PushState(); __result.ChangePsylinkLevel(Math.Min(Rand.RangeInclusive(3, 5), __result.GetMaxPsylinkLevel()), false); Rand.PopState(); } else if (storyTracker.adulthood.identifier.Contains("_Warlock")) { Rand.PushState(); __result.ChangePsylinkLevel(Math.Min(Rand.RangeInclusive(1, 3), __result.GetMaxPsylinkLevel()), false); Rand.PopState(); } else if (adult) { Rand.PushState(); __result.ChangePsylinkLevel(Math.Min(Rand.RangeInclusive(0, 2), __result.GetMaxPsylinkLevel()), false); Rand.PopState(); } } } /* * if (adult) * { * if (__result.isOrk()) * { * if (storyTracker.adulthood.identifier.Contains("_Boss") || storyTracker.adulthood.identifier.Contains("_Nob")) * { * HarmonyPatches.ChangeBodyType(__result, BodyTypeDefOf.Hulk); * } * else * { * HarmonyPatches.ChangeBodyType(__result, BodyTypeDefOf.Male); * } * } * } */ } }
public bool HasTrait(Trait trait) { foreach(TraitLeveler tl in traits) { if (tl.trait.GetName() == trait.GetName()) return true; } return false; }
protected void AddTrait(Trait trait) { traits.Add(trait); }
public void ChangeTrait(Trait trait) { this.trait = trait; swap = true; }
private static void GenerateTraits(Pawn pawn, PawnGenerationRequest request) { if (pawn.story == null) { return; } if (pawn.story.childhood.forcedTraits != null) { List <TraitEntry> forcedTraits = pawn.story.childhood.forcedTraits; for (int i = 0; i < forcedTraits.Count; i++) { TraitEntry traitEntry = forcedTraits[i]; if (traitEntry.def == null) { Log.Error("Null forced trait def on " + pawn.story.childhood); } else if (!pawn.story.traits.HasTrait(traitEntry.def)) { pawn.story.traits.GainTrait(new Trait(traitEntry.def, traitEntry.degree, false)); } } } if (pawn.story.adulthood != null && pawn.story.adulthood.forcedTraits != null) { List <TraitEntry> forcedTraits2 = pawn.story.adulthood.forcedTraits; for (int j = 0; j < forcedTraits2.Count; j++) { TraitEntry traitEntry2 = forcedTraits2[j]; if (traitEntry2.def == null) { Log.Error("Null forced trait def on " + pawn.story.adulthood); } else if (!pawn.story.traits.HasTrait(traitEntry2.def)) { pawn.story.traits.GainTrait(new Trait(traitEntry2.def, traitEntry2.degree, false)); } } } int num = Rand.RangeInclusive(2, 3); if (request.AllowGay && (LovePartnerRelationUtility.HasAnyLovePartnerOfTheSameGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheSameGender(pawn))) { Trait trait = new Trait(TraitDefOf.Gay, PawnGenerator.RandomTraitDegree(TraitDefOf.Gay), false); pawn.story.traits.GainTrait(trait); } while (pawn.story.traits.allTraits.Count < num) { TraitDef newTraitDef = DefDatabase <TraitDef> .AllDefsListForReading.RandomElementByWeight((TraitDef tr) => tr.GetGenderSpecificCommonality(pawn)); if (!pawn.story.traits.HasTrait(newTraitDef)) { if (newTraitDef == TraitDefOf.Gay) { if (!request.AllowGay) { continue; } if (LovePartnerRelationUtility.HasAnyLovePartnerOfTheOppositeGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheOppositeGender(pawn)) { continue; } } if (request.Faction == null || Faction.OfPlayerSilentFail == null || !request.Faction.HostileTo(Faction.OfPlayer) || newTraitDef.allowOnHostileSpawn) { if (!pawn.story.traits.allTraits.Any((Trait tr) => newTraitDef.ConflictsWith(tr)) && (newTraitDef.conflictingTraits == null || !newTraitDef.conflictingTraits.Any((TraitDef tr) => pawn.story.traits.HasTrait(tr)))) { if (newTraitDef.requiredWorkTypes == null || !pawn.story.OneOfWorkTypesIsDisabled(newTraitDef.requiredWorkTypes)) { if (!pawn.story.WorkTagIsDisabled(newTraitDef.requiredWorkTags)) { int degree = PawnGenerator.RandomTraitDegree(newTraitDef); if (!pawn.story.childhood.DisallowsTrait(newTraitDef, degree) && (pawn.story.adulthood == null || !pawn.story.adulthood.DisallowsTrait(newTraitDef, degree))) { Trait trait2 = new Trait(newTraitDef, degree, false); if (pawn.mindState != null && pawn.mindState.mentalBreaker != null) { float num2 = pawn.mindState.mentalBreaker.BreakThresholdExtreme; num2 += trait2.OffsetOfStat(StatDefOf.MentalBreakThreshold); num2 *= trait2.MultiplierOfStat(StatDefOf.MentalBreakThreshold); if (num2 > 0.4f) { continue; } } pawn.story.traits.GainTrait(trait2); } } } } } } } }