예제 #1
0
        public void UpdateMeta(int serialLength)
        {
            BulkDataStartOffset += serialLength - Exports.First().SerialSize;
            Exports.First().SerialSize = serialLength;
            NameCount = Names.Length;
            int num  = 193;
            int num2 = 0;

            FNameEntry[] names = Names;
            foreach (FNameEntry fNameEntry in names)
            {
                num2 += fNameEntry.GetLength();
            }
            int num3 = ImportCount * 28;
            int num4 = ExportCount * 108;

            ImportOffset            = num + num2;
            ExportOffset            = num + num2 + num3;
            DependsOffset           = num + num2 + num3 + num4 - 4;
            TotalHeaderSize         = num + num2 + num3 + num4 + 4;
            AssetRegistryDataOffset = num + num2 + num3 + num4;
            PreloadDependencyOffset = TotalHeaderSize;
            Generations.First().NameCount = Names.Length;
            Exports.First().SerialOffset  = TotalHeaderSize;
        }
예제 #2
0
 // todo: instead of validating by item ID, validate by item type.
 public static bool IsItemHoldable(Generations generation, Versions version, int heldItemID)
 {
     if (generation.Equals(Generations.Generation4))
     {
         if (version.Equals(Versions.Diamond) || version.Equals(Versions.Pearl) || version.Equals(Versions.Platinum))
         {
             if (heldItemID < 1 || (heldItemID >= 113 && heldItemID <= 134) || heldItemID > 427)
             {
                 return(false);
             }
         }
         else
         {
             if (heldItemID < 1 || (heldItemID >= 113 && heldItemID <= 134) || (heldItemID >= 428 && heldItemID <= 484) || (heldItemID >= 501 && heldItemID <= 504) || heldItemID >= 532)
             {
                 return(false);
             }
         }
     }
     else if (generation.Equals(Generations.Generation5))
     {
         if (heldItemID < 1 || (heldItemID >= 113 && heldItemID <= 115) || (heldItemID >= 120 && heldItemID <= 133) || (heldItemID >= 426 && heldItemID <= 484) || (heldItemID >= 501 && heldItemID <= 503) || (heldItemID >= 532 && heldItemID <= 536) || heldItemID.Equals(574) || (heldItemID >= 578 && heldItemID <= 579) || (heldItemID >= 616 && heldItemID <= 617) || heldItemID >= 621)
         {
             return(false);
         }
     }
     return(true);
 }
예제 #3
0
        public Melody Generate()
        {
            var currentPopulation = _initializer.Initialize();

            ApplyMutationOperators(currentPopulation);
            currentPopulation.Individuals.ToList().ForEach(currentMelody => _fitnessCalculator.Calculate(_initializer.BaseMelody, currentMelody));
            Generations.Add(currentPopulation);

            while (!_stopChecker.Stop(this))
            {
                var newPopulation = _replacementOperator.Replace(currentPopulation);
                newPopulation.Individuals.ToList().ForEach(currentMelody => _fitnessCalculator.Calculate(_initializer.BaseMelody, currentMelody));
                var best = newPopulation.BestIndividual();
                Print(best, newPopulation.Sequence.ToString());
                PrintFitnessValues(best);

                Generations.Add(newPopulation);
                currentPopulation = newPopulation;
            }

            Print(_initializer.BaseMelody, "input");
            PrintFitnessValues(_initializer.BaseMelody);

            Print(BestEver, "output");
            PrintFitnessValues(BestEver);

            return(BestEver);
        }
예제 #4
0
        public void Generations_MatchesInbox()
        {
            FrameworkSet fxs        = FrameworkSet.Load("FrameworkLists");
            Version      maxVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);

            foreach (var fxGroup in fxs.Frameworks)
            {
                foreach (var fx in fxGroup.Value)
                {
                    var thisFx       = new NuGetFramework(fx.FrameworkName.Identifier, fx.FrameworkName.Version, fx.FrameworkName.Profile);
                    var fxGeneration = Generations.DetermineGenerationForFramework(thisFx, false);

                    foreach (var assembly in fx.Assemblies.Where(a => !s_classicAssemblies.Contains(a.Key) && a.Value != maxVersion))
                    {
                        _log.Reset();
                        Version assmGeneration = _generations.DetermineGenerationFromSeeds(assembly.Key, assembly.Value, _log);

                        Version effectiveFxGeneration;
                        if (!s_generationException.TryGetValue(Tuple.Create(fx.FrameworkName, assembly.Key), out effectiveFxGeneration))
                        {
                            effectiveFxGeneration = fxGeneration;
                        }

                        Assert.Equal(0, _log.ErrorsLogged);
                        Assert.Equal(0, _log.WarningsLogged);
                        Assert.True(null != assmGeneration, $"{assembly.Key},{assembly.Value} should be tracked by generations");
                        Assert.True(assmGeneration.Major >= 1 && assmGeneration.Minor >= 0);
                        Assert.True(assmGeneration <= effectiveFxGeneration, $"Generation {assmGeneration} of {assembly.Key}, {assembly.Value} must be less than or equal to {fxGeneration} since this assembly is inbox in {fx.FrameworkName} which is mapped to generation {effectiveFxGeneration}.");
                    }
                }
            }
        }
예제 #5
0
        public void blinker_oscillator_should_oscillate_according_to_wikipedia(
            int x, int y, int generationIndex, bool isAlive)
        {
            var generations = new Generations(new Cell(0, 1), new Cell(1, 1), new Cell(2, 1));

            generations[generationIndex].Contains(new Cell(x, y)).Should().Be(isAlive);
        }
예제 #6
0
        public void blinker_oscillator_should_oscillate_according_to_wikipedia(
            int x, int y, int generationIndex, bool isAlive)
        {
            var generations = new Generations(new Cell(0, 1), new Cell(1, 1), new Cell(2, 1));

            generations[generationIndex].Contains(new Cell(x, y)).Should().Be(isAlive);
        }
예제 #7
0
        public static int SpeciesAtGeneration(Generations generation)
        {
            switch (generation)
            {
            case Generations.Generation1:
                return(151);

            case Generations.Generation2:
                return(251);

            case Generations.Generation3:
                return(386);

            case Generations.Generation4:
                return(493);

            case Generations.Generation5:
                return(649);

            case Generations.Generation6:
                return(721);

            default:
                throw new NotSupportedException();
            }
        }
예제 #8
0
        /// <summary>
        ///
        /// </summary>
        public void CreateNewGeneration()
        {
            Generations[NbGeneration - 1] = Generations[NbGeneration - 1].OrderByDescending(x => x.Fitness).ToArray();
            //Checker si shallow copy
            NetworkGenome[] generationTemp = new NetworkGenome[GenerationSize];
            NetworkGenome[] elites         = GetElites(NbGeneration);

            float totalFitness = GetTotalFitness(NbGeneration);


            int indexNewGen  = 0;
            int indexPartner = -1;

            //garde lelite
            for (int i = 0; i < elites.Length && indexNewGen < GenerationSize; i++)
            {
                generationTemp[indexNewGen++] = elites[i];
            }
            //rajoute random pour diversiter
            for (int i = 0; i < (int)(LoserPercent * GenerationSize) && indexNewGen < GenerationSize; i++)
            {
                generationTemp[indexNewGen++] = new NetworkGenome(NeuralNetwork.Layout, NeuralNetwork.NbNecessaryInputs, NeuralNetwork.NetworkSize, MutationRnd, CrossOverRnd, MutationChance);
            }

            //fill avec des enfants
            while (indexNewGen < GenerationSize)
            {
                indexPartner = ChooseMateIndex(NbGeneration);
                Genome[] enfants = Generations[NbGeneration - 1][indexPartner].ProduceOffspring(Generations[NbGeneration - 1][ChooseMateIndex(NbGeneration, indexPartner)]);
                generationTemp[indexNewGen++] = (enfants[0] as NetworkGenome);
                generationTemp[indexNewGen++] = (enfants[1] as NetworkGenome);
            }

            Generations.Add(generationTemp);
        }
예제 #9
0
        public void AddNewGeneration()
        {
            var newGeneration = new List <Knapsack>();

            for (int i = 0; i < PopulationSize; i++)
            {
                var candidate = Mutate(Crossover(Select(), Select()));

                newGeneration.Add(candidate);

                var knapsackFitness     = GetKnapsackFitness(candidate);
                var bestKnapsackFitness = GetKnapsackFitness(BestOfRun);
                if (knapsackFitness > bestKnapsackFitness)
                {
                    BestOfRun        = candidate;
                    BestOfRunFitness = knapsackFitness;
                }
            }

            //Console.WriteLine(RunNumber);
            RunNumber++;
            //Console.WriteLine(BestOfRunFitness);
            CurrentGeneration = newGeneration;
            Generations.Add(newGeneration);
        }
예제 #10
0
        public static LocationNumbering GenerationToLocationNumbering(Generations generation)
        {
            switch (generation)
            {
            case Generations.Generation1:
                return(LocationNumbering.Generation1);

            case Generations.Generation2:
                return(LocationNumbering.Generation2);

            case Generations.Generation3:
                return(LocationNumbering.Generation3);

            case Generations.Generation4:
                return(LocationNumbering.Generation4);

            case Generations.Generation5:
                return(LocationNumbering.Generation5);

            case Generations.Generation6:
                return(LocationNumbering.Generation6);

            default:
                throw new ArgumentException();
            }
        }
예제 #11
0
        /// <summary>
        /// Creates a new generation.
        /// </summary>
        /// <returns>The new generation.</returns>
        /// <param name="chromosomes">Chromosomes.</param>
        public void CreateNewGeneration(IList <IChromosome> chromosomes)
        {
            ExceptionHelper.ThrowIfNull("chromosomes", chromosomes);

            CurrentGeneration = new Generation(++GenerationsNumber, chromosomes);
            Generations.Add(CurrentGeneration);
            GenerationStrategy.RegisterNewGeneration(this);
        }
        /// <summary>
        ///     Creates a new generation.
        /// </summary>
        /// <param name="genes">The genes to build the new generation of.</param>
        public virtual void CreateNewGeneration(IList <IGenome> genes)
        {
            if (genes == null)
            {
                throw new NullReferenceException(nameof(genes));
            }

            CurrentGeneration = new Generation(++NumberOfGenerations, genes);
            Generations.Add(CurrentGeneration);
        }
예제 #13
0
 /// <summary>
 ///
 /// </summary>
 public void CreateFirstGeneration()
 {
     NetworkGenome[] generationTemp = new NetworkGenome[GenerationSize];
     for (int i = 0; i < GenerationSize; i++)
     {
         generationTemp[i] = new NetworkGenome(NeuralNetwork.Layout, NeuralNetwork.NbNecessaryInputs,
                                               NeuralNetwork.NetworkSize, MutationRnd, CrossOverRnd, MutationChance, NeuralNetwork.Layers[0].Neurons[0].MinValueRand, NeuralNetwork.Layers[0].Neurons[0].MaxValueRand);
     }
     Generations.Add(generationTemp);
 }
예제 #14
0
        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            Generations.Clear();
            var generations = await _accessService.GetGenerations();

            Generations.AddRange(generations);
            WhiteGeneration = Generations[0];
            BlackGeneration = Generations[0];
        }
예제 #15
0
 public FormStats BaseStats(Generations generation)
 {
     if (m_form_stats == null)
     {
         m_form_stats = m_pokedex.FormStats(ID);
     }
     // xxx: this is O(n) and we can do O(log n) but it requires rolling
     // our own binary search and YAGNI for a list of at most 6 values.
     // http://stackoverflow.com/questions/20474896/finding-nearest-value-in-a-sorteddictionary
     return(m_form_stats.Last(pair => (int)(pair.Key) <= (int)generation).Value);
 }
        private void CheckF()
        {
            if (setF1 != setF2)
            {
                return;
            }

            ParetoPointGeneration gen = new ParetoPointGeneration();

            for (int i = 0; i < F1.Length; i++)
            {
                gen.Points.Add(new MyPoint(F1[i], F2[i]));
            }

            // pareto
            uint[] indicies = ParetoFrontFinder.FindParetoFront(F1, F2);
            ParetoIncidies = indicies.Select(n => (int)n).ToArray();
            ParetoFront.Clear();
            for (int i = 0; i < indicies.Length; i++)
            {
                ParetoFront.Add(new Point(F1[indicies[i]], F2[indicies[i]]));
            }

            // calc colors
            Generations.Add(gen);
            if (Generations.Count > maxGen)
            {
                Generations.RemoveAt(0);
            }

            for (int i = 0; i < Generations.Count; i++)
            {
                byte c = (byte)(255 - ((double)i + 1) / Generations.Count * 255);
                Generations[i].Color = new SolidColorBrush(Color.FromArgb(255, c, c, c));
                Generations[i].Size  = i == Generations.Count - 1 ? 8 : 4;
            }

            RecalculateScale();

            if (!Generations.Any())
            {
                return;
            }
            if (!Generations.Last().Points.Any())
            {
                return;
            }
            if (SelectedIndex >= Generations.Last().Points.Count)
            {
                return;
            }
            SelectedPoint = Generations.Last().Points[SelectedIndex];
        }
예제 #17
0
        public static BanStatus GetBanStatus(int pid, string IpAddress, Generations generation)
        {
            try
            {
                BanStatus pidBan     = Database.Instance.CheckBanStatus(pid);
                BanStatus ipBan      = Database.Instance.CheckBanStatus(IpAddress);
                BanStatus macBan     = null;
                BanStatus saveBan    = null;
                BanStatus ipRangeBan = null;


                try
                {
                    switch (generation)
                    {
                    case Generations.Generation4:
                    {
                        var profile = Database.Instance.GamestatsGetProfile4(pid);
                        macBan  = Database.Instance.CheckBanStatus(profile.MacAddress);
                        saveBan = Database.Instance.CheckBanStatus(profile);
                        break;
                    }

                    case Generations.Generation5:
                    {
                        var profile = Database.Instance.GamestatsGetProfile5(pid);
                        macBan  = Database.Instance.CheckBanStatus(profile.MacAddress);
                        saveBan = Database.Instance.CheckBanStatus(profile);
                        break;
                    }
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    uint ipBinary = IpAddressHelper.Ipv4ToBinary(IpAddress);
                    ipRangeBan = Database.Instance.CheckBanStatus(ipBinary);
                }
                catch (Exception)
                {
                }

                return(new[] { pidBan, ipBan, macBan, saveBan, ipRangeBan }.Where(ban => ban != null).OrderBy(ban => ban.Level).LastOrDefault());
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #18
0
        private void Initialize()
        {
            if (!Goal.All(c => char.IsLetter(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c)))
            {
                throw new ArgumentException("Для поля Goal допускаются только буквы и знаки пробела.");
            }
            if (!Origin.All(c => char.IsLetter(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c)))
            {
                throw new ArgumentException("Для поля Origin допускаются только буквы и знаки пробела.");
            }

            State = Origin;
            Generations.Add("Поколение " + Generation + ": " + State);
        }
예제 #19
0
 public void UpdateNewIteration(int startCol, int endCol)
 {
     Cell[,] Previous = Generations.Last();
     if (startCol == -1 || endCol == -1)
     {
         startCol = 0;
         endCol   = GameCols - 1;
     }
     for (int i = 0; i < GameRows; i++)
     {
         for (int j = startCol; j <= endCol; j++)
         {
             int   num  = 0;
             int[] temp = Neightbourhood(Previous, i, j);
             for (int k = 0; k < temp.Length; k++)
             {
                 if (temp[k] != -1)
                 {
                     if (temp[k] == 1)
                     {
                         num++;
                     }
                 }
             }
             if (Previous[i, j].State == 1)
             {
                 if (num == 2 || num == 3)
                 {
                     Current[i, j].State = 1;
                 }
                 else
                 {
                     Current[i, j].State = 0;
                 }
             }
             else
             {
                 if (num == 3)
                 {
                     Current[i, j].State = 1;
                 }
                 else
                 {
                     Current[i, j].State = 0;
                 }
             }
         }
     }
 }
예제 #20
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                log.Info("C# HTTP trigger function processed a request.");
                var firstGen = await Generations.GetFirstGenerationAsync(log);

                IndexService.IndexCollection(firstGen, "firstgeneration");
                return(req.CreateResponse(HttpStatusCode.OK, "Indexing completed!"));
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
예제 #21
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Surface  = (GetTemplateChild("PART_ContentHostNodes") as ItemsControl);
            Surface2 = (GetTemplateChild("PART_ContentHostLines") as ItemsControl);

            CalculateGenerations();

            Surface.Width   = Generations.Max(n => n.Nodes.Count) * HorizontalNodeSpace;
            Surface.Height  = Generations.Count * VerticalNodeSpace;
            Surface2.Width  = Surface.Width;
            Surface2.Height = Surface.Height;

            AllocateNodes(Nodes);
            AllocateLines();
        }
예제 #22
0
        private void AddToGeneration(int level, IGeneticTreeNode node)
        {
            var generation = GetGeneration(level);

            if (generation == null)
            {
                Generations.Add(new Generation()
                {
                    Level = level, Nodes = new List <IGeneticTreeNode>()
                });
                generation = GetGeneration(level);
            }
            if (!generation.Nodes.Contains(node))
            {
                AddToGeneration(generation, node);
            }
        }
        public GeneticAlgorithm(int generationsPerRun, int populationSize, double crossoverRate, double mutationRate, int lowerBound, int upperBound, int selectionStrategy, int recombinationStrategy, int mutationStrategy)
        {
            var gen1 = new List <Candidate>();

            GenerationsPerRun     = generationsPerRun;
            LowerBound            = lowerBound;
            UpperBound            = upperBound;
            PopulationSize        = populationSize;
            CrossoverRate         = crossoverRate;
            MutationRate          = mutationRate;
            CurrentGeneration     = gen1;
            SelectionStrategy     = (SelectionStrategy)selectionStrategy;
            RecombinationStrategy = (RecombinationStrategy)recombinationStrategy;
            MutationStrategy      = (MutationStrategy)mutationStrategy;
            Generations.Add(gen1);
            InitializePopulation();
        }
        private void RecalculateScale()
        {
            MyPoint[] plot1        = new MyPoint[0];
            double    actualWidth  = 0;
            double    actualHeight = 0;

            try
            {
                Dispatcher.Invoke(() =>
                {
                    plot1        = Generations.SelectMany(n => n.Points).ToArray();
                    actualWidth  = Plots.ActualWidth;
                    actualHeight = Plots.ActualHeight;
                });
            }
            catch { }

            ValueToSet valueToSet = RecalculateScale(plot1, actualWidth, actualHeight, X1, Y1);

            try
            {
                if (!valueToSet.setXY && !valueToSet.setScale)
                {
                    return;
                }

                Dispatcher.Invoke(() =>
                {
                    if (valueToSet.setXY)
                    {
                        X0 = valueToSet.x0;
                        Y0 = valueToSet.y0;
                        X1 = valueToSet.x1;
                        Y1 = valueToSet.y1;
                    }

                    if (valueToSet.setScale)
                    {
                        ScaleX = valueToSet.scaleX;
                        ScaleY = valueToSet.scaleY;
                    }
                });
            }
            catch { }
        }
예제 #25
0
        public FormStats(Pokedex pokedex, int form_id, Generations min_generation, 
            int type1, int type2, IntStatValues base_stats, ByteStatValues reward_evs)
            : base(pokedex)
        {
            m_form_pair = Form.CreatePair(m_pokedex);
            m_type1_pair = Type.CreatePair(m_pokedex);
            m_type2_pair = Type.CreatePair(m_pokedex);
            m_lazy_pairs.Add(m_form_pair);
            m_lazy_pairs.Add(m_type1_pair);
            m_lazy_pairs.Add(m_type2_pair);

            m_form_pair.Key = form_id;
            MinGeneration = min_generation;
            m_type1_pair.Key = type1;
            m_type2_pair.Key = type2;
            BaseStats = base_stats;
            RewardEvs = reward_evs;
        }
예제 #26
0
        public FormStats(Pokedex pokedex, int form_id, Generations min_generation,
                         int type1, int type2, IntStatValues base_stats, ByteStatValues reward_evs)
            : base(pokedex)
        {
            m_form_pair  = Form.CreatePair(m_pokedex);
            m_type1_pair = Type.CreatePair(m_pokedex);
            m_type2_pair = Type.CreatePair(m_pokedex);
            m_lazy_pairs.Add(m_form_pair);
            m_lazy_pairs.Add(m_type1_pair);
            m_lazy_pairs.Add(m_type2_pair);

            m_form_pair.Key  = form_id;
            MinGeneration    = min_generation;
            m_type1_pair.Key = type1;
            m_type2_pair.Key = type2;
            BaseStats        = base_stats;
            RewardEvs        = reward_evs;
        }
예제 #27
0
 public ItemData(DataRow row, Generations gen)
 {
     this.id            = (ushort)(long)row["ID"];
     this.name          = row["Name"] as string;
     this.description   = row["Description"] as string;
     this.pocketType    = ItemData.GetPocketTypeFromString(row["Pocket"] as string);
     this.subPocketType = (row["SubPocket"] is DBNull ? this.pocketType : ItemData.GetPocketTypeFromString(row["SubPocket"] as string));
     this.transferUpID  = 0;                  //(ushort)(long)row["TransferUpID"];
     this.order         = (row["Order"] is DBNull ? 0 : (int)(long)row["Order"]);
     this.price         = (uint)(long)row["Price"];
     this.sell          = (uint)(long)row["Sell"];
     this.coinsPrice    = (uint)(long)row["Coins"];
     this.bpPrice       = (uint)(long)row["BP"];
     this.pcPrice       = (uint)(long)row["PC"];
     this.sootPrice     = (uint)(long)row["Soot"];
     this.obtainable    = (bool)row["Obtainable"];
     this.important     = (bool)row["Important"];
     this.exclusives    = ItemData.GetExclusivesFromString(row["Exclusive"] as string, gen);
 }
        /// <summary>
        /// Creates a new generation.
        /// </summary>
        /// <param name="chromosomes">The chromosomes for new generation.</param>
        public virtual void CreateNewGeneration(IList <IChromosome> chromosomes)
        {
            chromosomes.ValidateGenes();                 // validate

            var distinct = chromosomes.SelectDistinct(); // select distinct

            // Make sure that chromosomes without fitness are unique in terms of
            // same gene values sequence wasn't encountered in previous generations ->
            if (GenerationsNumber > 0)
            {
                distinct.RemoveEvaluatedPreviously(Generations);
            }

            // Create new Generation from distinct (!) ->
            CurrentGeneration = new Generation(++GenerationsNumber, distinct);

            // Add to collection ->
            Generations.Add(CurrentGeneration);
        }
예제 #29
0
 public ItemData(DataRow row, Generations gen)
 {
     this.id				= (ushort)(long)row["ID"];
     this.name			= row["Name"] as string;
     this.description	= row["Description"] as string;
     this.pocketType		= ItemData.GetPocketTypeFromString(row["Pocket"] as string);
     this.subPocketType	= (row["SubPocket"] is DBNull ? this.pocketType : ItemData.GetPocketTypeFromString(row["SubPocket"] as string));
     this.transferUpID	= 0; //(ushort)(long)row["TransferUpID"];
     this.order			= (row["Order"] is DBNull ? 0 : (int)(long)row["Order"]);
     this.price			= (uint)(long)row["Price"];
     this.sell			= (uint)(long)row["Sell"];
     this.coinsPrice		= (uint)(long)row["Coins"];
     this.bpPrice		= (uint)(long)row["BP"];
     this.pcPrice		= (uint)(long)row["PC"];
     this.sootPrice		= (uint)(long)row["Soot"];
     this.obtainable		= (bool)row["Obtainable"];
     this.important		= (bool)row["Important"];
     this.exclusives		= ItemData.GetExclusivesFromString(row["Exclusive"] as string, gen);
 }
예제 #30
0
 public bool Equals(SmogonResponse?other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(GenerationPrefix == other.GenerationPrefix &&
            Generations.SetEquals(other.Generations) &&
            Pokemons.SetEquals(other.Pokemons) &&
            Formats.SetEquals(other.Formats) &&
            Natures.SetEquals(other.Natures) &&
            Abilities.SetEquals(other.Abilities) &&
            Moves.SetEquals(other.Moves) &&
            Types.SetEquals(other.Types) &&
            Items.SetEquals(other.Items));
 }
예제 #31
0
        public void Mutate(Dispatcher dispatcher = null)
        {
            // Create C mutated strings + the current parent.
            var candidates = (from child in Enumerable.Repeat(State, Children)
                              select Mutate(child, Probability))
                             .Concat(Enumerable.Repeat(State, 1));

            // Sort the strings by the fitness function.
            var sorted = from candidate in candidates
                         orderby Fitness(Goal, candidate) descending
                         select candidate;

            // New parent is the most fit candidate.
            State = sorted.First();

            Generation++;
            if (dispatcher != null)
            {
                dispatcher.Invoke(() => Generations.Add("Поколение " + Generation + ": " + State));
            }
        }
        public void Parse(BinaryReader br)
        {
            Version          = br.ReadInt32();
            HeaderSize       = br.ReadInt32();
            FolderNameLength = br.ReadInt32();
            FolderName       = Encoding.UTF8.GetString(br.ReadBytes(FolderNameLength));
            PackageFlags     = br.ReadInt32();
            NameCount        = br.ReadInt32();
            NameOffset       = br.ReadInt32();
            ExportCount      = br.ReadInt32();
            ExportOffset     = br.ReadInt32();
            ImportCount      = br.ReadInt32();
            ImportOffset     = br.ReadInt32();
            DependsOffset    = br.ReadInt32();
            SerialOffset     = br.ReadInt32();
            Unknown2         = br.ReadInt32();
            Unknown3         = br.ReadInt32();
            Unknown4         = br.ReadInt32();
            FGuid            = $"{br.ReadInt32()}.{br.ReadInt32()}.{br.ReadInt32()}.{br.ReadInt32()}";
            GenerationsCount = br.ReadInt32();

            for (int i = 0; i < GenerationsCount; i++)
            {
                var generation = new Generation();
                generation.Parse(br);
                Generations.Add(generation);
            }

            EngineVersion       = br.ReadInt32();
            CookerVersion       = br.ReadInt32();
            CompressionFlags    = br.ReadInt32();
            NumCompressedChunks = br.ReadInt32();

            for (int i = 0; i < NumCompressedChunks; i++)
            {
                var compressedChunk = new CompressedChunk();
                compressedChunk.Parse(br);
                CompressedChunks.Add(compressedChunk);
            }
        }
예제 #33
0
        public int?Value(Generations generation)
        {
            switch (generation)
            {
            case Generations.Generation1:
            case Generations.Generation2:
                throw new NotSupportedException();

            case Generations.Generation3:
                return(Value3);

            case Generations.Generation4:
                return(Value4);

            case Generations.Generation5:
                return(Value5);

            case Generations.Generation6:
            default:
                return(Value6);
            }
        }
예제 #34
0
 public FormStats BaseStats(Generations generation)
 {
     if (m_form_stats == null) m_form_stats = m_pokedex.FormStats(ID);
     // xxx: this is O(n) and we can do O(log n) but it requires rolling
     // our own binary search and YAGNI for a list of at most 6 values.
     // http://stackoverflow.com/questions/20474896/finding-nearest-value-in-a-sorteddictionary
     return m_form_stats.Last(pair => (int)(pair.Key) <= (int)generation).Value;
 }
예제 #35
0
 public GenerationsTests(ITestOutputHelper output)
 {
     _generations = Generations.Load("generations.json", false);
     _log = new Log(output);
 }
예제 #36
0
 public int? Position(Generations generation)
 {
     switch (generation)
     {
         case Generations.Generation1:
         case Generations.Generation2:
             throw new NotSupportedException();
         case Generations.Generation3:
             return Position3;
         case Generations.Generation4:
             return Position4;
         case Generations.Generation5:
             return Position5;
         case Generations.Generation6:
         default:
             return Position6;
     }
 }
예제 #37
0
 public static LocationNumbering GenerationToLocationNumbering(Generations generation)
 {
     switch (generation)
     {
         case Generations.Generation1:
             return LocationNumbering.Generation1;
         case Generations.Generation2:
             return LocationNumbering.Generation2;
         case Generations.Generation3:
             return LocationNumbering.Generation3;
         case Generations.Generation4:
             return LocationNumbering.Generation4;
         case Generations.Generation5:
             return LocationNumbering.Generation5;
         case Generations.Generation6:
             return LocationNumbering.Generation6;
         default:
             throw new ArgumentException();
     }
 }
예제 #38
0
 public int? Value(Generations generation)
 {
     switch (generation)
     {
         case Generations.Generation1:
         case Generations.Generation2:
             throw new NotSupportedException();
         case Generations.Generation3:
             return Value3;
         case Generations.Generation4:
             return Value4;
         case Generations.Generation5:
             return Value5;
         case Generations.Generation6:
         default:
             return Value6;
     }
 }
예제 #39
0
 public int? Value(Generations generation)
 {
     LocationNumbering numbering = GenerationToLocationNumbering(generation);
     return Value(numbering);
 }
예제 #40
0
 private static GameTypeFlags GetExclusivesFromString(string exclusives, Generations gen)
 {
     GameTypeFlags gameTypeFlags = GameTypeFlags.None;
     if (gen == Generations.Gen3) {
         if (exclusives == null || exclusives == "")
             return GameTypeFlags.AllGen3;
         if (exclusives.Contains('R')) gameTypeFlags |= GameTypeFlags.Ruby;
         if (exclusives.Contains('S')) gameTypeFlags |= GameTypeFlags.Sapphire;
         if (exclusives.Contains('E')) gameTypeFlags |= GameTypeFlags.Emerald;
         if (exclusives.Contains('F')) gameTypeFlags |= GameTypeFlags.FireRed;
         if (exclusives.Contains('L')) gameTypeFlags |= GameTypeFlags.LeafGreen;
         if (exclusives.Contains('C')) gameTypeFlags |= GameTypeFlags.Colosseum;
         if (exclusives.Contains('X')) gameTypeFlags |= GameTypeFlags.XD;
     }
     else if (gen == Generations.Gen2) {
         if (exclusives == null || exclusives == "")
             return GameTypeFlags.AllGen2;
         if (exclusives.Contains('G')) gameTypeFlags |= GameTypeFlags.Gold;
         if (exclusives.Contains('S')) gameTypeFlags |= GameTypeFlags.Silver;
         if (exclusives.Contains('C')) gameTypeFlags |= GameTypeFlags.Crystal;
     }
     else if (gen == Generations.Gen1) {
         if (exclusives == null || exclusives == "")
             return GameTypeFlags.AllGen1;
         if (exclusives.Contains('R')) gameTypeFlags |= GameTypeFlags.Red;
         if (exclusives.Contains('B')) gameTypeFlags |= GameTypeFlags.Blue;
         if (exclusives.Contains('Y')) gameTypeFlags |= GameTypeFlags.Yellow;
     }
     return gameTypeFlags;
 }
        public PokeManagerWindow()
        {
            this.UseLayoutRounding = true;
            PokeManager.Initialize(this);

            this.gameIndex = 0;
            this.loaded = false;
            this.gameSave = null;
            this.gen = Generations.Gen3;
            this.selectedTab = 0;

            this.timer = new DispatcherTimer();
            this.timer.Interval = TimeSpan.FromSeconds(5);
            this.timer.Tick += OnTick;
            this.timer.Start();

            #region Stuff

            /*Gen3GBAGameSave rbySave = new Gen3GBAGameSave(System.IO.Path.Combine("Saves", "Ruby Hack.sav"));

            foreach (IBlockData blockData in rbySave.MostRecentSave.BlockDataCollection) {

                if (blockData.SectionID >= SectionTypes.PCBufferA)
                    continue;
                for (int i = 0; i < SectionIDTable.GetContents(blockData.SectionID); i++) {

                    if (blockData.Raw[i] == 0x55 && blockData.Raw[i + 1] == 0x55) {
                        Console.WriteLine(i);
                        //804 NatPokedexBC (0x420)
                    }
                }
            }

            Gen3GBAGameSave frSave = new Gen3GBAGameSave(System.IO.Path.Combine("Saves", "FireRed Hack.sav"));

            foreach (IBlockData blockData in frSave.MostRecentSave.BlockDataCollection) {

                if (blockData.SectionID >= SectionTypes.PCBufferA)
                    continue;
                for (int i = 0; i < SectionIDTable.GetContents(blockData.SectionID); i++) {

                    if (blockData.Raw[i] == 0x55 && blockData.Raw[i + 1] == 0x55) {
                        Console.WriteLine(i);
                        //100 NatPokedexBC
                        //3940 TeamAndItems (Save == 3968) 3940-132=3808
                    }
                }
            }*/

            /*Dictionary<SectionTypes, List<DifferenceData>> differenceData = new Dictionary<SectionTypes, List<DifferenceData>>();

            foreach (SectionTypes sectionType in Enum.GetValues(typeof(SectionTypes))) {
                IBlockData least = emSave.LeastRecentSave.BlockDataCollection.GetBlockData(sectionType);
                IBlockData most = emSave.MostRecentSave.BlockDataCollection.GetBlockData(sectionType);
                differenceData.Add(sectionType, new List<DifferenceData>());

                DifferenceData difference = null;
                for (int i = 0; i < SectionIDTable.GetContents(sectionType); i++) {
                    if (least.Raw[i] != most.Raw[i]) {
                        if (difference == null)
                            difference = new DifferenceData(i);
                        else
                            difference.Length++;
                    }
                    else if (difference != null) {
                        differenceData[sectionType].Add(difference);
                        difference = null;
                    }
                }
            }*/

            /*int saveIndex = 0;
            while (saveIndex != -1) {
                BlockDataCollection bdcLeast = emSave.LeastRecentSave.BlockDataCollection;
                BlockDataCollection bdcMost = emSave.MostRecentSave.BlockDataCollection;
                Console.WriteLine(saveIndex);
                emSave.Save(System.IO.Path.Combine("Saves", "Tests", saveIndex.ToString() + ".sav"));
                saveIndex++;
                emSave = new Gen3GBAGameSave(System.IO.Path.Combine("Saves", "POKEMON EMER-7b058a7aea5bfbb352026727ebd87e17.sav"));
            }*/

            /*Dictionary<string, GameTypes> gameTypeTable = new Dictionary<string, GameTypes>() {
                {"RUBY", GameTypes.Ruby},
                {"SAPP", GameTypes.Sapphire},
                {"EMER", GameTypes.Emerald},
                {"FIRE", GameTypes.FireRed},
                {"LEAF", GameTypes.LeafGreen}
            };
            string[] files = Directory.GetFiles("Saves");
            foreach (string file in files) {
                foreach (KeyValuePair<string, GameTypes> pair in gameTypeTable) {
                    if (System.IO.Path.GetFileName(file).Contains(pair.Key) && System.IO.Path.GetExtension(file) == ".sav") {
                        PokeManager.AddGameSave(file, pair.Value);
                    }
                }
            }*/
            /*PokeManager.AddGameSave(System.IO.Path.Combine("Saves", "01-GC6E-pokemon_colosseum.gci"));
            PokeManager.AddGameSave(System.IO.Path.Combine("Saves", "01-GC6E-pokemon_colosseum1.gci"));
            PokeManager.AddGameSave(System.IO.Path.Combine("Saves", "01-GC6E-pokemon_colosseum2.gci"));
            PokeManager.AddGameSave(System.IO.Path.Combine("Saves", "01-GC6E-pokemon_colosseum3.gci"));*/

            #endregion

            InitializeComponent();

            UpdateSettingsMenuItems();

            this.loaded = true;

            if (PokeManager.Settings.DefaultStartupSize.Width != 0 && PokeManager.Settings.DefaultStartupSize.Height != 0) {
                this.Width = PokeManager.Settings.DefaultStartupSize.Width;
                this.Height = PokeManager.Settings.DefaultStartupSize.Height;
            }

            PokeManager.IsReloading = true;
            LoadGame(PokeManager.Settings.IsValidDefaultGame ? PokeManager.Settings.DefaultGame : -1);
            PokeManager.IsReloading = false;

            if (((TabItem)tabControl.Items[PokeManager.Settings.DefaultStartupTab]).Visibility == Visibility.Visible)
                Dispatcher.BeginInvoke((Action)(() => tabControl.SelectedIndex = PokeManager.Settings.DefaultStartupTab));

            if (!PokeManager.IsAprilFoolsDay)
                menuItemAprilFoolsMode.Visibility = Visibility.Collapsed;
        }