Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public void StringConstructor_Should_Ignore_Whitespace_At_Start_And_End()
        {
            var generation = new Generation("  -X-  ", 1, 3);

            Assert.Equal(1, generation.TotalAlive);
            Assert.True(generation.IsAlive(1, 0));
        }
Exemplo n.º 2
0
        public void StringConstructor_Should_Handle_Multiple_Rows()
        {
            var generation = new Generation("X--X--X--", 3, 3);

            Assert.Equal(3, generation.TotalAlive);
            Assert.True(generation.IsAlive(0, 0) && generation.IsAlive(0, 1) && generation.IsAlive(0, 2));
        }
Exemplo n.º 3
0
 public void StartPuzzle(Generation generation)
 {
     generationPrefab = generation;
     ((Generation)Instantiate(generationPrefab,puzzleSpawnLocation[genIndex++], Quaternion.identity)).order = generationCount++;
     ((Generation)Instantiate(generationPrefab,puzzleSpawnLocation[genIndex++], Quaternion.identity)).order = generationCount++;
     ((Generation)Instantiate(generationPrefab,puzzleSpawnLocation[genIndex++], Quaternion.identity)).order = generationCount++;
 }
Exemplo n.º 4
0
        public void ProcessOscillatorTest()
        {
            Generation<SimpleCell> seedGeneration = new Generation<SimpleCell>(5, 5);
            //setup seed
            //Blinker (period 2) - Oscillator
            seedGeneration.Cells[2][1].IsAlive = true;
            seedGeneration.Cells[2][2].IsAlive = true;
            seedGeneration.Cells[2][3].IsAlive = true;

            var engine = new Engine<SimpleCell>(seedGeneration, 2);
            engine.DontSleep = true;
            engine.Process(Help);

            Assert.AreEqual(3, _testRuns.Count);

            var run0 = _testRuns[0]; //this is the seed
            Assert.IsTrue(run0.Cells[2][1].IsAlive);
            Assert.IsTrue(run0.Cells[2][2].IsAlive);
            Assert.IsTrue(run0.Cells[2][3].IsAlive);

            var run1 = _testRuns[1];

            Assert.IsFalse(run1.Cells[0][0].IsAlive);
            Assert.IsFalse(run1.Cells[0][1].IsAlive);
            Assert.IsFalse(run1.Cells[0][2].IsAlive);
            Assert.IsFalse(run1.Cells[0][3].IsAlive);
            Assert.IsFalse(run1.Cells[0][4].IsAlive);

            Assert.IsFalse(run1.Cells[1][0].IsAlive);
            Assert.IsFalse(run1.Cells[1][1].IsAlive);
            Assert.IsTrue(run1.Cells[1][2].IsAlive);
            Assert.IsFalse(run1.Cells[1][3].IsAlive);
            Assert.IsFalse(run1.Cells[1][4].IsAlive);

            Assert.IsFalse(run1.Cells[2][0].IsAlive);
            Assert.IsFalse(run1.Cells[2][1].IsAlive);
            Assert.IsTrue(run1.Cells[2][2].IsAlive);
            Assert.IsFalse(run1.Cells[2][3].IsAlive);
            Assert.IsFalse(run1.Cells[2][4].IsAlive);

            Assert.IsFalse(run1.Cells[3][0].IsAlive);
            Assert.IsFalse(run1.Cells[3][1].IsAlive);
            Assert.IsTrue(run1.Cells[3][2].IsAlive);
            Assert.IsFalse(run1.Cells[3][3].IsAlive);
            Assert.IsFalse(run1.Cells[3][4].IsAlive);

            Assert.IsFalse(run1.Cells[4][0].IsAlive);
            Assert.IsFalse(run1.Cells[4][1].IsAlive);
            Assert.IsFalse(run1.Cells[4][2].IsAlive);
            Assert.IsFalse(run1.Cells[4][3].IsAlive);
            Assert.IsFalse(run1.Cells[4][4].IsAlive);

            var run2 = _testRuns[2]; //this is same as seed due to oscillation effect
            Assert.IsTrue(run2.Cells[2][1].IsAlive);
            Assert.IsTrue(run2.Cells[2][2].IsAlive);
            Assert.IsTrue(run2.Cells[2][3].IsAlive);

            //the asserts above are too verbose. In the next version, compact them to another method that can
            //assert bool values in an array and a list of indices
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Generation<SimpleCell> seedGeneration = new Generation<SimpleCell>(5, 5);
            //setup seed
            //Blinker (period 2) - Oscillator
            seedGeneration.Cells[2][1].IsAlive = true;
            seedGeneration.Cells[2][2].IsAlive = true;
            seedGeneration.Cells[2][3].IsAlive = true;

            //Toad
            //Generation<SimpleCell> seedGeneration = new Generation<SimpleCell>(6, 6);
            //seedGeneration.Cells[2][2].IsAlive = true;
            //seedGeneration.Cells[2][3].IsAlive = true;
            //seedGeneration.Cells[2][4].IsAlive = true;
            //seedGeneration.Cells[3][1].IsAlive = true;
            //seedGeneration.Cells[3][2].IsAlive = true;
            //seedGeneration.Cells[3][3].IsAlive = true;

            //Still Life - boat
            //Generation<SimpleCell> seedGeneration = new Generation<SimpleCell>(4, 4);
            //seedGeneration.Cells[1][1].IsAlive = true;
            //seedGeneration.Cells[1][2].IsAlive = true;
            //seedGeneration.Cells[2][1].IsAlive = true;
            //seedGeneration.Cells[2][2].IsAlive = true;

            Engine<SimpleCell> engine = new Engine<SimpleCell>(seedGeneration, maxGens);

            engine.Process(Display);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Done");
            Console.ReadLine();
        }
Exemplo n.º 6
0
 public void Render(Generation.IHtmlWriter writer)
 {
     foreach (var item in values)
     {
         writer.AddAttribute(item.Key, item.Value);
     }
 }
Exemplo n.º 7
0
        private static void RenderObject(Generation.IHtmlWriter writer, object content)
        {
            if (content == null)
                return;

            // render nested control
            if (content is IRenderable)
            {
                ((IRenderable)content).Render(writer);
                return;
            }

            // render text value
            string contentText;
            bool encode;
            if (content is IHtmlContent)
            {
                contentText = ((IHtmlContent)content).GetRawString();
                encode = false;
            }
            else
            {
                contentText = content.ToString();
                encode = true;
            }

            writer.WriteText(contentText, encode);
        }
Exemplo n.º 8
0
        public void new_generation_should_kill_alive_cell_with_eight_alive_neighbours()
        {
            var generation = new Generation(new Cell(0, 0), new Cell(1, 0), new Cell(2, 0),
                                            new Cell(0, 1), new Cell(1, 1), new Cell(2, 1),
                                            new Cell(0, 2), new Cell(1, 2), new Cell(2, 2));

            generation.Tick().Contains(new Cell(1, 1)).Should().BeFalse();
        }
    protected virtual void StartGeneration()
    {
        generationNumber++;

        if(generationTxt != null)
        {
            generationTxt.text = "GEN " + generationNumber;
        }

        Debug.Log("New generation " + generationNumber);
        Generation currentGeneration = new Generation("G" + generationNumber);
        generations.AddLast(currentGeneration);
    }
Exemplo n.º 10
0
 public static void Display(Generation<SimpleCell> g, int currLevel)
 {
     Console.Clear();
     for (int outerCtr = 0; outerCtr < g.Cells.Count; outerCtr++ )
     {
         string[] line = g.Cells[outerCtr].Select(c => c.IsAlive ? "X" : "-").ToArray<string>();
         foreach(string part in line)
             Console.Write(part);
         Console.WriteLine();
     }
     Console.WriteLine();
     //somehow make the gen level display correct for now
     Console.WriteLine("Processed Gen {0}", currLevel);
 }
		/// <summary>
		/// Creates a new generation with a better fitted offspring based on the provided generation.
		/// </summary>
		private Generation CreateBetterGeneration(Generation oldGeneration, string expectedOutput)
		{
			Generation result = null;
			bool betterGeneration = false;
			while (!betterGeneration)
			{
				result = _generationBuilder.BuildNewGeneration(oldGeneration, expectedOutput);
				if (oldGeneration.Offspring == null || result.Offspring.Fitness < oldGeneration.Offspring.Fitness)
				{
					betterGeneration = true;
				}
			}

			return result;
		}
		/// <summary>
		/// Starts the evolution simulation
		/// </summary>
		/// <param name="input">The expected output</param>
		public void StartEvolution(string input)
		{
			Console.WriteLine("Original input: {0}", input);
			Person parent1 = _individFactory.CreateIndividual(_randomizer.GetRandomizedInput(input), input);
			Person parent2 = _individFactory.CreateIndividual(_randomizer.GetRandomizedInput(input), input);
			Console.WriteLine("First parent: {0}", parent1);
			Console.WriteLine("Second parent: {0}", parent2);

			// set up an initial generation
			Generation initialGeneration = new Generation();
			initialGeneration.Ancestors.Add(parent1);
			initialGeneration.Ancestors.Add(parent2);

			// start the main loop
			StartInner(initialGeneration, input);
		}
Exemplo n.º 13
0
        public void Should_Result_In_A_Empty_Grid_With_Diehard_Seed_At_130th_Tick()
        {
            var grid = @"------X-XX-------X---XXX";

            var generation = new Generation(grid, 3, 8);

            // Run 129 ticks.
            for (int i = 0; i < 129; i++)
                generation = generation.Tick();

            Assert.NotEqual(0, generation.TotalAlive);

            // Run the 130th tick.
            generation = generation.Tick();

            Assert.Equal(0, generation.TotalAlive);
        }
		/// <summary>
		/// Starts the inner main loop that finds the solution.
		/// </summary>
		private void StartInner(Generation initialGeneration, string expectedOutput)
		{
			Stopwatch stopwatch = Stopwatch.StartNew();
			Generation lastGeneration = initialGeneration;
			bool finalGenerationFound = false;
			int generationCount = 0;

			// create better generations with each iteration to reach the expected result
			while (!finalGenerationFound)
			{
				lastGeneration = CreateBetterGeneration(lastGeneration, expectedOutput);
				Console.WriteLine("Gen: {0} | Fitness: {1} | {2}", ++generationCount, lastGeneration.Offspring.Fitness, lastGeneration.Offspring.Value);
				finalGenerationFound = lastGeneration.Offspring.Fitness == 0;
			}
			stopwatch.Stop();
			TimeSpan ts = TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds);
			Console.WriteLine("Elapsed time: {0}", ts);
		}
Exemplo n.º 15
0
		public Generation BuildNewGeneration(Generation oldGeneration, string expectedResult)
		{
			Generation result = new Generation();
			result.Offspring = new Person();

			// find the best 2 ancestors to create a new generation (this includes the parents)
			var allPossibleAncestors = new List<Person>();

			// include the ancestors of the last generation
			foreach (Person parent in oldGeneration.Ancestors)
			{
				if (allPossibleAncestors.All(a => a.Value != parent.Value))
				{
					allPossibleAncestors.Add(parent);
				}
			}
			// include the offspring of the last generation
			if (oldGeneration.Offspring != null && !string.IsNullOrWhiteSpace(oldGeneration.Offspring.Value))
			{
				if (allPossibleAncestors.All(a => a.Value != oldGeneration.Offspring.Value))
				{
					allPossibleAncestors.Add(oldGeneration.Offspring);
				}
			}

			// order by fitness values in ascending order to take the best 2 ancestors, the rest are eliminated
			Person[] bestAncestors = allPossibleAncestors.OrderBy(d => d.Fitness).Take(2).ToArray();
			result.Ancestors.Add(bestAncestors[0]);
			result.Ancestors.Add(bestAncestors[1]);

			// create the child and evaluate its fitness
			result.Offspring.Value = _childFactory.GetNewChild(result.Ancestors);
			result.Offspring.Fitness = _stringDistanceCalculator.GetDistance(result.Offspring.Value, expectedResult);

			return result;
		}
Exemplo n.º 16
0
 /// <summary>
 /// Constructor: Encryption ( Generation, Key )
 /// </summary>
 public Encrypt(Generation Gen, Byte Key)
 {
     this.Reset(Gen, Key);
 }
Exemplo n.º 17
0
 /// <summary>
 /// Reset Encryption ( Generation )
 /// </summary>
 public void Reset(Generation Gen)
 {
     this.Reset(Gen, mKey);
 }
Exemplo n.º 18
0
    public void LoadData(List <string> heroData)
    {
        int index = 2;

        StringId = heroData[0].Split(' ')[1];

        while (heroData[index] != ".end")
        {
            List <string> data = heroData[index++].Replace("%", "").Replace("\"", "").
                                 Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            switch (data[0])
            {
            case "rendering:":
                RenderingRankOverride = int.Parse(data[2]);
                break;

            case "commonfx:":
                if (CommonEffects == null)
                {
                    CommonEffects = new CommonEffects(data);
                }
                else
                {
                    CommonEffects.LoadData(data);
                }
                break;

            case "combat_skill:":
                SkillArtInfo skillArt = new SkillArtInfo(data, false);
                SkillArtInfo.Add(skillArt);
                break;

            case "riposte_skill:":
                SkillArtInfo riposteArt = new SkillArtInfo(data, false);
                SkillArtInfo.Add(riposteArt);
                break;

            default:
                Debug.LogError("Unknown art token in hero: " + StringId);
                break;
            }
        }
        index += 2;

        while (heroData[index] != ".end")
        {
            List <string> data = heroData[index++].Replace("%", "").Replace("\"", "").
                                 Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            switch (data[0])
            {
            case "resistances:":
                Resistanses.Add(AttributeType.Stun, float.Parse(data[2]) / 100);
                Resistanses.Add(AttributeType.Poison, float.Parse(data[4]) / 100);
                Resistanses.Add(AttributeType.Bleed, float.Parse(data[6]) / 100);
                Resistanses.Add(AttributeType.Disease, float.Parse(data[8]) / 100);
                Resistanses.Add(AttributeType.Move, float.Parse(data[10]) / 100);
                Resistanses.Add(AttributeType.Debuff, float.Parse(data[12]) / 100);
                Resistanses.Add(AttributeType.DeathBlow, float.Parse(data[14]) / 100);
                Resistanses.Add(AttributeType.Trap, float.Parse(data[16]) / 100);
                break;

            case "weapon:":
                Equipment weapon = new Equipment(data[2], Weapons.Count + 1, HeroEquipmentSlot.Weapon);
                weapon.EquipmentModifiers.Add(new FlatModifier(AttributeType.DamageLow, float.Parse(data[6]), false));
                weapon.EquipmentModifiers.Add(new FlatModifier(AttributeType.DamageHigh, float.Parse(data[7]), false));
                weapon.EquipmentModifiers.Add(new FlatModifier(AttributeType.CritChance, float.Parse(data[9]) / 100, false));
                weapon.EquipmentModifiers.Add(new FlatModifier(AttributeType.SpeedRating, float.Parse(data[11]), false));
                Weapons.Add(weapon);
                break;

            case "armour:":
                Equipment armor = new Equipment(data[2], Armors.Count + 1, HeroEquipmentSlot.Armor);
                armor.EquipmentModifiers.Add(new FlatModifier(AttributeType.DefenseRating, float.Parse(data[4]) / 100, false));
                armor.EquipmentModifiers.Add(new FlatModifier(AttributeType.HitPoints, float.Parse(data[8]), true));
                Armors.Add(armor);
                break;

            case "combat_skill:":
                List <string> combatData = new List <string>();
                data = heroData[index - 1].Split(new char[] { '\"' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                bool isEffectData = false;
                foreach (var item in data)
                {
                    if (isEffectData)
                    {
                        if (item.Trim(' ').StartsWith("."))
                        {
                            isEffectData = false;
                        }
                        else
                        {
                            combatData.Add(item);
                            continue;
                        }
                    }

                    string[] combatItems = item.Replace("%", "").Split(
                        new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (combatItems[combatItems.Length - 1] == ".effect")
                    {
                        isEffectData = true;
                    }
                    combatData.AddRange(combatItems);
                }

                CombatSkillVariants.Add(new CombatSkill(combatData, true));
                break;

            case "combat_move_skill:":
                MoveSkill moveSkill = new MoveSkill();
                moveSkill.Id           = data[2];
                moveSkill.Type         = data[6];
                moveSkill.MoveBackward = int.Parse(data[8]);
                moveSkill.MoveForward  = int.Parse(data[9]);
                MoveSkill = moveSkill;
                break;

            case "riposte_skill:":
                List <string> riposteData = new List <string>();
                data = heroData[index - 1].Split(new char[] { '\"' }).ToList();
                bool isReposteEffect = false;
                foreach (var item in data)
                {
                    if (isReposteEffect)
                    {
                        if (item.Trim(' ')[0] == '.')
                        {
                            isEffectData = false;
                        }
                        else
                        {
                            riposteData.Add(item);
                            continue;
                        }
                    }

                    string[] combatItems = item.Replace("%", "").Split(
                        new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (combatItems[combatItems.Length - 1] == ".effect")
                    {
                        isEffectData = true;
                    }
                    riposteData.AddRange(combatItems);
                }
                RiposteSkill = new CombatSkill(riposteData, true);
                break;

            case "incompatible_party_member:":
                IncompatiablePartyTag = data[4];
                break;

            case "tag:":
                Tags.Add(data[2]);
                break;

            case "controlled:":
                TargetRank = int.Parse(data[2]);
                break;

            case "id_index:":
                IndexId = int.Parse(data[2]);
                break;

            case "skill_selection:":
                CanSelectCombatSkills        = bool.Parse(data[2]);
                NumberOfSelectedCombatSkills = int.Parse(data[4]);
                break;

                #region Death Door
            case "deaths_door:":
                if (DeathDoor == null)
                {
                    DeathDoor = new DeathDoor(data);
                }
                else
                {
                    DeathDoor.LoadData(data);
                }
                break;

                #endregion
                #region Generation
            case "generation:":
                if (Generation == null)
                {
                    Generation = new HeroGeneration(data);
                }
                else
                {
                    Generation.LoadData(data);
                }
                break;

                #endregion
                #region Battle Loot
            case "extra_battle_loot:":
                if (ExtraBattleLoot == null)
                {
                    ExtraBattleLoot = new LootDefinition(data);
                }
                else
                {
                    ExtraBattleLoot.LoadData(data);
                }
                break;

                #endregion
                #region Curio Loot
            case "extra_curio_loot:":
                if (ExtraCurioLoot == null)
                {
                    ExtraCurioLoot = new LootDefinition(data);
                }
                else
                {
                    ExtraCurioLoot.LoadData(data);
                }
                break;

                #endregion
                #region Inventory Stack
            case "extra_stack_limit:":
                ExtraStackLimit = data[2];
                break;

                #endregion
                #region Mode
            case "mode:":
                Modes.Add(new CharacterMode(data));
                break;

                #endregion
            default:
                Debug.LogError("Unknown info token " + data[0] + " in hero: " + StringId);
                break;
            }
        }

        CombatSkills = new List <CombatSkill>(CombatSkillVariants.FindAll(skill => skill.Level == 0));
    }
Exemplo n.º 19
0
 protected override void LoadMembers(Generation.ClassDiagraming.ClassDiagramVisitorContext context)
 {
     // don't load any member for enums
 }
Exemplo n.º 20
0
    public Generation Next()
    {
        Generation newGeneration = new Generation(this);

        return(newGeneration);
    }
Exemplo n.º 21
0
        public void new_generation_should_keep_alive_cell_with_two_live_neighbours()
        {
            var generation = new Generation(new Cell(1, 1), new Cell(0, 1), new Cell(2, 1));

            generation.Tick().Contains(new Cell(1, 1)).Should().BeTrue();
        }
Exemplo n.º 22
0
 protected override void LoadMembers(Generation.ClassDiagraming.ClassDiagramVisitorContext context)
 {
     // don't load members if it's an enum
 }
Exemplo n.º 23
0
 public int CompareTo(SiloAddress other)
 {
     return(other == null ? 1 : Generation.CompareTo(other.Generation));
 }
Exemplo n.º 24
0
 private void ReadHeader(Stream s)
 {
     try
     {
         s.Seek(0, 0);
         DebugLog.PrintLn("Reading Package Summary...");
         HeaderInfo h = new HeaderInfo();
         h.magic = ReadUInt(s);
         if (h.magic != 0x9E2A83C1)
         {
             throw new Exception("Not a valid PCC Package, wrong magic!");
         }
         h.ver1                 = ReadUInt16(s);
         h.ver2                 = ReadUInt16(s);
         h.HeaderLength         = ReadUInt(s);
         h.Group                = ReadUString(s);
         h._offsetFlag          = (uint)s.Position;
         h.Flags                = ReadUInt(s);
         GeneralInfo.compressed = (h.Flags & 0x02000000) != 0;
         DebugLog.PrintLn("Is Compressed : " + GeneralInfo.compressed);
         h.unk1 = ReadUInt(s);
         if (h.unk1 != 0)
         {
             throw new Exception("Not a valid PCC Package, Unk1 != 0");
         }
         h.NameCount     = ReadUInt(s);
         h.NameOffset    = ReadUInt(s);
         h.ExportCount   = ReadUInt(s);
         h.ExportOffset  = ReadUInt(s);
         h.ImportCount   = ReadUInt(s);
         h.ImportOffset  = ReadUInt(s);
         h.FreeZoneStart = ReadUInt(s);
         h.FreeZoneEnd   = ReadUInt(s);
         h.unk2          = ReadUInt(s);
         h.unk3          = ReadUInt(s);
         h.unk4          = ReadUInt(s);
         h.GUID          = new byte[16];
         s.Read(h.GUID, 0, 16);
         int count = ReadInt(s);
         DebugLog.PrintLn("Reading Generations...");
         h.Generations = new List <Generation>();
         for (int i = 0; i < count; i++)
         {
             Generation g = new Generation();
             g.ExportCount = ReadUInt(s);
             g.ImportCount = ReadUInt(s);
             g.NetObjCount = ReadUInt(s);
             h.Generations.Add(g);
         }
         DebugLog.PrintLn("Done.");
         h.EngineVersion      = ReadUInt(s);
         h.CookerVersion      = ReadUInt(s);
         h.unk5               = ReadUInt(s);
         h.unk6               = ReadUInt(s);
         h.CompressionFlag    = ReadUInt(s);
         h._offsetCompFlagEnd = (uint)s.Position;
         count    = ReadInt(s);
         h.Chunks = new List <CompressedChunk>();
         if (GeneralInfo.compressed)
         {
             DebugLog.PrintLn("Reading Chunktable...");
             for (int i = 0; i < count; i++)
             {
                 CompressedChunk c = new CompressedChunk();
                 c.UnCompOffset = ReadUInt(s);
                 c.UnCompSize   = ReadUInt(s);
                 c.CompOffset   = ReadUInt(s);
                 c.CompSize     = ReadUInt(s);
                 h.Chunks.Add(c);
             }
             h.DeCompBuffer = new MemoryStream();
             DebugLog.PrintLn("Done.");
         }
         h.unk7 = ReadUInt(s);
         h.unk8 = ReadUInt(s);
         Header = h;
         if (GeneralInfo.compressed)
         {
             ReadChunks(s);
         }
         DebugLog.PrintLn("Done.");
     }
     catch (Exception ex)
     {
         DebugLog.PrintLn("PCCPACKAGE::READHEADER ERROR:\n" + ex.Message);
     }
 }
Exemplo n.º 25
0
 public static int LiveCellAtLocation(RowCol location, Generation cells) => cells[location] ? 1 : 0;
Exemplo n.º 26
0
        public static void Run()
        {
            var lines = File.ReadAllLines("input.txt");

            var initialState = lines[0].Substring(15);
            var rules        = new List <Rule>();

            for (int l = 2; l < lines.Length; l++)
            {
                var rule = new Rule(lines[l]);
                rules.Add(rule);
            }

            cavern = new Cavern(initialState);

            //Console.WriteLine(cavern.ToString(cavern.CurrentGeneration, -3, 35));

            for (int g = 1; g <= 20; g++)
            {
                var instructions = new List <Instruction>();

                var currentGeneration = cavern.Generations[cavern.CurrentGeneration];

                var currentGenerationString = currentGeneration.ToString();
                var generationString        = currentGenerationString;

                int minRange = currentGeneration.MinRange;
                int maxRange = currentGeneration.MaxRange;

                //if (currentGenerationString.StartsWith("#")) {
                minRange        -= 3;
                generationString = "..." + generationString;
                //}

                //if (currentGenerationString.EndsWith("#")) {
                maxRange        += 3;
                generationString = generationString + "...";
                //}

                foreach (var rule in rules)
                {
                    var result = rule.Valid(minRange, generationString);
                    if (result.Count > 0)
                    {
                        foreach (int potId in result)
                        {
                            instructions.Add(new Instruction {
                                PotId = potId, CreatesAPlant = rule.CreatesAPlant
                            });
                        }
                    }
                }

                var generation = new Generation(minRange, new string('.', maxRange - minRange));

                foreach (var instruction in instructions)
                {
                    var pot = generation.Pots[instruction.PotId];
                    pot.HasPlant = instruction.CreatesAPlant;
                    generation.Pots[instruction.PotId] = pot;
                }

                cavern.NextGeneration(minRange, generation.ToString());
                //Console.WriteLine(cavern.ToString(cavern.CurrentGeneration, -3, 35));
            }

            var lastGeneration = cavern.Generations[20];

            int sum = 0;

            foreach (var kvp in lastGeneration.Pots)
            {
                if (kvp.Value.HasPlant)
                {
                    sum += kvp.Key;
                }
            }

            //Console.WriteLine(lastGeneration.ToString());
            Console.WriteLine(sum);
            //AssertMockInput();
        }
Exemplo n.º 27
0
        public async Task GetRelatedEntitiesCountShouldReturnCorrectValues()
        {
            var options = new DbContextOptionsBuilder <NeedForCarsDbContext>()
                          .UseInMemoryDatabase("RelatedEntitiesDb_engines")
                          .Options;

            var context = new NeedForCarsDbContext(options);

            var enginesService = new EnginesService(context);

            var make = new Make
            {
                Name        = "Make",
                Description = "Desc"
            };
            await context.Makes.AddAsync(make);

            var model = new Model
            {
                MakeId = make.Id,
                Name   = "Model1",
            };
            await context.Models.AddAsync(model);

            var generation = new Generation
            {
                ModelId = model.Id,
                Name    = "Model1"
            };
            await context.Generations.AddAsync(generation);

            var engine = new Engine
            {
                Name     = "engine",
                MaxHP    = 100,
                FuelType = Models.Enums.FuelType.Diesel,
                Creator  = "creator"
            };
            await context.Engines.AddAsync(engine);

            var car = new Car
            {
                GenerationId = generation.Id,
                EngineId     = engine.Id,
                Transmission = Models.Enums.Transmission.Automatic,
                DriveWheel   = Models.Enums.DriveWheel.AllWheelDrive,
                BeginningOfProductionYear  = 2000,
                BeginningOfProductionMonth = 1
            };
            await context.Cars.AddAsync(car);

            var user = new NeedForCarsUser
            {
                Email        = "*****@*****.**",
                UserName     = "******",
                PasswordHash = "HASHEDPASSWORD",
                FirstName    = "First",
                LastName     = "Last",
                PhoneNumber  = "1234567890"
            };
            await context.Users.AddAsync(user);

            var userCar = new UserCar
            {
                OwnerId             = user.Id,
                CarId               = car.Id,
                Color               = "color",
                ProductionDateYear  = 2000,
                ProductionDateMonth = 1,
                Mileage             = 0
            };
            await context.UserCars.AddAsync(userCar);

            await context.SaveChangesAsync();

            enginesService.GetRelatedEntitiesCount(engine, out int cars, out int userCars);

            Assert.True(cars == 1 && userCars == 1);
        }
Exemplo n.º 28
0
 public void FoliageGenerationCallback(Voronoi sourceVoronoi, Generation world)
 {
     roadGenerator.Generate(sourceVoronoi, world, zone);
 }
Exemplo n.º 29
0
 public IEnumerable <InstalledFile> GetAssets(Generation generation, Gender gender = Gender.All)
 {
     return(Cache.Where(x => x.Key.CheckFlag(generation)).SelectMany(x => x.Value.GetAssets(gender)));
 }
Exemplo n.º 30
0
        internal static Int32 SubjectTagFromSubjectIDAndGeneration( Int32 subjectID, Generation generation, LinksDataSet dsLinks )
        {
            if ( dsLinks == null ) throw new ArgumentNullException("dsLinks");
            if ( dsLinks.tblSubject.Count <= 0 ) throw new InvalidOperationException("There should be more than one row in tblSubject.");

            string select = string.Format("{0} = {1} AND {2} = {3}",
                 dsLinks.tblSubject.SubjectIDColumn.ColumnName, subjectID,
                (byte)generation, dsLinks.tblSubject.GenerationColumn.ColumnName);
            LinksDataSet.tblSubjectRow[] drs = (LinksDataSet.tblSubjectRow[])dsLinks.tblSubject.Select(select);
            Trace.Assert(drs.Length == 1, "The should be exactly one SubjectRow retreived.");
            return drs[0].SubjectTag;
        }
Exemplo n.º 31
0
    void Update()
    {
        if (useTimer)
        {
            generationTimeCounter += Time.deltaTime;
            if (generationTimeCounter >= Config.STANDARD_GENERATION_TIME)
            {
                generationTimeCounter = 0;
                startNextGeneration   = true;
            }
        }

        if (startNextGeneration)
        {
            if (!evaluationFramePassed)
            {
                //EVALUATE SHIPS
                foreach (RandomShipCreator r in shipCreators)
                {
                    r.evaluateShip(this);
                }
                evaluationFramePassed = true;
            }
            else
            {
                //ALWAYS KEEP THE BEST OF ALL TIME
                foreach (ShipArchive s in currentGeneration.getShipArchives())
                {
                    if (s.fitness < bestOfAllTime.fitness)
                    {
                        bestOfAllTime = new ShipArchive(s.root.copyTree(), s.fitness);
                    }
                }

                //PERFORM SELECTION
                List <ShipChromosomeNode> selectionList = currentGeneration.SUS((uint)shipCreators.Count);

                //PERFORM CROSSOVER
                List <ShipChromosomeNode> nextGeneration =
                    CrossoverAndMutationManager.TreeCrossover(selectionList);

                //PERFORM MUTATION
                CrossoverAndMutationManager.TreeMutate(nextGeneration);                //NodeMutate(nextGeneration);

                //RESET THE CURRENT GENERATION AND STORE THE OLD ONE
                generations.Add(currentGeneration);
                currentGeneration = new Generation();

                //INITIALIZE THE NEXT GENERATION
                shipCreators[0].generatePhysicalShip(bestOfAllTime.root);
                for (int i = 1; i < shipCreators.Count; ++i)
                {
                    shipCreators[i].generatePhysicalShip(nextGeneration[i]);
                }
                activateGeneration();
                //generationTimeCounter = 0;
                evaluationFramePassed = false;
                startNextGeneration   = false;
            }
        }
    }
Exemplo n.º 32
0
        /// <summary>
        /// Performs the selection of chromosomes from the generation specified.
        /// </summary>
        /// <param name="number">The number of chromosomes to select.</param>
        /// <param name="generation">The generation where the selection will be made.</param>
        /// <returns>The select chromosomes.</returns>
        protected override IList <IChromosome> PerformSelectChromosomes(int number, Generation generation)
        {
            var ordered = generation.Chromosomes.OrderByDescending(c => c.Fitness);

            return(ordered.Take(number).ToList());
        }
Exemplo n.º 33
0
 /// <summary> 
 /// Updates state on barrier trip and wakes up everyone.
 /// Called only while holding lock.
 /// </summary>
 private void nextGeneration()
 {
     _generation.isTripped = true;
     Monitor.PulseAll(_internalBarrierEntryLock);
     _waitingPartiesCount = _parties;
     _generation = new Generation();
 }
Exemplo n.º 34
0
        static void Main(string[] args)
        {
            var generation = new Generation(new Bot.Factory.PlayerFactory());

            generation.Run();
        }
Exemplo n.º 35
0
 public void OnEnable()
 {
     hideFlags = HideFlags.HideAndDontSave;
     if (genClass == null)
     {
         genClass = new Generation();
     }
     if (texClass == null)
     {
         texClass = new List<wbTexturing>();
     }
 }
Exemplo n.º 36
0
 public override int GetHashCode()
 {
     return(Directory.GetHashCode() + Generation.GetHashCode());
 }
        public void SelectChromosomes_Generation_ChromosomesSelected()
        {
            var target = new StochasticUniversalSamplingSelection();
            var c1     = new ChromosomeStub();

            c1.Fitness = 0.1;

            var c2 = new ChromosomeStub();

            c2.Fitness = 0.5;

            var c3 = new ChromosomeStub();

            c3.Fitness = 0;

            var c4 = new ChromosomeStub();

            c4.Fitness = 0.7;

            var generation = new Generation(1, new List <IChromosome>()
            {
                c1, c2, c3, c4
            });

            // Fitness sum: 0.1 + 0.5 + 0 + 0.7 = 1.3
            // c1:  8% = 0.08
            // c2: 38% = 0.46
            // c3:  0% = 0.46
            // c4: 54% = 1.00
            var rnd = Substitute.For <IRandomization>();

            rnd.GetDouble().Returns(0.3);
            RandomizationProvider.Current = rnd;

            // Step size 1/2 = 0.5
            var actual = target.SelectChromosomes(2, generation);

            Assert.AreEqual(2, actual.Count);
            Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3
            Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.8

            // Step size 1/3 = 0.33
            actual = target.SelectChromosomes(3, generation);
            Assert.AreEqual(3, actual.Count);
            Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3
            Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.63
            Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.96

            // Step size 1/4 = 0.25
            actual = target.SelectChromosomes(4, generation);
            Assert.AreEqual(4, actual.Count);
            Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3
            Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.55
            Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.80
            Assert.AreEqual(c1.Fitness, actual[3].Fitness); // 0.05

            // Step size 1/5 = 0.20
            actual = target.SelectChromosomes(5, generation);
            Assert.AreEqual(5, actual.Count);
            Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3
            Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.5
            Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.7
            Assert.AreEqual(c4.Fitness, actual[3].Fitness); // 0.9
            Assert.AreEqual(c2.Fitness, actual[4].Fitness); // 0.1
        }
Exemplo n.º 38
0
        public void RemoveChild(Node <Person> child, string name)
        {
            Generation generation = GetGenerationByID(child.Value.GenerationID);

            generation.RemovePerson(child, name);
        }
Exemplo n.º 39
0
 private void Help(Generation<SimpleCell> g, int level)
 {
     _testRuns.Add(g);
     //if need be uncomment the code below before running the tests
     //for (int outerCtr = 0; outerCtr < g.Cells.Count; outerCtr++)
     //{
     //    string[] line = g.Cells[outerCtr].Select(c => c.IsAlive ? "X" : "-").ToArray<string>();
     //    foreach (string part in line)
     //        Console.Write(part);
     //    Console.WriteLine();
     //}
     //Console.WriteLine();
 }
Exemplo n.º 40
0
        public void SelectChromosomes_Generation_ChromosomesSelected()
        {
            var target = new RankSelection();
            var c1     = Substitute.ForPartsOf <ChromosomeBase>(2);

            c1.Fitness = 0.1;

            var c2 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c2.Fitness = 0.5;

            var c3 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c3.Fitness = 0;

            var c4 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c4.Fitness = 0.7;

            var generation = new Generation(1, new List <IChromosome>()
            {
                c1, c2, c3, c4
            });

            // Just one selected chromosome is c1.
            FlowAssert.IsAtLeastOneAttemptOk(100, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.AreEqual(1, actual.Count(c => c.Fitness == 0.1));
            });

            // All selected chromosome is c1.
            FlowAssert.IsAtLeastOneAttemptOk(1000, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.IsTrue(actual.All(c => c.Fitness == 0.1));
            });

            // Just one selected chromosome is c2.
            FlowAssert.IsAtLeastOneAttemptOk(100, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.AreEqual(1, actual.Count(c => c.Fitness == 0.5));
            });

            // All selected chromosome is c2.
            FlowAssert.IsAtLeastOneAttemptOk(1000, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.IsTrue(actual.All(c => c.Fitness == 0.5));
            });

            // Just one selected chromosome is c3.
            FlowAssert.IsAtLeastOneAttemptOk(100, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.AreEqual(1, actual.Count(c => c.Fitness == 0));
            });

            // All selected chromosome is c3.
            FlowAssert.IsAtLeastOneAttemptOk(1000, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.IsTrue(actual.All(c => c.Fitness == 0));
            });

            // Just one selected chromosome is c4.
            FlowAssert.IsAtLeastOneAttemptOk(100, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.AreEqual(1, actual.Count(c => c.Fitness == 0.7));
            });

            // All selected chromosome is c4.
            FlowAssert.IsAtLeastOneAttemptOk(1000, () =>
            {
                var actual = target.SelectChromosomes(2, generation);
                Assert.AreEqual(2, actual.Count);
                Assert.IsTrue(actual.All(c => c.Fitness == 0.7));
            });
        }
Exemplo n.º 41
0
    public void PushGeneration(Generation gen)
    {
        if(genList.Count == 0)
        {
            gen.genCamera.IsPlayableCamera = true;
            gen.IsPlayable = true;
        }
        else
        {
            SoilScript[] soils = genList[0].GetComponentsInChildren<SoilScript>();

            foreach(SoilScript soil in soils)
            {
                SoilMessage m = new SoilMessage();
                m.id = soil.soilId;
                m.soilObject = soil.SoilObject;
                m.action = Action.INCREMENT_GENERATION;
                m.Broadcast(gen.gameObject);
            }
        }

        if(genList.Count < MAX_GENERATIONS)
        {
            gen.genCamera.SkipTransition();
        }

        genList.Insert(0, gen);

        if(genList.Count > MAX_GENERATIONS)
        {
            genList[genList.Count - 1].genCamera.FlaggedForDeath = true;
            IsTransitioning = true;
        }

        while (messages.Count != 0)
        {
            messages.Dequeue().Broadcast(gen.gameObject);
        }

        dirty = true;
    }
Exemplo n.º 42
0
 private void Awake()
 {
     generation = FindObjectOfType <Generation>();
 }
Exemplo n.º 43
0
 /// <summary>
 /// Reset Encryption ( Generation, Key )
 /// </summary>
 public void Reset(Generation Gen, Byte Key)
 {
     this.mKey = Key;
     this.mGeneration = Gen;
     this.mIterator[0] = ITERATOR_START_VAL[(int)this.mGeneration];
     this.mIterator[1] = ITERATOR_START_VAL[(int)this.mGeneration];
     this.mLimit = -1;
 }
Exemplo n.º 44
0
        private void ConnectChildrenToParents(object sender, GenerationChangedEventArgs e)
        {
            Generation            generation = (Generation)sender;
            List <Node <Person> > personList = new List <Node <Person> >();

            foreach (Grid grid in generation.GenerationGridList)
            {
                foreach (TextBox textBox in grid.Children.OfType <TextBox>())
                {
                    Node <Person> nextPerson = null;
                    if (generation.TextBoxList.IndexOf(textBox) != generation.TextBoxList.Count - 1)
                    {
                        if (PersonTree.GetNodeByName(PersonTree.Tree, textBox.Text,
                                                     generation.TextBoxList[generation.TextBoxList.IndexOf(textBox) + 1].Text) != null)
                        {
                            nextPerson = PersonTree.GetNodeByName(PersonTree.Tree, textBox.Text,
                                                                  generation.TextBoxList[generation.TextBoxList.IndexOf(textBox) + 1].Text);
                        }
                    }

                    else
                    {
                        nextPerson = PersonTree.GetNodeByName(PersonTree.Tree, textBox.Text, string.Empty);
                    }
                    if (nextPerson != null)
                    {
                        if (nextPerson.Value.GenerationID == generation.GenerationID)
                        {
                            if (!personList.Any(item => item.Value.Name == nextPerson.Value.Name))
                            {
                                personList.Add(nextPerson);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < ConnectionsGrid.Children.Count; i++)
            {
                if (ConnectionsGrid.Children[i].GetType() == typeof(Line) &&
                    ((Line)ConnectionsGrid.Children[i]).Name == "Child" + generation.GenerationID.ToString().Replace("-", string.Empty))
                {
                    ConnectionsGrid.Children.Remove(ConnectionsGrid.Children[i]);
                    i--;
                }
            }

            //for (int i = 0; i < generation.ParentsGridList[parentIndex].Children.Count - 1; i++)
            //{
            //    if (generation.ParentsGridList[parentIndex].Children[i].GetType() == typeof(Line) &&
            //        ((Line)generation.ParentsGridList[parentIndex].Children[i]).Name ==
            //        "Child" + generation.GenerationID.ToString().Replace("-", string.Empty))
            //    {
            //        generation.ParentsGridList[parentIndex].Children.Remove(generation.ParentsGridList[parentIndex].Children[i]);
            //        i--;
            //    }
            //}

            foreach (Node <Person> person in personList)
            {
                int  parentIndex       = 0;
                int  parentColumnIndex = 0;
                bool found             = false;
                for (int i = 0; i < generation.ParentsGridList.Count; i++)
                {
                    for (int j = 0; j < generation.ParentsGridList[i].Children.Count && !found; j++)
                    {
                        if (generation.ParentsGridList[i].Children[j].GetType() == typeof(TextBox))
                        {
                            if ((string)generation.ParentsGridList[i].Children[j].GetValue(TextBox.TextProperty) == person.Parent.Value.Name)
                            {
                                parentIndex       = i;
                                parentColumnIndex = Grid.GetColumn(generation.ParentsGridList[i].Children[j]);
                                found             = true;
                            }
                        }
                    }
                }

                Line verticalLine1 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = 12.5,
                    X2      = 12.5,
                    Y1      = SystemFonts.MessageFontSize,
                    Y2      = SystemFonts.MessageFontSize * 2 + 1,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                generation.ParentsGridList[parentIndex].Children.Add(verticalLine1);
                Grid.SetRow(verticalLine1, 0);
                Grid.SetColumn(verticalLine1, parentColumnIndex + 1);

                Line verticalLine2 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = 12.5,
                    X2      = 12.5,
                    Y1      = 0,
                    Y2      = SystemFonts.MessageFontSize * 2 + 2,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                generation.ParentsGridList[parentIndex].Children.Add(verticalLine2);
                Grid.SetRow(verticalLine2, 1);
                Grid.SetColumn(verticalLine2, parentColumnIndex + 1);

                Line verticalLine3 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = 12.5,
                    X2      = 12.5,
                    Y1      = 0,
                    Y2      = SystemFonts.MessageFontSize * 3 + 8,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                generation.ParentsGridList[parentIndex].Children.Add(verticalLine3);
                Grid.SetRow(verticalLine3, 2);
                Grid.SetColumn(verticalLine3, parentColumnIndex + 1);

                Line verticalLine4 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = 12.5,
                    X2      = 12.5,
                    Y1      = 0,
                    Y2      = SystemFonts.MessageFontSize * 3 + 8,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                generation.ParentsGridList[parentIndex].Children.Add(verticalLine4);
                Grid.SetRow(verticalLine4, 4);
                Grid.SetColumn(verticalLine4, parentColumnIndex + 1);

                verticalLine4.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
                verticalLine4.Arrange(new Rect(verticalLine3.DesiredSize));
                verticalLine4.UpdateLayout();

                Point endPoint = verticalLine4.TranslatePoint(new Point(verticalLine4.X2, verticalLine4.Y2), ConnectionsGrid);

                int generationGridIndex = 0;
                int textBoxColumnIndex  = 0;
                foreach (Grid grid in generation.GenerationGridList)
                {
                    foreach (TextBox textBox in grid.Children.OfType <TextBox>())
                    {
                        if (textBox.Text == person.Value.Name)
                        {
                            generationGridIndex = generation.GenerationGridList.IndexOf(grid);
                            textBoxColumnIndex  = Grid.GetColumn(textBox);
                        }
                    }
                }

                Line verticalLine5 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = 125,
                    X2      = 125,
                    Y1      = 4,
                    Y2      = -SystemFonts.MessageFontSize * 2 - 2,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                generation.GenerationGridList[generationGridIndex].Children.Add(verticalLine5);
                Grid.SetRow(verticalLine5, 0);
                Grid.SetColumn(verticalLine5, textBoxColumnIndex);

                verticalLine5.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
                verticalLine5.Arrange(new Rect(verticalLine5.DesiredSize));
                verticalLine5.UpdateLayout();

                Point startPoint = verticalLine5.TranslatePoint(new Point(verticalLine5.X2, verticalLine5.Y2), ConnectionsGrid);

                Line horizontalLine1 = new Line()
                {
                    Stroke          = Brushes.Black,
                    Visibility      = Visibility.Visible,
                    StrokeThickness = 1,
                    X1      = startPoint.X,
                    X2      = endPoint.X,
                    Y1      = startPoint.Y,
                    Y2      = endPoint.Y,
                    Stretch = Stretch.None,
                    Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                };
                ConnectionsGrid.Children.Add(horizontalLine1);

                if (person.Value.Partner != string.Empty)
                {
                    Line horizontalLine = new Line()
                    {
                        Stroke          = Brushes.Black,
                        Visibility      = Visibility.Visible,
                        StrokeThickness = 1,
                        X1      = 0,
                        X2      = 25,
                        Y1      = SystemFonts.MessageFontSize,
                        Y2      = SystemFonts.MessageFontSize,
                        Stretch = Stretch.None,
                        Name    = "Child" + generation.GenerationID.ToString().Replace("-", string.Empty)
                    };
                    generation.GenerationGridList[generationGridIndex].Children.Add(horizontalLine);
                    Grid.SetRow(horizontalLine, 0);
                    Grid.SetColumn(horizontalLine, textBoxColumnIndex + 1);
                }
            }

            List <Node <Person> > parentsList = new List <Node <Person> >();

            foreach (Node <Person> person in personList)
            {
                if (!parentsList.Contains(person.Parent))
                {
                    parentsList.Add(person.Parent);
                }
            }

            foreach (Node <Person> parent in parentsList)
            {
                Node <Person> firstPerson = personList.FirstOrDefault(p => p.Parent == parent);
                Node <Person> lastPerson  = personList.LastOrDefault(p => p.Parent == parent);

                Grid generationGrid = null;

                foreach (Grid grid in generation.GenerationGridList)
                {
                    foreach (TextBox textBox in grid.Children.OfType <TextBox>())
                    {
                        if (textBox.Text == firstPerson.Value.Name)
                        {
                            generationGrid = grid;
                        }
                    }
                }

                int numberOfPartners = 0;
                for (int i = personList.IndexOf(firstPerson); i < personList.IndexOf(lastPerson); i++)
                {
                    if (personList[i].Value.Partner != string.Empty)
                    {
                        numberOfPartners++;
                    }
                }
            }
        }
Exemplo n.º 45
0
 protected override void RenderControl(Generation.IHtmlWriter writer)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 46
0
        public void TestRealistic()
        {
            var doctests = new List <Extraction.Doctest>
            {
                new Extraction.Doctest(
                    ns: "SomeNamespace",
                    usings: new List <Extraction.UsingDirective>
                {
                    new Extraction.UsingDirective("System.IO", null),
                    new Extraction.UsingDirective("Microsoft.CodeAnalysis.SyntaxTree", null),
                },
                    body: "var a = 1;",
                    line: 10,
                    column: 11),
                new Extraction.Doctest(
                    ns: "SomeNamespace",
                    usings: new List <Extraction.UsingDirective>(),
                    body: "var b = 2;",
                    line: 20,
                    column: 21),
                new Extraction.Doctest(
                    ns: "AnotherNamespace",
                    usings: new List <Extraction.UsingDirective>
                {
                    new Extraction.UsingDirective("Microsoft.CodeAnalysis.SyntaxTree", null),
                },
                    body: "var c = 3;",
                    line: 30,
                    column: 31),
                new Extraction.Doctest(
                    ns: "AnotherNamespace",
                    usings: new List <Extraction.UsingDirective>(),
                    body: "var d = 4;",
                    line: 40,
                    column: 41),
                new Extraction.Doctest(
                    ns: "SomeNamespace",
                    usings: new List <Extraction.UsingDirective>
                {
                    new Extraction.UsingDirective("Microsoft.CodeAnalysis.SyntaxTree", null),
                },
                    body: "var e = 5;",
                    line: 50,
                    column: 51),
                new Extraction.Doctest(
                    ns: "SomeNamespace",
                    usings: new List <Extraction.UsingDirective>(),
                    body: "var f = 6;",
                    line: 60,
                    column: 61)
            };

            var writer = new System.IO.StringWriter();

            Generation.Generate(doctests, writer);

            string expected = @"// This file was automatically generated by doctest-csharp.
// !!! DO NOT EDIT OR APPEND !!!

using Microsoft.CodeAnalysis.SyntaxTree;
using System.IO;

using NUnit.Framework;

namespace SomeNamespace.Tests
{
    public class DocTests
    {
        [Test]
        public void AtLine10AndColumn11
        {
            var a = 1;
        }

        [Test]
        public void AtLine20AndColumn21
        {
            var b = 2;
        }
    }
}

namespace AnotherNamespace.Tests
{
    public class DocTests
    {
        [Test]
        public void AtLine30AndColumn31
        {
            var c = 3;
        }

        [Test]
        public void AtLine40AndColumn41
        {
            var d = 4;
        }
    }
}

namespace SomeNamespace.Tests
{
    public class DocTests2
    {
        [Test]
        public void AtLine50AndColumn51
        {
            var e = 5;
        }

        [Test]
        public void AtLine60AndColumn61
        {
            var f = 6;
        }
    }
}

// This file was automatically generated by doctest-csharp.
// !!! DO NOT EDIT OR APPEND !!!
";

            Assert.AreEqual(expected, writer.ToString());
        }
Exemplo n.º 47
0
        private Int32 TranslateExtractSource( ExtractSource extractSource, Generation generation, bool femalesOnly, Int32[] passoverValues, DataTable dtImport )
        {
            Int32 gen1ReponseRecordsAddedCount = 0;
            LinksDataSet.tblVariableRow[] drsVariablesToTranslate = VariablesToTranslate(extractSource);
            _dsLinks.tblResponse.BeginLoadData();

            string subjectIDColumnName;
            string genderColumnName;
            switch ( generation ) {
                case Generation.Gen1:
                    subjectIDColumnName = Constants.Gen1SubjectIDColumn;
                    genderColumnName = Constants.Gen1GenderColumn;
                    break;
                case Generation.Gen2:
                    subjectIDColumnName = Constants.Gen2SubjectIDColumn;
                    genderColumnName = Constants.Gen2GenderColumn;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("generation", generation, "The generation value was not recognized.");
            }

            foreach ( DataRow drImport in dtImport.Rows ) {
                GenderBothGenerations gender = (GenderBothGenerations)Convert.ToInt32(drImport[genderColumnName]);
                if ( !femalesOnly || gender == GenderBothGenerations.Female ) {
                    Int32 subjectID = Convert.ToInt32(drImport[subjectIDColumnName]);
                    Int32 subjectTag = Retrieve.SubjectTagFromSubjectIDAndGeneration(subjectID, generation, _dsLinks);
                    foreach ( LinksDataSet.tblVariableRow drVariable in drsVariablesToTranslate ) {
                        string columnName = drVariable.VariableCode;
                        LinksDataSet.tblResponseRow drResponse = _dsLinks.tblResponse.NewtblResponseRow();
                        drResponse.Generation = (byte)generation;
                        drResponse.SubjectTag = subjectTag;
                        drResponse.ExtendedID = GetExtendedID(subjectTag);
                        drResponse.SurveySource = drVariable.SurveySource;
                        drResponse.SurveyYear = drVariable.SurveyYear;
                        drResponse.Item = drVariable.Item; //if ( drResponse.Item == 13 ) Trace.Assert(true);
                        drResponse.Value = Convert.ToInt32(drImport[columnName]);

                        LinksDataSet.tblItemRow drItem = drVariable.tblItemRow;
                        if ( !(drItem.MinValue <= drResponse.Value && drResponse.Value <= drItem.MaxValue) )
                            throw new InvalidOperationException(string.Format("For Item '{0}', variable '{1}', the value '{2}' exceeded the bounds of [{3}, {4}].", drVariable.Item, drVariable.ID, drResponse.Value, drItem.MinValue, drItem.MaxValue));
                        if ( 0 <= drResponse.Value && drResponse.Value < drItem.MinNonnegative )
                            throw new InvalidOperationException(string.Format("For Item '{0}', variable '{1}', the value '{2}' dipped below the minimum nonnegative value of {3}.", drVariable.Item, drVariable.ID, drResponse.Value, drItem.MinNonnegative));
                        if ( !passoverValues.Contains(drResponse.Value) ) {
                            drResponse.LoopIndex = drVariable.LoopIndex;
                            _dsLinks.tblResponse.AddtblResponseRow(drResponse);
                            gen1ReponseRecordsAddedCount += 1;
                        }
                    }
                }
            }
            _dsLinks.tblResponse.EndLoadData();
            return gen1ReponseRecordsAddedCount;
        }
Exemplo n.º 48
0
 public Generation(Generation generation)
 {
     number         = generation.number + 1;
     prevGeneration = generation;
 }
Exemplo n.º 49
0
 /// <summary>
 /// Returns true if the given generation uses the type with the given ID.
 /// </summary>
 private bool HasType(Generation generation, TypeEntry typeId)
 {
     return(typeId.Generation.Id <= generation.Id);
 }
Exemplo n.º 50
0
        public void EvolveTestXOR()
        {
            // Spawn the population
            population.Spawn(150);

            IGeneration generation = new Generation(population);

            int[,] xor = new int[2, 2];
            xor[0, 0]  = 0;
            xor[0, 1]  = 1;
            xor[1, 0]  = 1;
            xor[1, 1]  = 0;

            bool success = false;

            //Debug.WriteLine(DotGraph.Get(population.Genomes.First()));

            Enumerable.Range(1, 100).ToList().ForEach(i =>
            {
                //if (generation.FittestGenome != null)
                //    Debug.WriteLine(DotGraph.Get(generation.FittestGenome));

                if (!success)
                {
                    //Debug.WriteLine("(G" + i + ")" + "Genomes: " + generation.Population.Genomes.Count);

                    if (generation.FittestGenome != null &&
                        generation.FittestGenome.Activate(new double[] { 0, 0 })[0] < 0.5 &&
                        generation.FittestGenome.Activate(new double[] { 0, 1 })[0] >= 0.5 &&
                        generation.FittestGenome.Activate(new double[] { 1, 0 })[0] >= 0.5 &&
                        generation.FittestGenome.Activate(new double[] { 1, 1 })[0] < 0.5)
                    {
                        success = true;

                        string json = JsonConvert.SerializeObject(generation.FittestGenome);

                        Debug.WriteLine("Success!");
                        Debug.WriteLine(json);
                        Debug.WriteLine(DotGraph.Get(generation.FittestGenome));
                        Debug.WriteLine(i);
                    }
                    else
                    {
                        generation = generation.Evolve(g =>
                        {
                            double error = 0;

                            Enumerable.Range(0, 2).ToList().ForEach(x =>
                            {
                                Enumerable.Range(0, 2).ToList().ForEach(y =>
                                {
                                    int r      = xor[x, y];
                                    double[] o = g.Activate(new double[] { x, y });

                                    double distanceFromAnswer = Math.Abs(r - Math.Min(1, Math.Round(o[0], 4)));

                                    error += distanceFromAnswer;
                                });
                            });

                            return(Math.Pow(4 - error, 2));
                        });
                    }
                }
            });
        }
Exemplo n.º 51
0
    IEnumerator EndGeneration(Voronoi voronoi, Generation world, PointOfInterest pointOfInterest)
    {
        yield return(new WaitForSeconds(1f));

        pointOfInterest.FoliageGenerationCallback(voronoi, world);
    }
Exemplo n.º 52
0
        public void EvolveTestBitPosition()
        {
            GenomeParameters.AverageWeightDifferenceFactor  = 3;
            GenomeParameters.CompatibilityDistanceThreshold = 4;

            // Spawn the population
            population = new Population(4, 4);
            population.Spawn(300);

            IGeneration generation = new Generation(population);

            bool success = false;

            Enumerable.Range(1, 500).ToList().ForEach(i =>
            {
                //Debug.WriteLine("(G" + i + ")" + "Genomes: " + generation.Population.Genomes.Count);

                if (!success)
                {
                    double[] output1 = new double[] {};
                    double[] output2 = new double[] {};
                    double[] output3 = new double[] {};
                    double[] output4 = new double[] {};

                    if (generation.FittestGenome != null)
                    {
                        output1 = generation.FittestGenome.Activate(new double[] { 1, 0, 0, 0 });
                        output2 = generation.FittestGenome.Activate(new double[] { 0, 1, 0, 0 });
                        output3 = generation.FittestGenome.Activate(new double[] { 0, 0, 1, 0 });
                        output4 = generation.FittestGenome.Activate(new double[] { 0, 0, 0, 1 });
                    }

                    if (generation.FittestGenome != null &&
                        output1[0] >= 0.5 &&
                        output1[1] < 0.5 &&
                        output1[2] < 0.5 &&
                        output1[3] < 0.5 &&
                        output2[0] < 0.5 &&
                        output2[1] >= 0.5 &&
                        output2[2] < 0.5 &&
                        output2[3] < 0.5 &&
                        output3[0] < 0.5 &&
                        output3[1] < 0.5 &&
                        output3[2] >= 0.5 &&
                        output3[3] < 0.5 &&
                        output4[0] < 0.5 &&
                        output4[1] < 0.5 &&
                        output4[2] < 0.5 &&
                        output4[3] >= 0.5)
                    {
                        success = true;

                        string json = JsonConvert.SerializeObject(generation.FittestGenome);

                        Debug.WriteLine("Success!");
                        Debug.WriteLine(json);
                        Debug.WriteLine(DotGraph.Get(generation.FittestGenome));
                        Debug.WriteLine(i);
                    }
                    else
                    {
                        generation = generation.Evolve(g =>
                        {
                            double error = 0;

                            Enumerable.Range(0, 4).ToList().ForEach(x =>
                            {
                                double[] bitPos = new double[] { 0, 0, 0, 0 };
                                bitPos[x]++;

                                double[] o = g.Activate(bitPos);

                                double distanceFromAnswer = 0;

                                for (int y = 0; y <= 3; y++)
                                {
                                    double r = double.IsNaN(o[y]) ? 0 : Math.Min(1, Math.Round(o[y], 4));

                                    if (y == x)
                                    {
                                        distanceFromAnswer += Math.Abs(1 - r);
                                    }
                                    else
                                    {
                                        distanceFromAnswer += Math.Abs(0 - r);
                                    }
                                }

                                error += distanceFromAnswer;
                            });

                            return(Math.Pow(Math.Max(4 - error, 0), 2));
                        });
                    }
                }
            });
        }
Exemplo n.º 53
0
 /// <summary> 
 /// Creates a new <see cref="Spring.Threading.CyclicBarrier.Parties"/> that will trip when the
 /// given number of <paramref name="parties"/> (threads) are waiting upon it, and which
 /// will execute the given barrier action when the barrier is tripped,
 /// performed by the last thread entering the barrier.
 /// </summary>
 /// <param name="parties">the number of threads that must invoke <see cref="M:Spring.Threading.CyclicBarrier.Await"/>
 /// before the barrier is tripped.
 /// </param>
 /// <param name="barrierAction">the <see cref="Spring.Threading.IRunnable"/> to execute when the barrier is
 /// tripped, or <see lang="null"/>  if there is no action.
 /// </param>
 /// <exception cref="System.ArgumentException">if <paramref name="parties"/> is less than 1.</exception>
 /// <exception cref="ArgumentNullException">if <paramref name="barrierAction"/> is null.</exception>
 public CyclicBarrier(int parties, IRunnable barrierAction)
 {
     if (parties <= 0)
     {
         throw new ArgumentException();
     }
     _parties = parties;
     _waitingPartiesCount = parties;
     _barrierCommand = barrierAction;
     _generation = new Generation();
 }
 // Start is called before the first frame update
 void Start()
 {
     GlobalGeneration = this.gameObject.GetComponent <Generation>();
     path             = Application.dataPath + "/Resources/LevelData.json";
     Debug.Log(path);
 }
Exemplo n.º 55
0
        public void new_generation_should_revive_dead_cell_with_three_alive_neighbours()
        {
            var generation = new Generation(new Cell(0, 0), new Cell(1, 0), new Cell(2, 0));

            generation.Tick().Contains(new Cell(1, 1)).Should().BeTrue();
        }
Exemplo n.º 56
0
 /// <summary> Object.GetHashCode method override. </summary>
 public override int GetHashCode()
 {
     // Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
     return(Endpoint.GetHashCode() ^ Generation.GetHashCode());
 }
Exemplo n.º 57
0
 // others
 public void SetGeneration(Generation <SnakeGA> generation)
 {
     _generationId = generation.Number;
     _individualId = generation.Population.ToList().FindIndex(i => i == this) + 1;
 }
Exemplo n.º 58
0
    public void RunGeneration(Generation generation)
    {
        if (generation == null)
        {
            throw new Exception("Null generation");
        }

        for (int y = 1; y < _mapHeight - 1; y++)
        {
            for (int x = 1; x < _mapWidth - 1; x++)
            {
                int rule1Count = 0;
                int rule2Count = 0;

                for (int i = -1; i <= 1; i++)
                {
                    for (int j = -1; j <= 1; j++)
                    {
                        if (_mapGrid [y + i] [x + j] != FALSE)
                        {
                            rule1Count++;
                        }
                    }
                }

                for (int i = y - 2; i <= y + 2; i++)
                {
                    for (int j = x - 2; j <= x + 2; j++)
                    {
                        if (Math.Abs(i - y) == 2 && Math.Abs(j - x) == 2)
                        {
                            continue;
                        }

                        if (i < 0 || j < 0 || i >= _mapHeight || j >= _mapWidth)
                        {
                            continue;
                        }

                        if (_mapGrid [i] [j] != FALSE)
                        {
                            rule2Count++;
                        }
                    }
                }

                if (rule1Count >= generation.rule1Cutoff || rule2Count <= generation.rule2Cutoff)
                {
                    _auxiliaryMapGrid [y] [x] = TRUE;
                }
                else
                {
                    _auxiliaryMapGrid [y] [x] = FALSE;
                }
            }
        }

        for (int y = 1; y < _mapHeight - 1; y++)
        {
            for (int x = 1; x < _mapWidth - 1; x++)
            {
                _mapGrid [y] [x] = _auxiliaryMapGrid [y] [x];
            }
        }
    }
Exemplo n.º 59
0
 /// <summary>
 /// Performs the selection of chromosomes from the generation specified.
 /// </summary>
 /// <returns>The selected chromosomes.</returns>
 /// <param name="number">The number of chromosomes to select.</param>
 /// <param name="generation">The generation where the selection will be made.</param>
 protected abstract IList <IChromosome> PerformSelectChromosomes(int number, Generation generation);
Exemplo n.º 60
0
        public async Task GetByIdShouldReturnCorrectCar()
        {
            var options = new DbContextOptionsBuilder <NeedForCarsDbContext>()
                          .UseInMemoryDatabase("GetByIdCarDb")
                          .Options;

            var context = new NeedForCarsDbContext(options);

            var makesService       = new MakesService(context);
            var modelsService      = new ModelsService(context, makesService);
            var generationsService = new GenerationsService(context, modelsService);
            var carsService        = new CarsService(context, generationsService);

            var make = new Make
            {
                Name        = "Make",
                Description = "Desc"
            };

            await context.Makes.AddAsync(make);

            await context.SaveChangesAsync();

            var model = new Model
            {
                MakeId = make.Id,
                Name   = "Model"
            };

            await context.Models.AddAsync(model);

            await context.SaveChangesAsync();

            var generation = new Generation
            {
                ModelId     = model.Id,
                BodyType    = Models.Enums.BodyType.Convertible,
                Name        = "Name",
                Seats       = 5,
                Description = "Desc"
            };

            await context.Generations.AddAsync(generation);

            await context.SaveChangesAsync();

            var engine = new Engine
            {
                Name     = "Name1",
                FuelType = Models.Enums.FuelType.Diesel,
                MaxHP    = 100,
                Creator  = "Creator"
            };

            await context.Engines.AddAsync(engine);

            await context.SaveChangesAsync();

            var car = new Car
            {
                Name         = "Name1",
                GenerationId = generation.Id,
                EngineId     = engine.Id,
                Transmission = Models.Enums.Transmission.Automatic,
                DriveWheel   = Models.Enums.DriveWheel.AllWheelDrive,
                BeginningOfProductionYear  = 2000,
                BeginningOfProductionMonth = 1
            };

            await context.Cars.AddAsync(car);

            await context.SaveChangesAsync();

            var result = carsService.GetById(car.Id);

            Assert.Equal("Name1", result.Name);
        }