//--------------------------------------------------------------------- public Parameters(Ecoregions.IDataset ecoregionDataset, Species.IDataset speciesDataset) : base(ecoregionDataset, speciesDataset) { this.climateChangeUpdates = new List<ClimateChange.ParametersUpdate>(); }
private static Species GetIndividualsFromSaveGenome(List<SaveGenome> saveGenomes) { Random rand = new Random(); Species individuals = new Species(); for (int i = 0; i < saveGenomes.Count; i++ ) { individuals.Add(new Individual(i, saveGenomes[i].x, saveGenomes[i].y, saveGenomes[i].dx, saveGenomes[i].dy, saveGenomes[i].dx2, saveGenomes[i].dy2, new Parameters(saveGenomes[i].neighborhoodRadius, saveGenomes[i].normalSpeed, saveGenomes[i].maxSpeed, saveGenomes[i].c1, saveGenomes[i].c2, saveGenomes[i].c3, saveGenomes[i].c4, saveGenomes[i].c5), saveGenomes[i].type, saveGenomes[i].isMobile) ); } return individuals; }
//-5000 to -2500- Starving //-2500 to -1000- Hungry //-1000 to 0- Slightly Hungry //0 to 1000- Fed //1000 to 2500- Well Fed //2500 to 5000- Stuffed public Player(string n, Species sp, Class c) { name = n; species = sp; career = c; identifier = species.abbrv + career.abbrv; stats = species.baseStats.addStatMod(career.statMod).adjust(); stats.xp = 0; if (species == Species._darkElf) { status.addStatus(new Status("Shadowbound", 1, true, ConsoleForeground.Maroon, ConsoleBackground.Black)); status.addStatus(new Status("Accursed", 1, true, ConsoleForeground.Red, ConsoleBackground.Black)); } if (species == Species._faerie) { status.addStatus(new Status("Magic Sight", 1, true, ConsoleForeground.Yellow, ConsoleBackground.Black)); status.addStatus(new Status("Fly", 1, true, ConsoleForeground.Cyan, ConsoleBackground.Black)); } if (species == Species._woodElf) { status.addStatus(new Status("rPoison", 1, true, ConsoleForeground.Green, ConsoleBackground.Black)); } if (species == Species._merfolk) { status.addStatus(new Status("Swimmer", 1, true, ConsoleForeground.Cyan, ConsoleBackground.Black)); } if (species == Species._karura) { status.addStatus(new Status("Fast Metabolism", 1, true, ConsoleForeground.Maroon, ConsoleBackground.Black)); } //status.addStatus(new Status("Clairvoyance", 1, true, ConsoleForeground.Olive, ConsoleBackground.Black)); equipment = new Equipment(); abilities.Add(new Ability("Rest and Heal", AbilityEffect.RESTHEAL, 0, 0)); //status.addStatus(new Status("Fly", 1, 2000, ConsoleForeground.Cyan, ConsoleBackground.Black)); }
public void AddSpecies(string name, float selfInteraction, float birthRate, float population=0f) { if (system.ContainsKey(name)) { throw new System.ArgumentException("system already contains a species with that name!"); } Species newSpecies = new Species(name, population, birthRate, -selfInteraction); // -!!! system.Add(name, newSpecies); }
public PopulationSimulator(int width, int height) { swarmInBirthOrder = new Species(); swarmInXOrder = new Species(); swarmInYOrder = new Species(); Population = new Population(); }
/// <summary> /// Initializes a new instance of the <see cref="Race" /> class for testing. /// </summary> /// <param name="species">Species of the race.</param> /// <param name="color">Color.</param> public Race(Species species, GameColor color) { Species = species; LeaderName = species.GetDefaultLeaderName(); ImageFilename = species.GetImageFilename(); Description = species.GetEnumAttributeText(); Color = color; }
public static String GenerateName(Species species) { string result = ""; string[] split = new string[1] { "\r\n" }; char[] splitchar = new char[1] { ':' }; switch (species) { case Species.Human: srReader = new StreamReader("Data/HumanNames.txt"); break; default: return "TEST"; } NameCategories = srReader.ReadToEnd().Split(splitchar, System.StringSplitOptions.RemoveEmptyEntries); for (int i = 1; i <= NameCategories.Length - 1; i = i + 2) { SpecificNames = ((String)NameCategories.GetValue(i)).Split(split, System.StringSplitOptions.RemoveEmptyEntries); result = result + SpecificNames.GetValue(ran.Next(0, SpecificNames.Length - 1)); } result = result.Replace("%", string.Empty); return result; }
public Judge(int day, Agent agent, Agent target, Species result) { Day = day; Agent = agent; Target = target; Result = result; }
public Monkey(string name, int age, Species species, bool hasPoo) { Name = name; Age = age; _Species = species; HasPoo = hasPoo; }
public List<Species> CreatePopulation(int width, int height) { if (parameters == null) return null; List<Species> newListSpecies = new List<Species>(); Parameters tempParam; for (int i = 0; i < parameters.Count; i++) { tempParam = parameters[i]; var spcs = new Species(new List<Individual>()); for (int j = 1; j < popCounts[i]; j++) { spcs.Add(new Individual(j, rand.NextDouble() * width, rand.NextDouble() * height, rand.NextDouble() * 10 - 5, rand.NextDouble() * 10 - 5, new Parameters( tempParam))); } newListSpecies.Add(spcs); } //mutate(); return newListSpecies; }
private static void Main(string[] args) { var network = NeuralBuilder.BuildFullConnected(Math.Tanh, 1, 20, 20, 1); var mutationDic = new Dictionary<IMutation, double> { {new WeigthMutate(), 1}, {new ConnectSynapse(), 0.5}, {new RemoveSynapse(), 0.5}, // {new ConnectNeuron(Math.Tanh), 0.4}, {new MultiMutate(new[] {new WeigthMutate(), new WeigthMutate()}), 0.5}, {new MultiMutate(new[] { new ConnectSynapse(), new ConnectSynapse()}), 0.2} }; var specie = new Species(FitFunc, network, mutationDic); specie.OnImprovement += OnImprovement; specie.Sensitivity = 0.0001; lastFit = FitFunc(network); startTime = DateTime.Now; while (true) { specie.Iteration(); specie.Sensitivity *= 0.9999; if (network.LoopDetected()) Console.WriteLine("LOOP!"); } network.MetricsRecitate(); NeuralBuilder.BuildDOTGraph(network, "outgraph.dot"); }
//--------------------------------------------------------------------- public InputParameters(Ecoregions.IDataset ecoregionDataset, Species.IDataset speciesDataset) : base(ecoregionDataset, speciesDataset) { sufficientLight = new List<ISufficientLight>(); this.climateChangeUpdates = new List<DynamicChange.ParametersUpdate>(); }
/// <summary> /// Initializes a new instance of the <see cref="RaceStat"/> struct. /// </summary> /// <param name="species">The species.</param> /// <param name="leaderName">Name of the race leader.</param> /// <param name="imageFilename">The filename used to find the image texture in an atlas for this race.</param> /// <param name="description">The race description.</param> /// <param name="color">The race color.</param> public RaceStat(Species species, string leaderName, string imageFilename, string description, GameColor color) : this() { Species = species; LeaderName = leaderName; ImageFilename = imageFilename; Description = description; Color = color; }
private static List<SaveGenome> GetSavedGenomes(Species species) { List<SaveGenome> savedGenomes = new List<SaveGenome>(); foreach (Individual individual in species) { savedGenomes.Add(SwarmSaveHelper.GetSavedGenomeFromIndividual(individual)); } return savedGenomes; }
public void PropertyTests() { // arrange const int id = 5; const string name = "Dog"; // act var species = new Species() { Id = id, Name = name }; // assert Assert.AreEqual(species.Id, id); Assert.AreEqual(species.Name, name); }
//--------------------------------------------------------------------- public Parameters(Ecoregions.AuxParm<Percentage>[] minRelativeBiomass, Species.AuxParm<double> leafLongevity, Species.AuxParm<double> woodyDecayRate, Species.AuxParm<double> mortCurveShapeParm, Species.AuxParm<Ecoregions.AuxParm<double>> establishProbability, Species.AuxParm<Ecoregions.AuxParm<int>> maxANPP, Species.AuxParm<Ecoregions.AuxParm<double>> leafLitterDecayRate) { this.minRelativeBiomass = minRelativeBiomass; this.leafLongevity = leafLongevity; this.woodyDecayRate = woodyDecayRate; this.mortCurveShapeParm = mortCurveShapeParm; this.establishProbability = establishProbability; this.maxANPP = maxANPP; this.leafLitterDecayRate = leafLitterDecayRate; }
public void PropertyTests() { // arrange const int id = 5; const string name = "Dalmatian"; var species = new Species() { Id = 1, Name = "Dog" }; var category = new Category() { Id = 5, Name = "Guard dog" }; // act var breed = new Breed() { Id = id, Name = name, Species = species, Category = category }; // assert Assert.AreEqual(breed.Id, id); Assert.AreEqual(breed.Name, name); Assert.AreEqual(breed.Species, species); Assert.AreEqual(breed.Category, category); }
static void OnImprovement(Species sender, IMutation mutationType) { Console.Clear(); var improve = sender.BestFit - lastFit; if (imrovement.ContainsKey(mutationType)) imrovement[mutationType] += improve; else imrovement.Add(mutationType,improve); Console.WriteLine("Iteration: {0} Seconds elapsed: {1}", sender.Iterations, (DateTime.Now- startTime).TotalSeconds); Console.WriteLine("Fit: {0}",sender.BestFit); Console.WriteLine("Neurons: {0}, Synapses: {1} \r\n", sender.Network.NeuronsCount, sender.Network.SynapsesCount); foreach (var value in imrovement.OrderByDescending(a=>a.Value)) Console.WriteLine(value.Key.GetType().Name+" "+value.Value/sender.MutationsCollection[value.Key]); }
// --- Public methods of the class Player --- /// <summary>The default constructor creates a new human player and gives it a new id.</summary> public Player(Position position) { if (_instanceCounter >= 2) { // The number of players to created exceeds 2: throw new PSTException("Player: Trying to create more than two players"); } _id = _instanceCounter; ++_instanceCounter; // By default the player is a human: _species = Species.Human; // Set some default for the computer strength: _computerStrength = ComputerStrength.Medium; _position = position; // By default the player's name is taken from the resources, i.e. something like "Player #1": _name = KalahaResources.I.GetRes("Player", (_id + 1)); }
// Update is called once per frame void Update() { // If we have no life on this planet, then there's a random chance of life forming if (population == 0) { float f = Random.Range(0.0f, 1.0f); Debug.Log(CHANCE_OF_ABIOGENESIS * Time.deltaTime); if (f <= CHANCE_OF_ABIOGENESIS * Time.deltaTime) { // Life has formed! how miraculous Species species = new Species("test"); SpeciesOnPlanet aSpeciesOnPlanet = new SpeciesOnPlanet(species, gameObject, 2); speciesOnPlanet.Add(aSpeciesOnPlanet); } } population = 0; foreach (SpeciesOnPlanet species in speciesOnPlanet) { population += species.population; } }
public bool AddAnimal(string name, DateTime birthDate, Species species, Cage cage, decimal weight, Gender gender, Employee guard, Employee vet, DateTime arivalDate) { var newAnimal = new Animal() { Name = name, BirthDate = birthDate, SpeciesID = species.SpeciesID, CageID = cage.CageID, Weight = (decimal)weight, Gender = (int)gender, GuardID = guard.EmployeeID, VetID = vet.EmployeeID, ArrivalDate = arivalDate }; using (var db = new ZooMasterDBEntities()) { db.Animals.Add(newAnimal); return db.SaveChanges() == 1; } }
//--------------------------------------------------------------------- public Parameters(int timestep, SeedingAlgorithms seedAlgorithm, Ecoregions.AuxParm<Percentage>[] minRelativeBiomass, Species.AuxParm<double> leafLongevity, Species.AuxParm<double> woodyDecayRate, Species.AuxParm<double> mortCurveShapeParm, Species.AuxParm<Ecoregions.AuxParm<double>> establishProbability, Species.AuxParm<Ecoregions.AuxParm<int>> maxANPP, Species.AuxParm<Ecoregions.AuxParm<double>> leafLitterDecayRate, string ageOnlyDisturbanceParms) { this.timestep = timestep; this.seedAlg = seedAlgorithm; this.minRelativeBiomass = minRelativeBiomass; this.leafLongevity = leafLongevity; this.woodyDecayRate = woodyDecayRate; this.mortCurveShapeParm = mortCurveShapeParm; this.establishProbability = establishProbability; this.maxANPP = maxANPP; this.leafLitterDecayRate = leafLitterDecayRate; this.ageOnlyDisturbanceParms = ageOnlyDisturbanceParms; }
/// <summary> /// This breeds to parents to make a new child from a species offspring has a chance of being a clone of the parent /// </summary> /// <param name="config"></param> /// <param name="species"></param> /// <returns></returns> public static Genome BreedChild(EvolutionConfig config, Species species) { Genome child; // If the specie only contains one child, the species can't crossover if (species.genomes.Count == 1) child = (Genome) species.genomes.First().Clone(); else { Genome parentA = species.genomes.ElementAt(rng.Next(species.genomes.Count)); // Non-crossover chance if (rng.NextDouble() >= config.CrossOverRate) child = (Genome) parentA.Clone(); else { // Crossover Genome parentB = species.genomes.Where(g => g != parentA).ElementAt(rng.Next(species.genomes.Count - 1)); child = new Genome(config, parentA, parentB); } } // Mutate child.Mutate(); return child; }
//--------------------------------------------------------------------- public Parameters(Ecoregions.AuxParm<Percentage>[] minRelativeBiomass, Species.AuxParm<double> leafLongevity, Species.AuxParm<double> woodyDecayRate, Species.AuxParm<double> mortCurveShapeParm, Species.AuxParm<double> leafLignin, Ecoregions.AuxParm<int> aet, ISufficientLight[] sufficientLight, Species.AuxParm<Ecoregions.AuxParm<double>> establishProbability, Species.AuxParm<Ecoregions.AuxParm<int>> maxANPP, Species.AuxParm<Ecoregions.AuxParm<int>> maxBiomass) { this.minRelativeBiomass = minRelativeBiomass; this.leafLongevity = leafLongevity; this.woodyDecayRate = woodyDecayRate; this.mortCurveShapeParm = mortCurveShapeParm; this.leafLignin = leafLignin; this.aet = aet; this.sufficientLight = sufficientLight; this.establishProbability = establishProbability; this.maxANPP = maxANPP; this.maxBiomass = maxBiomass; //this.leafLitterDecayRate = leafLitterDecayRate; }
//--------------------------------------------------------------------- public Parameters(int timestep, SeedingAlgorithms seedAlgorithm, Ecoregions.AuxParm<Percentage>[] minRelativeBiomass, Species.AuxParm<double> leafLongevity, Species.AuxParm<double> woodyDecayRate, Species.AuxParm<double> mortCurveShapeParm, Species.AuxParm<Ecoregions.AuxParm<double>> establishProbability, Species.AuxParm<Ecoregions.AuxParm<int>> maxANPP, Species.AuxParm<Ecoregions.AuxParm<double>> leafLitterDecayRate, string ageOnlyDisturbanceParms, List<ClimateChange.ParametersUpdate> climateChangeUpdates) : base(minRelativeBiomass, leafLongevity, woodyDecayRate, mortCurveShapeParm, establishProbability, maxANPP, leafLitterDecayRate) { this.timestep = timestep; this.seedAlg = seedAlgorithm; this.ageOnlyDisturbanceParms = ageOnlyDisturbanceParms; this.climateChangeUpdates = climateChangeUpdates; }
private static void DrawKey(PictureBox pb, Species species) { if (species == null) { return; } var w = pb.Width; var h = pb.Height; Bitmap bmp = new Bitmap(w, h); using (Graphics g = Graphics.FromImage(bmp)) using (var font = new Font("Microsoft Sans Serif", 8.25f)) using (var format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }) using (var pen = new Pen(Color.Black)) using (var brush = new SolidBrush(Color.Black)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; // border g.DrawRectangle(pen, 0, 0, w - 1, h - 1); // stats const int padding = 4; const int statCircleSize = PedigreeCreatureCompact.DefaultStatSize * 3 / 2; const int statRadius = statCircleSize / 2; const int radiusInnerCircle = statRadius / 7; var statLeftTopCoords = new Point(padding, padding); var center = new Point(statLeftTopCoords.X + statRadius, statLeftTopCoords.Y + statRadius); brush.Color = Color.White; g.FillEllipse(brush, statLeftTopCoords.X, statLeftTopCoords.Y, statRadius * 2, statRadius * 2); brush.Color = Color.Black; var usedStats = Enumerable.Range(0, Values.STATS_COUNT).Where(si => si != (int)StatNames.Torpidity && species.UsesStat(si)).ToArray(); var anglePerStat = 360f / usedStats.Length; var i = 0; foreach (var si in usedStats) { var angle = PedigreeCreatureCompact.AngleOffset + anglePerStat * i++; g.DrawPie(pen, statLeftTopCoords.X, statLeftTopCoords.Y, statCircleSize, statCircleSize, angle, anglePerStat); // text const int radiusPosition = statRadius * 7 / 10; var anglePosition = Math.PI * 2 / 360 * (angle + anglePerStat / 2); const int statTexSizeHalf = 15; var x = (int)Math.Round(radiusPosition * Math.Cos(anglePosition) + center.X - statTexSizeHalf); var y = (int)Math.Round(radiusPosition * Math.Sin(anglePosition) + center.Y - statTexSizeHalf); g.DrawString(Utils.StatName(si, true, species.statNames), font, brush, new RectangleF(x, y, statTexSizeHalf * 2, statTexSizeHalf * 2), format); } brush.Color = Color.Gray; g.FillEllipse(brush, center.X - radiusInnerCircle, center.Y - radiusInnerCircle, 2 * radiusInnerCircle, 2 * radiusInnerCircle); // circles const int textX = 3 * padding + 6; const int lineHeight = 15; void CircleExplanation(Color circleColor, string text, int y, int circleSize, int circleOffset = 0) { PedigreeCreatureCompact.DrawFilledCircle(g, brush, pen, circleColor, padding + circleOffset, y + lineHeight / 4 + circleOffset, circleSize); brush.Color = Color.Black; g.DrawString(text, font, brush, textX, y); } void RectangleExplanation(Color rectangleColor, string text, int y, int size) { pen.Color = rectangleColor; pen.Width = 2; g.DrawRectangle(pen, padding, y, size, size); brush.Color = Color.Black; g.DrawString(text, font, brush, textX, y); } void ArrowExplanation(List <int[]> linesList, int lineStyle, string text, int y, int size) { var yLine = y + lineHeight / 2; linesList.Add(new[] { padding, yLine, padding + size, yLine, lineStyle }); brush.Color = Color.Black; g.DrawString(text, font, brush, textX, y); } int yText = statRadius * 2 + 4 * padding; CircleExplanation(Utils.MutationMarkerColor, "mutation in stat", yText, 6); yText += lineHeight; CircleExplanation(Utils.MutationMarkerPossibleColor, "possible mutation in stat", yText, 6); yText += lineHeight; CircleExplanation(Color.Yellow, "mutation in color", yText, 4, 1); yText += lineHeight; CircleExplanation(Color.GreenYellow, "creature without mutations", yText, 6); yText += lineHeight; CircleExplanation(Utils.MutationColor, "creature mutations < limit", yText, 6); yText += lineHeight; CircleExplanation(Color.DarkRed, "creature mutations ≥ limit", yText, 6); yText += lineHeight; // rectangles RectangleExplanation(Color.DodgerBlue, "selected creature", yText, 10); yText += lineHeight; RectangleExplanation(Utils.MutationMarkerColor, "creature with mutation", yText, 10); yText += lineHeight; // arrows var lines = new[] { null, new List <int[]>(), null }; ArrowExplanation(lines[1], 1, "offspring", yText, 10); yText += lineHeight; ArrowExplanation(lines[1], 2, "stat inheritance", yText, 10); yText += lineHeight; ArrowExplanation(lines[1], 3, "stat inheritance with", yText, 10); g.DrawString("possible mutation", font, brush, textX, yText + lineHeight); DrawLines(g, lines); } pb.SetImageAndDisposeOld(bmp); }
public override int GetHashCode() { return(Species.GetHashCode()); }
protected override void Seed(MyZoo.DataContext.ZooDataBaseContext context) { Country sweden = new Country() { Name = "Sverige" }; Country russia = new Country() { Name = "Ryssland" }; Country zimbabwe = new Country() { Name = "Zimbabwe" }; Country norway = new Country() { Name = "Norge" }; DataContext.Type carnivore = new DataContext.Type() { Name = "Köttätare" }; DataContext.Type herbivore = new DataContext.Type() { Name = "Växtätare" }; DataContext.Environment ground = new DataContext.Environment() { Name = "Mark" }; DataContext.Environment tree = new DataContext.Environment() { Name = "Träd" }; DataContext.Environment water = new DataContext.Environment() { Name = "Vatten" }; Species bear = new Species() { Name = "Björn", Environment = ground, Type = carnivore }; Species amazonParrot = new Species() { Name = "Amazonpapegoja", Environment = tree, Type = herbivore }; Species seal = new Species() { Name = "Knubbsäl", Environment = water, Type = carnivore }; Animal bearMotherPascha = new Animal() { Name = "Pascha", Weight = 145, Sex = "Hona", Species = bear, Country = russia }; Animal bearFatherSture = new Animal() { Name = "Sture", Weight = 230, Sex = "Hane", Species = bear, Country = sweden }; Animal bearChildBjorne = new Animal() { Name = "Björne", Weight = 95, Sex = "Hane", Species = bear, Country = sweden }; Animal parrotMotherDoris = new Animal() { Name = "Doris", Weight = (float)1.1, Sex = "Hona", Species = amazonParrot, Country = sweden }; Animal parrotFatherGreger = new Animal() { Name = "Greger", Sex = "Hane", Weight = (float)1.5, Species = amazonParrot, Country = sweden }; Animal parrotChildSvea = new Animal() { Name = "Svea", Sex = "Hona", Weight = (float)0.5, Species = amazonParrot, Country = sweden }; Animal sealMotherBerta = new Animal() { Name = "Berta", Weight = 53, Sex = "Hona", Species = seal, Country = norway }; Animal sealFatherRoger = new Animal() { Name = "Roger", Weight = 125, Sex = "Hane", Species = seal, Country = sweden }; Animal sealChildSara = new Animal() { Name = "Sara", Weight = 35, Sex = "Hona", Species = seal, Country = sweden }; context.Families.AddOrUpdate(f => f.FamilyId, new Family() { AnimalChild = bearChildBjorne, AnimalFather = bearFatherSture, AnimalMother = bearMotherPascha }); context.Families.AddOrUpdate(f => f.FamilyId, new Family() { AnimalChild = parrotChildSvea, AnimalMother = parrotMotherDoris, AnimalFather = parrotFatherGreger }); context.Families.AddOrUpdate(f => f.FamilyId, new Family() { AnimalChild = sealChildSara, AnimalMother = sealMotherBerta, AnimalFather = sealFatherRoger }); var vetKurt = new Veterinarian() { Namn = "Kurt Wallin" }; var vetSaida = new Veterinarian() { Namn = "Saida Broberg" }; var vetKarin = new Veterinarian() { Namn = "Karin Andersson" }; var booking1Time = new DateTime(2017, 12, 13, 15, 30, 0); var booking2Time = new DateTime(2017, 11, 20, 13, 0, 0); var booking3Time = new DateTime(2017, 11, 15, 10, 30, 0); var booking1 = new Booking() { Animal = bearChildBjorne, Veterinarian = vetKurt, DateTime = booking1Time }; var booking2 = new Booking() { Animal = parrotChildSvea, Veterinarian = vetSaida, DateTime = booking2Time }; var booking3 = new Booking() { Animal = sealFatherRoger, Veterinarian = vetKarin, DateTime = booking3Time }; context.Bookings.AddOrUpdate(b => b.AnimalId, booking1, booking2, booking3 ); Diagnosis worm = new Diagnosis() { Name = "Mask", Description = "En parasit som orsakar näringsbrist och magbesvär" }; Diagnosis brokenLeg = new Diagnosis() { Name = "Brutet ben", Description = "Ett ben brutet på ett ställe. Orsakar inmobilitet och smärta." }; Medication painkiller = new Medication() { Name = "Smärtstillande medicin" }; Medication dewormingMedication = new Medication() { Name = "Avmaskningsmedel" }; //Journal bearBjorneJournal = new Journal() //{ // Animal = context.Animals.Find(1) //}; //Journal parrotSveaJournal = new Journal() //{ // Animal = context.Animals.Find(4) //}; //Journal sealRogerJournal = new Journal() //{ // Animal = context.Animals.Find(7), //}; JournalsDiagnos diagnoseJournalBjorne = new JournalsDiagnos() { Diagnosis = brokenLeg, Journal = new Journal() { Animal = bearChildBjorne }, Medications = { painkiller } }; JournalsDiagnos diagnoseJournalSara = new JournalsDiagnos() { Diagnosis = worm, Journal = new Journal() { Animal = sealChildSara }, Medications = { dewormingMedication } }; JournalsDiagnos diagnoseJournalRoger = new JournalsDiagnos() { Diagnosis = brokenLeg, Journal = new Journal() { Animal = sealFatherRoger }, Medications = { painkiller } }; context.JournalsDiagnoses.AddOrUpdate(j => j.JournalDiagnoseId, diagnoseJournalRoger, diagnoseJournalBjorne, diagnoseJournalSara ); }
private string GetSpeciesDirectory([NotNull] Species species) { return(Path.Combine(this.BaseTransformationSpeciesPath, species.Name)); }
public void setParentValues(Creature mother, Creature father) { if (mother == null && father == null) { labelMother.Text = "unknown"; labelFather.Text = "unknown"; for (int s = 0; s < values.Values.STATS_COUNT; s++) { parentStatValues[s].setValues(); } return; } Species species = mother?.Species ?? father.Species; for (int s = 0; s < values.Values.STATS_COUNT; s++) { // only display used stats and don't display torpidity bool statDisplayed = s != (int)StatNames.Torpidity && species.UsesStat(s); parentStatValues[s].Visible = statDisplayed; if (!statDisplayed) { continue; } int bestLevel = -1; int bestLevelPercent = 0; if (mother != null && father != null) { bestLevel = Math.Max(mother.levelsWild[s], father.levelsWild[s]); if (maxChartLevel > 0) { bestLevelPercent = (100 * bestLevel) / maxChartLevel; } } parentStatValues[s].setValues( mother == null ? -1 : (mother.valuesBreeding[s] * (Utils.Precision(s) == 1 ? 1 : 100)), father == null ? -1 : (father.valuesBreeding[s] * (Utils.Precision(s) == 1 ? 1 : 100)), mother != null && father != null ? (mother.valuesBreeding[s] > father.valuesBreeding[s] ? 1 : 2) : 0, bestLevel, bestLevelPercent ); } labelMother.Text = mother == null ? "unknown" : mother.name; labelFather.Text = father == null ? "unknown" : (labelMother.Width > 78 ? "\n" : "") + father.name; if (mother != null && father != null) { int minLv = 1, maxLv = 1; for (int s = 0; s < 7; s++) { if (mother.levelsWild[s] < father.levelsWild[s]) { minLv += mother.levelsWild[s]; maxLv += father.levelsWild[s]; } else { maxLv += mother.levelsWild[s]; minLv += father.levelsWild[s]; } } lbLevel.Text = $"Possible Level-Range: {minLv} - {maxLv}"; } else { lbLevel.Text = ""; } }
private static void AddSpecies(string name, Species species) => _species.Add(name, species);
public static MicrobeSpawner MakeMicrobeSpawner(Species species, CompoundCloudSystem cloudSystem, GameProperties currentGame) { return(new MicrobeSpawner(species, cloudSystem, currentGame)); }
// Update public ActionResult Update(int id) { Species selSpecies = db.Species.SqlQuery("select * from species where speciesid = @SpeciesId", new SqlParameter("@SpeciesID", id)).FirstOrDefault(); return(View(selSpecies)); }
public AgentProperties(Species species, Compound compound) { Species = species; Compound = compound; }
public SetSpeciesInCompoundProcessCommand(CompoundProcess process, Species species) { _process = process; _species = species; }
/// <summary> /// Report result of inquest. /// </summary> /// <param name="target"></param> /// <param name="species"></param> /// <returns></returns> public static string Inquested(Agent target, Species species) { string[] split = { Topic.INQUESTED.ToString(), (target != null) ? target.ToString() : "null", species.ToString() }; return WordAttachment(split); }
// overloading constructor public Animal(string name, Species species) : this() { Name = name; Type = species; }
/// <summary> /// Loads extra values-files that can add species values or modify existing ones /// </summary> public bool LoadModValues(List <string> modValueFileNames, bool showResults, out List <Mod> mods) { loadedModsHash = 0; List <Values> modifiedValues = new List <Values>(); mods = new List <Mod>(); if (modValueFileNames == null) { return(false); } CheckAndUpdateModFiles(modValueFileNames); foreach (string mf in modValueFileNames) { string filename = FileService.GetJsonPath(Path.Combine(FileService.ValuesFolder, mf)); if (TryLoadValuesFile(filename, setModFileName: true, out Values modValues)) { modifiedValues.Add(modValues); } } int speciesUpdated = 0; int speciesAdded = 0; // update data if existing foreach (Values modValues in modifiedValues) { // if mods are loaded multiple times, only keep the last mods.Remove(modValues.mod); mods.Add(modValues.mod); // species if (modValues.species != null) { foreach (Species sp in modValues.species) { if (string.IsNullOrWhiteSpace(sp.blueprintPath)) { continue; } Species originalSpecies = SpeciesByBlueprint(sp.blueprintPath); if (originalSpecies != null) { _V.species.Remove(originalSpecies); } _V.species.Add(sp); sp.Mod = modValues.mod; speciesAdded++; if (!blueprintToSpecies.ContainsKey(sp.blueprintPath)) { blueprintToSpecies.Add(sp.blueprintPath, sp); } } } // TODO support for mod colors } loadedModsHash = CreatureCollection.CalculateModListHash(mods); if (speciesUpdated == 0 && speciesAdded == 0) { return(true); // nothing changed } // sort new species OrderSpecies(); // mod-fooddata TODO _V.LoadAliases(); _V.UpdateSpeciesBlueprintDictionaries(); if (showResults) { MessageBox.Show($"The following mods were loaded:\n{string.Join(", ", modifiedValues.Select(m => m.mod.title).ToArray())}\n\n" + $"Species with changed stats: {speciesUpdated}\nSpecies added: {speciesAdded}", "Additional Values succesfully added", MessageBoxButtons.OK, MessageBoxIcon.Information); } return(true); }
public ActionResult Edit(int id = 0) { Species species = null; SpeciesEditViewModel viewModel = null; TaxonomyService _taxonomyService = new TaxonomyService(AuthenticatedUserSession.Environment); try { if (id > 0) { TempData["context"] = "Edit Species"; species = _taxonomyService.GetSpecies(id); viewModel = new SpeciesEditViewModel(); viewModel.ID = species.ID; viewModel.CurrentTaxonomySpeciesID = species.CurrentTaxonomySpeciesID; viewModel.NomenNumber = species.NomenNumber; viewModel.IsSpecificHybrid = species.IsSpecificHybrid; viewModel.SpeciesName = species.SpeciesName; viewModel.Name = species.Name; viewModel.IsAcceptedName = species.IsAcceptedName; viewModel.Authority = species.Authority; viewModel.IsSubSpecificHybrid = species.IsSubSpecificHybrid; viewModel.SubSpeciesName = species.SubSpeciesName; viewModel.SubSpeciesAuthority = species.SubSpeciesAuthority; viewModel.IsVarietalHybrid = species.IsVarietalHybrid; viewModel.VarietyName = species.VarietyName; viewModel.VarietyAuthority = species.VarietyAuthority; viewModel.FormaName = species.FormaName; viewModel.FormaAuthority = species.FormaAuthority; viewModel.FormaRankType = species.FormaRankType; viewModel.GenusID = species.GenusID; viewModel.GenusName = species.GenusName; viewModel.Protologue = species.Protologue; viewModel.NameAuthority = species.NameAuthority; viewModel.GenusID = species.GenusID; viewModel.GenusName = species.GenusName; viewModel.Authority = species.Authority; viewModel.CreatedDate = species.CreatedDate; viewModel.CreatedByCooperatorID = species.CreatedByCooperatorID; viewModel.CreatedByCooperatorName = species.CreatedByCooperatorName; viewModel.ModifiedDate = species.ModifiedDate; viewModel.ModifiedByCooperatorID = species.ModifiedByCooperatorID; viewModel.ModifiedByCooperatorName = species.ModifiedByCooperatorName; viewModel.Note = species.Note; viewModel.Citations = species.Citations; viewModel.CommonNames = species.CommonNames; //viewModel.Usages = species.Usages; //viewModel.RegulationMappings = species.RegulationMappings; } else { TempData["context"] = "Add Species"; viewModel = new SpeciesEditViewModel(); } } catch (Exception ex) { Log.Error(ex, ex.Message + ex.StackTrace); return(RedirectToAction("InternalServerError", "Error")); } return(View(BASE_PATH + "/Edit.cshtml", viewModel)); }
public abstract void PokedexInsertSpecies(Species s);
public SpeciesPopulation DefaultPopulationFor(Species species) { return(species.Populations.FindByName(_userSettings.DefaultPopulation) ?? species.Populations.ElementAt(0)); }
public static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: printUnits filename"); return(1); } string filename = args[0]; SBMLDocument document = libsbml.readSBML(filename); if (document.getNumErrors() > 0) { Console.Error.WriteLine("Encountered the following SBML errors:"); document.printErrors(); return(1); } Model model = document.getModel(); if (model == null) { Console.WriteLine("No model present."); return(1); } int i, j; for (i = 0; i < model.getNumSpecies(); i++) { Species s = model.getSpecies(i); Console.WriteLine("Species " + i + ": " + UnitDefinition.printUnits(s.getDerivedUnitDefinition())); } for (i = 0; i < model.getNumCompartments(); i++) { Compartment c = model.getCompartment(i); Console.WriteLine("Compartment " + i + ": " + UnitDefinition.printUnits(c.getDerivedUnitDefinition())) ; } for (i = 0; i < model.getNumParameters(); i++) { Parameter p = model.getParameter(i); Console.WriteLine("Parameter " + i + ": " + UnitDefinition.printUnits(p.getDerivedUnitDefinition())) ; } for (i = 0; i < model.getNumInitialAssignments(); i++) { InitialAssignment ia = model.getInitialAssignment(i); Console.WriteLine("InitialAssignment " + i + ": " + UnitDefinition.printUnits(ia.getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((ia.containsUndeclaredUnits() ? "yes\n" : "no\n")); } for (i = 0; i < model.getNumEvents(); i++) { Event e = model.getEvent(i); Console.WriteLine("Event " + i + ": "); if (e.isSetDelay()) { Console.WriteLine("Delay: " + UnitDefinition.printUnits(e.getDelay().getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((e.getDelay().containsUndeclaredUnits() ? "yes\n" : "no\n")); } for (j = 0; j < e.getNumEventAssignments(); j++) { EventAssignment ea = e.getEventAssignment(j); Console.WriteLine("EventAssignment " + j + ": " + UnitDefinition.printUnits(ea.getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((ea.containsUndeclaredUnits() ? "yes\n" : "no\n")); } } for (i = 0; i < model.getNumReactions(); i++) { Reaction r = model.getReaction(i); Console.WriteLine("Reaction " + i + ": "); if (r.isSetKineticLaw()) { Console.WriteLine("Kinetic Law: " + UnitDefinition.printUnits(r.getKineticLaw().getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((r.getKineticLaw().containsUndeclaredUnits() ? "yes\n" : "no\n")); } for (j = 0; j < r.getNumReactants(); j++) { SpeciesReference sr = r.getReactant(j); if (sr.isSetStoichiometryMath()) { Console.WriteLine("Reactant stoichiometryMath" + j + ": " + UnitDefinition.printUnits(sr.getStoichiometryMath().getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((sr.getStoichiometryMath().containsUndeclaredUnits() ? "yes\n" : "no\n")); } } for (j = 0; j < r.getNumProducts(); j++) { SpeciesReference sr = r.getProduct(j); if (sr.isSetStoichiometryMath()) { Console.WriteLine("Product stoichiometryMath" + j + ": " + UnitDefinition.printUnits(sr.getStoichiometryMath().getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((sr.getStoichiometryMath().containsUndeclaredUnits() ? "yes\n" : "no\n")); } } } for (i = 0; i < model.getNumRules(); i++) { Rule r = model.getRule(i); Console.WriteLine("Rule " + i + ": " + UnitDefinition.printUnits(r.getDerivedUnitDefinition())); Console.WriteLine(" undeclared units: "); Console.WriteLine((r.containsUndeclaredUnits() ? "yes\n" : "no\n")); } return(0); }
/// <summary> /// Set the stats of a creature to the inputs. /// </summary> /// <param name="statValues"></param> /// <param name="levelsWild"></param> /// <param name="levelsDom"></param> /// <param name="totalLevel"></param> /// <param name="TE">Taming Effectiveness</param> /// <param name="IB">Imprinting Bonus of the creature</param> /// <param name="tamed"></param> /// <param name="bred"></param> public void SetCreatureValues(double[] statValues, int[] levelsWild, int[] levelsDom, int totalLevel, double TE, double IB, bool tamed, bool bred, Species species) { int level = 1; for (int s = 0; s < Values.STATS_COUNT; s++) { _statControls[s].BeginUpdate(); } SetSpecies(species); if (statValues != null) { for (int s = 0; s < Values.STATS_COUNT; s++) { _statControls[s].StatValue = statValues[s]; } } if (levelsWild != null) { for (int s = 0; s < Values.STATS_COUNT; s++) { _statControls[s].LevelWild = levelsWild[s]; } level += levelsWild[(int)StatNames.Torpidity]; } if (levelsDom != null) { for (int s = 0; s < Values.STATS_COUNT; s++) { _statControls[s].LevelDom = levelsDom[s]; level += levelsDom[s]; } } SetTE(TE); SetIB(IB); if (tamed) { rbTamed.Checked = true; } else if (bred) { rbBred.Checked = true; } else { rbWild.Checked = true; } for (int s = 0; s < Values.STATS_COUNT; s++) { _statControls[s].EndUpdate(true); } nudCreatureLevel.Value = level > totalLevel ? level : totalLevel; CheckIfMultipliersAreEqualToSettings(); }
/// <summary> /// Removes a species from this patch /// </summary> /// <returns>True when a species was removed</returns> public bool RemoveSpecies(Species species) { return(SpeciesInPatch.Remove(species)); }
public static int Main(string[] args) { if (args.Length != 2) { Console.Write(Environment.NewLine + "Usage: unsetAnnotation <input-filename> <output-filename>" + Environment.NewLine + Environment.NewLine); return 1; } int i, j; string filename = args[0]; SBMLDocument document; document = libsbml.readSBML(filename); int errors = (int)document.getNumErrors(); if (errors > 0) { document.printErrors(); return errors; } Model m = document.getModel(); m.unsetAnnotation(); for (i = 0; i < m.getNumReactions(); i++) { Reaction re = m.getReaction(i); re.unsetAnnotation(); for (j = 0; j < re.getNumReactants(); j++) { SpeciesReference rt = re.getReactant(j); rt.unsetAnnotation(); } for (j = 0; j < re.getNumProducts(); j++) { SpeciesReference rt = re.getProduct(j); rt.unsetAnnotation(); } for (j = 0; j < re.getNumModifiers(); j++) { ModifierSpeciesReference md = re.getModifier(j); md.unsetAnnotation(); } if (re.isSetKineticLaw()) { KineticLaw kl = re.getKineticLaw(); kl.unsetAnnotation(); for (j = 0; j < kl.getNumParameters(); j++) { Parameter pa = kl.getParameter(j); pa.unsetAnnotation(); } } } for (i = 0; i < m.getNumSpecies(); i++) { Species sp = m.getSpecies(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumCompartments(); i++) { Compartment sp = m.getCompartment(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumFunctionDefinitions(); i++) { FunctionDefinition sp = m.getFunctionDefinition(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumUnitDefinitions(); i++) { UnitDefinition sp = m.getUnitDefinition(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumParameters(); i++) { Parameter sp = m.getParameter(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumRules(); i++) { Rule sp = m.getRule(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumInitialAssignments(); i++) { InitialAssignment sp = m.getInitialAssignment(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumEvents(); i++) { Event sp = m.getEvent(i); sp.unsetAnnotation(); for (j = 0; j < sp.getNumEventAssignments(); j++) { EventAssignment ea = sp.getEventAssignment(j); ea.unsetAnnotation(); } } for (i = 0; i < m.getNumSpeciesTypes(); i++) { SpeciesType sp = m.getSpeciesType(i); sp.unsetAnnotation(); } for (i = 0; i < m.getNumConstraints(); i++) { Constraint sp = m.getConstraint(i); sp.unsetAnnotation(); } libsbml.writeSBML(document, args[1]); return errors; }
private void btnAddAnimalsSelected_Click(object sender, EventArgs e) { try { int amount = int.Parse(txtAnimalAmount.Text); Species specie = (Species)cbxSpecies.SelectedItem; int counter = animals.Where(ani => ani.Species.Equals(specie)).Count(); if (counter % 10 == 0) { AnimalsSelected assd = new AnimalsSelected(); assd.Animaal = specie; assd.AnimalAmount = amount; AddingAnimal adding = new AddingAnimal(new List <AnimalsSelected>() { assd }, ID); MessageObject message = new MessageObject(assd.BinarySerialization(), 4, 3, 2); } else { //Cages available var cageIds = from loc in locations where !(loc.Cage.Equals(null)) select loc; foreach (Location item in cageIds) { tempLoc.Add(item); } int counters = 0; Species[] space = new Species[tempLoc.Count]; foreach (Location item in tempLoc) { foreach (Animal item2 in animals) { if (item.ID == item2.LocationID) { space[counters] = item2.Species; } } counters++; } for (int i = 0; i < space.Length; i++) { if (space[i].Equals(specie)) { int animalAmount = 0; foreach (Animal item in animals) { if (item.LocationID == tempLoc[i].ID) { animalAmount++; } } for (int j = 0; j < amount + 1; j++) { if (animalAmount < 10) { //Insert Singular Animal Here ArrayList AnimalToAdd = new ArrayList(); AnimalToAdd.Add(specie.AnimalName); //Generate Gender Random rnd = new Random(); int genderChance = rnd.Next(0, 7); string gender = ""; if (genderChance <= 3) { gender = "Female"; AnimalToAdd.Add(gender); } else { gender = "Male"; AnimalToAdd.Add(gender); } int age = rnd.Next(0, 2556); string mate = ""; if ((gender.Equals("Male") || gender.Equals("Female")) && age > 474) { mate = "Ready"; } else { mate = "Not Ready"; } AnimalToAdd.Add(mate); AnimalToAdd.Add(age); double eatTime = 2; if (age < 365 || age > 2920) { eatTime += 1.5; } AnimalToAdd.Add(eatTime); Animal ani = new Animal(gender, mate, eatTime, specie, age, tempLoc[i].ID); animals.Add(ani); MessageObject message = new MessageObject(ani.BinarySerialization(), 6, 3, 2); co.SendData(message); animalAmount++; amount--; } } } } } } catch (Exception) { MessageBox.Show("Please enter a number for Amount!"); } }
public async Task AddAsync(Species species) { await _context.Species.AddAsync(species); await _context.SaveChangesAsync(); }
private void Start() { humanSpecies = GameManager.HumanPlayer.species; statsTexts [0].text = humanSpecies.ToString(); statsImages [0].sprite = HUD.speciesPopSpriteDick [humanSpecies]; // Adjust Species Legend Dictionary <Species, Tuple <Image, Text> > legendDick = new Dictionary <Species, Tuple <Image, Text> > (); for (int i = 0; i < Pop_Dynamics_Model.allSpeciesArray.Length; i++) { legendImages[i].color = Pop_Dynamics_Model.speciesColorDick[Pop_Dynamics_Model.allSpeciesArray[i]]; legendTexts[i].text = Pop_Dynamics_Model.allSpeciesArray[i].ToString(); legendDick.Add(Pop_Dynamics_Model.allSpeciesArray[i], new Tuple <Image, Text> (legendImages[i], legendTexts[i])); } foreach (Species species in legendDick.Keys) { if (!Pop_Dynamics_Model.speciesList.Contains(species)) { legendDick[species].thing1.gameObject.SetActive(false); legendImages.Remove(legendDick[species].thing1); legendDick[species].thing2.gameObject.SetActive(false); legendTexts.Remove(legendDick[species].thing2); legendDick[Species.Wolves].thing1.rectTransform.anchorMax = legendDick[species].thing1.rectTransform.anchorMax; legendDick[Species.Wolves].thing1.rectTransform.anchorMin = legendDick[species].thing1.rectTransform.anchorMin; legendDick[Species.Wolves].thing2.rectTransform.anchorMax = legendDick[species].thing2.rectTransform.anchorMax; legendDick[Species.Wolves].thing2.rectTransform.anchorMin = legendDick[species].thing2.rectTransform.anchorMin; } } // Consumption consumptionTextDick.Add(Species.Grass, statsValuesList[statsValuesList.Count - 2]); consumptionFloatDick.Add(Species.Grass, Pop_Dynamics_Model.eatRatesDick [humanSpecies] [Species.Grass]); consumptionTextDick [Species.Grass].text = consumptionFloatDick [Species.Grass].ToString("0.###"); if (humanSpecies == Species.Sheep) { // carrot consumption shit is at the end of both statsImages and statsValuesList statsImages.RemoveAt(statsImages.Count - 1); statsImages[statsImages.Count - 1].rectTransform.anchorMin = new Vector2(0.2f, statsImages[statsImages.Count - 1].rectTransform.anchorMin.y); statsImages[statsImages.Count - 1].rectTransform.anchorMax = new Vector2(0.3f, statsImages[statsImages.Count - 1].rectTransform.anchorMax.y); statsValuesList.RemoveAt(statsValuesList.Count - 1); statsValuesList[statsValuesList.Count - 1].rectTransform.anchorMin = new Vector2(0.4f, statsValuesList[statsValuesList.Count - 1].rectTransform.anchorMin.y); statsValuesList[statsValuesList.Count - 1].rectTransform.anchorMax = new Vector2(0.6f, statsValuesList[statsValuesList.Count - 1].rectTransform.anchorMax.y); } else { consumptionTextDick.Add(Species.Carrots, statsValuesList[statsValuesList.Count - 1]); consumptionFloatDick.Add(Species.Carrots, Pop_Dynamics_Model.eatRatesDick [humanSpecies] [Species.Carrots]); consumptionTextDick [Species.Carrots].text = consumptionFloatDick [Species.Carrots].ToString("0.###"); } // Stats in Pop_Dynmaics_Model.modelStatsDick humanPopulation = (int)Pop_Dynamics_Model.modelStatsDick [humanSpecies] [StatsType.Population]; speciesValuesTextDick.Add(StatsType.Population, statsValuesList[0]); speciesValuesTextDick[StatsType.Population].text = humanPopulation.ToString(); for (int i = 0; i < statsOrderArray.Length; i++) { speciesValuesFloatDick.Add(statsOrderArray[i], Pop_Dynamics_Model.modelStatsDick [humanSpecies][statsOrderArray[i]]); speciesValuesTextDick.Add(statsOrderArray[i], statsValuesList[i + 1]); speciesValuesTextDick[statsOrderArray[i]].text = speciesValuesFloatDick[statsOrderArray[i]].ToString("0.###"); } // Predation wolfPredation = Pop_Dynamics_Model.eatRatesDick [Species.Wolves] [humanSpecies]; speciesValuesTextDick.Add(StatsType.EatRates, statsValuesList [6]); speciesValuesTextDick [StatsType.EatRates].text = wolfPredation.ToString("0.###"); }
/// <summary>Sets the species of the player.</summary> /// <param name="species">The species the player shall have</param> /// <param name="strength">The computer's strength (with default param mainly if the species is Human)</param> public void SetSpecies(Species species, ComputerStrength strength = ComputerStrength.Medium) { _species = species; //DEBUG Logging.Inst.LogMessage(this.ToString() + ": Species set to " + _species + ".\n"); if (_species == Species.Computer) { _computerStrength = strength; //DEBUG Logging.Inst.LogMessage(this.ToString() + ": Strength set to " + _computerStrength + ".\n"); } }
public async Task <PK8?> ReadOwPokemon(Species target, uint startoffset, byte[]?mondata, SAV8 TrainerData, CancellationToken token) { byte[]? data = null; Species species = 0; uint offset = startoffset; int i = 0; if (target != (Species)0) { do { data = await Connection.ReadBytesAsync(offset, 56, token).ConfigureAwait(false); species = (Species)BitConverter.ToUInt16(data.Slice(0, 2), 0); offset += 192; i++; } while (target != 0 && species != 0 && target != species && i <= 40); if (i > 40) { data = null; } } else if (mondata != null) { data = mondata; species = (Species)BitConverter.ToUInt16(data.Slice(0, 2), 0); } if (data != null && data[20] == 1) { PK8 pk = new PK8 { Species = (int)species, Form = data[2], CurrentLevel = data[4], Met_Level = data[4], Gender = (data[10] == 1) ? 0 : 1, OT_Name = TrainerData.OT, TID = TrainerData.TID, SID = TrainerData.SID, TrainerID7 = TrainerData.TrainerID7, TrainerSID7 = TrainerData.TrainerSID7, OT_Gender = TrainerData.Gender, HT_Name = TrainerData.OT, HT_Gender = TrainerData.Gender, Move1 = BitConverter.ToUInt16(data.Slice(48, 2), 0), Move2 = BitConverter.ToUInt16(data.Slice(50, 2), 0), Move3 = BitConverter.ToUInt16(data.Slice(52, 2), 0), Move4 = BitConverter.ToUInt16(data.Slice(54, 2), 0), Version = 44, }; pk.SetNature(data[8]); pk.SetAbility(data[12] - 1); if (data[22] != 255) { pk.SetRibbonIndex((RibbonIndex)data[22]); } if (!pk.IsGenderValid()) { pk.Gender = 2; } if (data[14] == 1) { pk.HeldItem = data[16]; } Shiny shinyness = (Shiny)(data[6] + 1); int ivs = data[18]; uint seed = BitConverter.ToUInt32(data.Slice(24, 4), 0); pk = OverworldSWSHRNG.CalculateFromSeed(pk, shinyness, ivs, seed); return(pk); } else { return(null); } }
// TODO: this is likely a huge cause of lag. Would be nice to be able // to spawn these so that only one per tick is spawned. public static IEnumerable <Microbe> SpawnBacteriaColony(Species species, Vector3 location, Node worldRoot, PackedScene microbeScene, CompoundCloudSystem cloudSystem, GameProperties currentGame, Random random) { var curSpawn = new Vector3(random.Next(1, 8), 0, random.Next(1, 8)); // Three kinds of colonies are supported, line colonies and clump colonies and Networks if (random.Next(0, 5) < 2) { // Clump for (int i = 0; i < random.Next(Constants.MIN_BACTERIAL_COLONY_SIZE, Constants.MAX_BACTERIAL_COLONY_SIZE + 1); i++) { // Dont spawn them on top of each other because it // causes them to bounce around and lag yield return(SpawnMicrobe(species, location + curSpawn, worldRoot, microbeScene, true, cloudSystem, currentGame)); curSpawn = curSpawn + new Vector3(random.Next(-7, 8), 0, random.Next(-7, 8)); } } else if (random.Next(0, 31) > 2) { // Line // Allow for many types of line // (I combined the lineX and lineZ here because they have the same values) var line = random.Next(-5, 6) + random.Next(-5, 6); for (int i = 0; i < random.Next(Constants.MIN_BACTERIAL_LINE_SIZE, Constants.MAX_BACTERIAL_LINE_SIZE + 1); i++) { // Dont spawn them on top of each other because it // Causes them to bounce around and lag yield return(SpawnMicrobe(species, location + curSpawn, worldRoot, microbeScene, true, cloudSystem, currentGame)); curSpawn = curSpawn + new Vector3(line + random.Next(-2, 3), 0, line + random.Next(-2, 3)); } } else { // Network // Allows for "jungles of cyanobacteria" // Network is extremely rare // To prevent bacteria being spawned on top of each other var vertical = false; var colony = new ColonySpawnInfo { Horizontal = false, Random = random, Species = species, CloudSystem = cloudSystem, CurrentGame = currentGame, CurSpawn = curSpawn, MicrobeScene = microbeScene, WorldRoot = worldRoot, }; for (int i = 0; i < random.Next(Constants.MIN_BACTERIAL_COLONY_SIZE, Constants.MAX_BACTERIAL_COLONY_SIZE + 1); i++) { if (random.Next(0, 5) < 2 && !colony.Horizontal) { colony.Horizontal = true; vertical = false; foreach (var microbe in MicrobeColonySpawnHelper(colony, location)) { yield return(microbe); } } else if (random.Next(0, 5) < 2 && !vertical) { colony.Horizontal = false; vertical = true; foreach (var microbe in MicrobeColonySpawnHelper(colony, location)) { yield return(microbe); } } else if (random.Next(0, 5) < 2 && !colony.Horizontal) { colony.Horizontal = true; vertical = false; foreach (var microbe in MicrobeColonySpawnHelper(colony, location)) { yield return(microbe); } } else if (random.Next(0, 5) < 2 && !vertical) { colony.Horizontal = false; vertical = true; foreach (var microbe in MicrobeColonySpawnHelper(colony, location)) { yield return(microbe); } } else { // Diagonal colony.Horizontal = false; vertical = false; foreach (var microbe in MicrobeColonySpawnHelper(colony, location)) { yield return(microbe); } } } } }
public GameInfoToSend GetGameInfoToSend(Agent agent) { GameData today = this; GameInfoToSend gi = new GameInfoToSend(); int day = today.Day; if (agent != null) { gi.Agent = agent.AgentIdx; } GameData yesterday = today.DayBefore; if (yesterday != null) { Agent executed = yesterday.Executed; if (executed != null) { gi.ExecutedAgent = executed.AgentIdx; } Agent attacked = yesterday.Attacked; if (attacked != null) { gi.AttackedAgent = attacked.AgentIdx; } if (gameSetting.VoteVisible) { List <VoteToSend> voteList = new List <VoteToSend>(); foreach (Vote vote in yesterday.VoteList) { voteList.Add(new VoteToSend(vote)); } gi.VoteList = voteList; } if (agent != null && (today.GetRole(agent) == Role.MEDIUM && executed != null)) { Species result = ((Role)yesterday.GetRole(executed)).GetSpecies(); gi.MediumResult = new JudgeToSend(new Judge(day, agent, executed, result)); } if (agent == null || today.GetRole(agent) == Role.SEER) { Judge divine = yesterday.Divine; if (divine != null && divine.Target != null) { Species result = ((Role)yesterday.GetRole(divine.Target)).GetSpecies(); gi.DivineResult = new JudgeToSend(new Judge(day, divine.Agent, divine.Target, result)); } } if (agent == null || today.GetRole(agent) == Role.WEREWOLF) { List <VoteToSend> attackVoteList = new List <VoteToSend>(); foreach (Vote vote in yesterday.AttackVoteList) { attackVoteList.Add(new VoteToSend(vote)); } gi.AttackVoteList = attackVoteList; } if (agent == null || today.GetRole(agent) == Role.BODYGUARD) { Guard guard = yesterday.Guard; if (guard != null) { gi.GuardedAgent = guard.Target.AgentIdx; } } } List <TalkToSend> talkList = new List <TalkToSend>(); foreach (Talk talk in today.TalkList) { talkList.Add(new TalkToSend(talk)); } gi.TalkList = talkList; Dictionary <int, string> statusMap = new Dictionary <int, string>(); foreach (Agent a in agentStatusMap.Keys) { statusMap[a.AgentIdx] = agentStatusMap[a].ToString(); } gi.StatusMap = statusMap; Dictionary <int, string> roleMap = new Dictionary <int, string>(); Role?role = (Role?)agentRoleMap[agent]; if (Role.WEREWOLF == role || agent == null) { List <TalkToSend> whisperList = new List <TalkToSend>(); foreach (Talk talk in today.WhisperList) { whisperList.Add(new TalkToSend(talk)); } gi.WhisperList = whisperList; } if (role != null) { roleMap[agent.AgentIdx] = role.ToString(); if (today.GetRole(agent) == Role.WEREWOLF) { foreach (Agent target in today.AgentList) { if (today.GetRole(target) == Role.WEREWOLF) { roleMap[target.AgentIdx] = Role.WEREWOLF.ToString(); } } } if (today.GetRole(agent) == Role.FREEMASON) { foreach (Agent target in today.AgentList) { if (today.GetRole(target) == Role.FREEMASON) { roleMap[target.AgentIdx] = Role.FREEMASON.ToString(); } } } } gi.RoleMap = roleMap; gi.Day = day; return(gi); }
public bool startTurn() { iteration++; int count = 0; count = Client.getMappableCount(connection); mappables = new Mappable[count]; for(int i = 0; i < count; i++) { mappables[i] = new Mappable(Client.getMappable(connection, i)); } count = Client.getTileCount(connection); tiles = new Tile[count]; for(int i = 0; i < count; i++) { tiles[i] = new Tile(Client.getTile(connection, i)); } count = Client.getSpeciesCount(connection); speciesList = new Species[count]; for(int i = 0; i < count; i++) { speciesList[i] = new Species(Client.getSpecies(connection, i)); } count = Client.getFishCount(connection); fishes = new Fish[count]; for(int i = 0; i < count; i++) { fishes[i] = new Fish(Client.getFish(connection, i)); } count = Client.getPlayerCount(connection); players = new Player[count]; for(int i = 0; i < count; i++) { players[i] = new Player(Client.getPlayer(connection, i)); } if(!initialized) { initialized = true; init(); } return run(); }
private void btnRunSim_Click(object sender, EventArgs e) { btnOpenMenu.Visible = true; openMenu = new Thread(() => { for (int i = 0; i >= -190; i = i - 3) { moveMenu(i, 0, pnlMenu); Thread.Sleep(2); } }); openMenu.Start(); if (!simRunning) { simRunning = true; btnRunSim.Text = "Running..."; lstActions.Items.Clear(); #region species var cageIds = from loc in locations where !(loc.Cage.Equals(null)) select loc; List <Location> tempLoc = new List <Location>(); foreach (Location item in cageIds) { tempLoc.Add(item); } int counters = 0; Species[] spacess = new Species[tempLoc.Count]; int counting = 0; foreach (Location item in tempLoc) { foreach (Animal item2 in animals) { if (item.ID == item2.LocationID && (!spacess.Contains(item2.Species))) { spacess[counting] = item2.Species; counting++; } } counters++; } Species[] space = new Species[counting]; for (int i = 0; i < counting; i++) { space[i] = spacess[i]; } double[] slowestAnimalEat = new double[counting]; for (int i = 0; i < slowestAnimalEat.Length; i++) { foreach (Animal item in animals) { if (item.Species.Equals(species[i]) && item.EatingTime > slowestAnimalEat[i]) { slowestAnimalEat[i] = item.EatingTime; } } } #endregion Thread runSim = new Thread(() => { addToActionsLst("Running Simulation..."); addToActionsLst("All Gates Opened..."); #region sort for (int pass = 1; pass <= space.Length - 2; pass++) { for (int i = 0; i <= space.Length - 2; i++) { if (slowestAnimalEat[i] > slowestAnimalEat[i + 1]) { double temp = slowestAnimalEat[i + 1]; Species spec = space[i + 1]; slowestAnimalEat[i + 1] = slowestAnimalEat[i]; space[i + 1] = space[i]; slowestAnimalEat[i] = temp; space[i] = spec; } } } #endregion for (int i = 0; i < space.Length; i++) { addToActionsLst(""); for (int j = 0; j < space.Length; j++) { if (i == j) { addToActionsLst(space[j].AnimalName + "s are walking to the Feeding Area"); } else { addToActionsLst(space[j].AnimalName + "s have been diverted"); } } Thread.Sleep((int)((10 - space[i].Speed) * 1000)); addToActionsLst(""); addToActionsLst(space[i].AnimalName + "s are eating"); Thread.Sleep((int)slowestAnimalEat[i] * 2000); addToActionsLst(""); addToActionsLst(space[i].AnimalName + "s are walking back"); Thread.Sleep((int)((10 - space[i].Speed) * 1000)); } addToActionsLst(""); addToActionsLst("All animals have eaten and are back in their respective Cages"); addToActionsLst(""); addToActionsLst("...All gates Closed"); simRunning = false; // btnRunSim.Text = "Run Simulation"; }); runSim.Start(); } }
public async Task HandleAsync(CreateSpeciesCommand command) { var species = new Species(command.Name, command.AnimalClass, command.ConsumeType); await _repository.AddSpecies(species); }
public static int Main(string[] args) { if (args.Length != 1) { Console.Write(Environment.NewLine + "Usage: printAnnotation filename" + Environment.NewLine + Environment.NewLine); return(1); } int i, j; string filename = args[0]; SBMLDocument document; document = libsbml.readSBML(filename); int errors = (int)document.getNumErrors(); Console.Write(Environment.NewLine); Console.Write("filename: " + filename + Environment.NewLine); Console.Write(Environment.NewLine); if (errors > 0) { document.printErrors(); return(errors); } /* Model */ Model m = document.getModel(); printAnnotation(m); for (i = 0; i < m.getNumReactions(); i++) { Reaction re = m.getReaction(i); printAnnotation(re); /* SpeciesReference (Reacatant) */ for (j = 0; j < re.getNumReactants(); j++) { SpeciesReference rt = re.getReactant(j); if (rt.isSetAnnotation()) { Console.Write(" "); } printAnnotation(rt, (rt.isSetSpecies() ? rt.getSpecies() : "")); } /* SpeciesReference (Product) */ for (j = 0; j < re.getNumProducts(); j++) { SpeciesReference rt = re.getProduct(j); if (rt.isSetAnnotation()) { Console.Write(" "); } printAnnotation(rt, (rt.isSetSpecies() ? rt.getSpecies() : "")); } /* ModifierSpeciesReference (Modifiers) */ for (j = 0; j < re.getNumModifiers(); j++) { ModifierSpeciesReference md = re.getModifier(j); if (md.isSetAnnotation()) { Console.Write(" "); } printAnnotation(md, (md.isSetSpecies() ? md.getSpecies() : "")); } /* KineticLaw */ if (re.isSetKineticLaw()) { KineticLaw kl = re.getKineticLaw(); if (kl.isSetAnnotation()) { Console.Write(" "); } printAnnotation(kl); /* Parameter */ for (j = 0; j < kl.getNumParameters(); j++) { Parameter pa = kl.getParameter(j); if (pa.isSetAnnotation()) { Console.Write(" "); } printAnnotation(pa); } } } /* Species */ for (i = 0; i < m.getNumSpecies(); i++) { Species sp = m.getSpecies(i); printAnnotation(sp); } /* Compartments */ for (i = 0; i < m.getNumCompartments(); i++) { Compartment sp = m.getCompartment(i); printAnnotation(sp); } /* FunctionDefinition */ for (i = 0; i < m.getNumFunctionDefinitions(); i++) { FunctionDefinition sp = m.getFunctionDefinition(i); printAnnotation(sp); } /* UnitDefinition */ for (i = 0; i < m.getNumUnitDefinitions(); i++) { UnitDefinition sp = m.getUnitDefinition(i); printAnnotation(sp); } /* Parameter */ for (i = 0; i < m.getNumParameters(); i++) { Parameter sp = m.getParameter(i); printAnnotation(sp); } /* Rule */ for (i = 0; i < m.getNumRules(); i++) { Rule sp = m.getRule(i); printAnnotation(sp); } /* InitialAssignment */ for (i = 0; i < m.getNumInitialAssignments(); i++) { InitialAssignment sp = m.getInitialAssignment(i); printAnnotation(sp); } /* Event */ for (i = 0; i < m.getNumEvents(); i++) { Event sp = m.getEvent(i); printAnnotation(sp); /* Trigger */ if (sp.isSetTrigger()) { Trigger tg = sp.getTrigger(); if (tg.isSetAnnotation()) { Console.Write(" "); } printAnnotation(tg); } /* Delay */ if (sp.isSetDelay()) { Delay dl = sp.getDelay(); if (dl.isSetAnnotation()) { Console.Write(" "); } printAnnotation(dl); } /* EventAssignment */ for (j = 0; j < sp.getNumEventAssignments(); j++) { EventAssignment ea = sp.getEventAssignment(j); if (ea.isSetAnnotation()) { Console.Write(" "); } printAnnotation(ea); } } /* SpeciesType */ for (i = 0; i < m.getNumSpeciesTypes(); i++) { SpeciesType sp = m.getSpeciesType(i); printAnnotation(sp); } /* Constraints */ for (i = 0; i < m.getNumConstraints(); i++) { Constraint sp = m.getConstraint(i); printAnnotation(sp); } return(errors); }
/// <summary> /// Report result of divine. /// </summary> /// <param name="target"></param> /// <param name="species"></param> /// <returns></returns> public static string Divined(Agent target, Species species) { string[] split = { Topic.DIVINED.ToString(), (target != null) ? target.ToString() : "null", species.ToString() }; return WordAttachment(split); }
public Task Add(Species species) { throw new NotImplementedException(); }
public void Attach(Species model) { RunInTransaction(session => session.SaveOrUpdate(model)); }
public PartSpeciesStruct(PartType _type, Species _species) { type = _type; species = _species; }