示例#1
0
        private static void Solve(ISolver solver, FlowerzGame game)
        {
            var board = TranslateToSolverBoard(game.Board);
            var queue = TranslateToPiecesQueue(game.Queue);

            var ct = CancellationTokenSource.Token;

            solver.CancellationTokenSource = CancellationTokenSource;

            solver.SolutionCreated += solver_SolutionCreated;

            try {
                Task.Factory.StartNew(ListenForEscape);
                _start = DateTime.Now;
                Task.Factory.StartNew(() => {
                    var solution = solver.Solve(board, queue);

                    OpenMovesStreamWriter();
                    board.Reset();
                    board.BoardChanged += WriteMoveToFile;
                    board.ApplyMoveList(solution);
                    board.Reset();
                    CloseMovesStreamWriter();

                    WriteBestSolution(solution);
                    var totalTime = DateTime.Now.Subtract(_start);
                    Console.WriteLine("Finished in {0}.", totalTime.ToString("G", new CultureInfo("nl-Nl")));
                    Console.WriteLine("Done. Press enter to finish ");
                    Console.ReadLine();
                }, CancellationTokenSource.Token).Wait(ct);
            } catch (OperationCanceledException e) {
                Console.WriteLine("Operation was canceled. Writing current best solution to file.");

                var currentBest = solver.GetCurrentBest;
                OpenMovesStreamWriter();
                board.Reset();
                board.BoardChanged += WriteMoveToFile;
                board.ApplyMoveList(currentBest);
                board.Reset();
                CloseMovesStreamWriter();

                var lastsolution = solver.LastGeneratedSolution;
                Console.WriteLine(lastsolution.ToImportableString());

                WriteBestSolution(currentBest);
                Console.WriteLine("Press enter to close.");
                Console.ReadLine();
            } catch (AggregateException e) {
                foreach (var v in e.InnerExceptions)
                {
                    Console.WriteLine(e.Message + " " + v.Message);
                }
            } finally {
                CancellationTokenSource.Dispose();
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || args[0] == null)
            {
                PrintUsage();
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
                return;
            }

            var fileLocation = args[0];

            if (File.Exists(fileLocation))
            {
                var game = FlowerzGame.CreateGameFromFile(fileLocation);

                using (var bw = new BinaryWriter(File.Open(@"C:\tmp\flowerzsolution.sol", FileMode.OpenOrCreate))) {
                    var builder = new SavegameBuilder(game);
                    var bytes   = builder.ToByteArray();

                    foreach (var b in bytes)
                    {
                        bw.Write(b);
                    }

                    bw.Flush();
                    bw.Close();
                }
                Console.WriteLine("File created.");
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("No file found at '{0}' ", fileLocation);
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadLine();
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || args[0] == null)
            {
                PrintUsage();
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
                return;
            }

            _solverType = GetCharInput(@"Please select search mode. Default: Genetic Algorithm
1. Depth First Search
2. Genetic Algorithm", new Dictionary <int, SolverType> {
                { 1, SolverType.DepthFirstSearch },
                { 2, SolverType.GeneticAlgorithm }
            }, SolverType.GeneticAlgorithm);

            var fileLocation = args[0];

            _solutionFilename = "Solution" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt";
            _movesFilename    = "Solution" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-moves.txt";

            if (File.Exists(fileLocation))
            {
                var game = FlowerzGame.CreateGameFromFile(fileLocation);

                if (_solverType == SolverType.GeneticAlgorithm)
                {
                    var solver = SolverFactory.GetGeneticAlgorithmSolver();

                    solver.GenerationCreated += gasolver_GenerationCreated;
                    solver.SolverCreated     += gasolver_SolverCreated;

                    GeneticAlgorithmOptions.PopulationSize = GetNumberInput($"What should the size of the population be? Default: {DefaultPopulationSize}", DefaultPopulationSize);
                    GeneticAlgorithmOptions.NumberOfGenerationsToCreate = GetNumberInput($"How many generations should be created? Default: {DefaultNumberOfGenerations}", DefaultNumberOfGenerations);
                    GeneticAlgorithmOptions.CrossOverChance             = GetNumberInput($"How big should the chance be to select the crossover operation? Default: {DefaultCrossoverChance}%", DefaultCrossoverChance);
                    GeneticAlgorithmOptions.MutationChance = GetNumberInput($"How big should the chance be that a mutation occurs? Default: {DefaultMutationChance}%", DefaultMutationChance);

                    var useGaImporttxt = GetCharInput(@"Use GA_Import.txt? Default: True
1. Yes
2. No", new Dictionary <int, bool> {
                        { 1, true },
                        { 2, false }
                    }, true);

                    if (useGaImporttxt)
                    {
                        if (File.Exists(GaImportFileName))
                        {
                            Console.WriteLine("Importing existing solutions . . .");
                            var numberOfImportedSolutions = 0;
                            using (var sr = new StreamReader(new FileStream(GaImportFileName, FileMode.Open))) {
                                string s;
                                while ((s = sr.ReadLine()) != null)
                                {
                                    solver.ImportMovelist(s);
                                    numberOfImportedSolutions++;
                                }
                            }
                            Console.WriteLine(numberOfImportedSolutions + " solutions imported");
                        }
                        else
                        {
                            Console.WriteLine("Unable to import solutions. Could not find file '" + GaImportFileName + "'.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Not importing solutions");
                    }

                    Console.WriteLine(GeneticAlgorithmOptions);
                    solver.GeneticAlgorithmOptions = GeneticAlgorithmOptions;
                    Solve(solver, game);
                }
                else if (_solverType == SolverType.DepthFirstSearch)
                {
                    DepthFirstSearchOptions.SearchRandomly = GetCharInput(@"Use random search? Default: no
1. Yes
2. No", new Dictionary <int, bool> {
                        { 1, true },
                        { 2, false }
                    }, false);
                    var solver = SolverFactory.GetDfsSolver();
                    solver.SearchOptions = DepthFirstSearchOptions;
                    Solve(solver, game);
                }
                else
                {
                    Console.WriteLine("No mode specified. Exiting.");
                    Console.WriteLine("Press any key to continue . . . ");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("No file found at '{0}' ", fileLocation);
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadLine();
            }
        }
 public SavegameBuilder(FlowerzGame game)
 {
     _game = game;
 }
示例#5
0
        public static void Main(string[] args)
        {
            if (args[0] == null)
            {
                Console.WriteLine("No mode specified. Specify any of the following:");
                Console.WriteLine("1. -c [filename] => Creates a save game file based on the data in the file.");
                Console.WriteLine("2. -s [filename] [-l] [-popSize:N] [-numGen:N] [-solutions:[filename]] [-shovel] => Solve the puzzle with as many squares left over as possible.");
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
                return;
            }
            if (args[1] == null)
            {
                Console.WriteLine("No file specified as second parameter. Please supply a full path as second parameter.");
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
                return;
            }

            foreach (var arg in args)
            {
                if (arg.Contains("-l"))
                {
                    _createDiagLogs = true;
                }

                if (arg.Contains("-shovel"))
                {
                    _solveForShovel = true;
                }

                if (arg.Contains("-popSize") || arg.Contains("-numGen") || arg.Contains("-solutions"))
                {
                    var kvl = arg.Split(':');
                    ProcessArgument(kvl[0], kvl[1]);
                }
            }

            if (_solveForShovel)
            {
                Console.WriteLine("Solving this with shovel. This could take exceptionally long.");
            }
            else
            {
                Console.WriteLine("Not solving for the shovel");
            }

            var mode         = args[0];
            var fileLocation = args[1];

            if (_createDiagLogs)
            {
                _geneticLogFilename   = "GeneticLog" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt";
                _crossoverlogFilename = "CrossoverHistoryLog" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt";
                Console.WriteLine("Genetic log stored at " + _geneticLogFilename);
                Console.WriteLine("Crossover log stored at " + _crossoverlogFilename);
            }

            _solutionFilename = "Solution" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt";
            _movesFilename    = "Solution" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-moves.txt";

            if (File.Exists(fileLocation))
            {
                var game = FlowerzGame.CreateGameFromFile(fileLocation);

                if (mode == "-c")
                {
                    using (var bw = new BinaryWriter(File.Open(@"C:\tmp\flowerzsolution.sol", FileMode.OpenOrCreate))) {
                        var builder = new SavegameBuilder(game);
                        var bytes   = builder.ToByteArray();
                        foreach (var b in bytes)
                        {
                            bw.Write(b);
                        }
                        bw.Flush();
                        bw.Close();
                    }
                    Console.WriteLine("File created.");
                    Console.WriteLine("Press any key to continue . . .");
                    Console.ReadLine();
                }
                else if (mode == "-s")
                {
                    //Solve
                    var solver   = SolverFactory.GetSolver(SolverType.GeneticAlgorithm);
                    var gasolver = solver as Flowerz.Solver.GA.Solver;
                    if (gasolver != null)
                    {
                        gasolver.GenerationCreated += gasolver_GenerationCreated;
                        gasolver.MovelistCreated   += GasolverMovelistCreated;
                        gasolver.CrossoverSelected += gasolver_CrossoverSelected;
                        gasolver.SolverCreated     += gasolver_SolverCreated;
                        gasolver.SolveForShovel     = _solveForShovel;

                        if (_passedPopulationSize.HasValue)
                        {
                            Console.WriteLine("Population size = " + _passedPopulationSize.Value + ".");
                            gasolver.PopulationSize = _passedPopulationSize.Value;
                        }

                        if (_passedNumberOfGenerations.HasValue)
                        {
                            Console.WriteLine("Algorithm will terminate after " + _passedNumberOfGenerations.Value + " generations");
                            gasolver.NumberOfGenerationsToCreate = _passedNumberOfGenerations.Value;
                        }

                        if (_passedFileNameWithSolution != null)
                        {
                            if (File.Exists(_passedFileNameWithSolution))
                            {
                                Console.WriteLine("Importing existing solutions . . .");
                                var numberOfImportedSolutions = 0;
                                using (var sr = new StreamReader(new FileStream(_passedFileNameWithSolution, FileMode.Open))) {
                                    string s;
                                    while ((s = sr.ReadLine()) != null)
                                    {
                                        gasolver.ImportMovelist(s);
                                        numberOfImportedSolutions++;
                                    }
                                }
                                Console.WriteLine(numberOfImportedSolutions + " solutions imported");
                            }
                            else
                            {
                                Console.WriteLine("Unable to import solutions. Could not find file '" + _passedFileNameWithSolution + "'.");
                            }
                        }
                    }

                    var board    = TranslateToSolverBoard(game.Board);
                    var queue    = TranslateToPiecesQueue(game.Queue);
                    var solution = solver.Solve(board, queue);
                    board.BoardChanged += board_BoardChanged;
                    board.ApplyMoveList(solution);
                    board.Reset();

                    using (var sw = new StreamWriter(_solutionFilename, true)) {
                        Console.WriteLine("Leftover spaces after applying solution = " + solution.Score);
                        Console.WriteLine(@"    A  B  C  D  E  F  G");
                        Console.WriteLine(@"01 __ __ __ __ __ __ __");
                        Console.WriteLine(@"02 __ __ __ __ __ __ __");
                        Console.WriteLine(@"03 __ __ __ __ __ __ __");
                        Console.WriteLine(@"04 __ __ __ __ __ __ __");
                        Console.WriteLine(@"05 __ __ __ __ __ __ __");
                        Console.WriteLine(@"06 __ __ __ __ __ __ __");
                        Console.WriteLine(@"07 __ __ __ __ __ __ __");
                        sw.WriteLine("Leftover spaces after applying solution = " + solution.Score);
                        sw.WriteLine(@"    A  B  C  D  E  F  G");
                        sw.WriteLine(@"01 __ __ __ __ __ __ __");
                        sw.WriteLine(@"02 __ __ __ __ __ __ __");
                        sw.WriteLine(@"03 __ __ __ __ __ __ __");
                        sw.WriteLine(@"04 __ __ __ __ __ __ __");
                        sw.WriteLine(@"05 __ __ __ __ __ __ __");
                        sw.WriteLine(@"06 __ __ __ __ __ __ __");
                        sw.WriteLine(@"07 __ __ __ __ __ __ __");
                        Console.WriteLine(solution.ToString());
                        sw.WriteLine();
                        sw.WriteLine();
                        sw.WriteLine("You can use the following line to import this solution into a new run");

                        for (var i = 0; i < solution.Count; i++)
                        {
                            if (solution[i].Piece.Type == PieceType.Flower || solution[i].Piece.Type == PieceType.Butterfly)
                            {
                                if (i == 0)
                                {
                                    sw.Write(solution.Score + "|");
                                }
                                if (i <= solution.Count - 2)
                                {
                                    sw.Write(solution[i] + ";");
                                }
                                else
                                {
                                    sw.Write(solution[i]);
                                }
                            }
                        }

                        sw.Flush();
                        sw.Close();
                    }
                    Console.WriteLine("Solution stored at " + _solutionFilename);
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Invalid mode specified. Please use -s or -c");
                    Console.WriteLine("Press any key to continue . . .");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("File not found:" + fileLocation);
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadLine();
            }
        }