Exemplo n.º 1
0
        public Maze Load()
        {
            var maze = new Maze();
            var inputFile = File.ReadAllLines(arguments[0]);

            //Load in headings
            maze.grid_x = int.Parse(inputFile[0].Split(' ')[0]);
            maze.grid_y = int.Parse(inputFile[0].Split(' ')[1]);
            maze.start_x = int.Parse(inputFile[1].Split(' ')[0]);
            maze.start_y = int.Parse(inputFile[1].Split(' ')[1]);
            maze.end_x = int.Parse(inputFile[2].Split(' ')[0]);
            maze.end_y = int.Parse(inputFile[2].Split(' ')[1]);

            maze.mazeLayout = new Tile[maze.grid_x, maze.grid_y];
            for (var i = 3; i < inputFile.Length; i++)
            {
                //Assuming single space
                var inputMazeColumn = inputFile[i].Split(' ');
                for (var j = 0; j < inputMazeColumn.Length; j++)
                {
                    TileType type = inputMazeColumn[j] == "0" ? TileType.FreeSpace : TileType.Wall;
                    //Minus 3 to cater for the header rows
                    maze.mazeLayout[i - 3, j] = new Tile(type);
                }
            }
            return maze;
        }
Exemplo n.º 2
0
 public void Setup()
 {
     inputMaze = CreateTestMaze();
     expectedMaze = CreateTestMaze();
     expectedMaze.mazeLayout[1, 1].SolutionPath = true;
     expectedMaze.mazeLayout[1, 2].SolutionPath = true;
     expectedMaze.mazeLayout[1, 3].SolutionPath = true;
     expectedMaze.mazeLayout[2, 3].SolutionPath = true;
     expectedMaze.mazeLayout[3, 3].SolutionPath = true;
     expectedMaze.mazeLayout[4, 3].SolutionPath = true;
 }
Exemplo n.º 3
0
 private bool TestSolutionPath(Maze expected, Maze actual)
 {
     for (var i = 0; i < expected.grid_x; i++)
     {
         for (var j = 0; j < expected.grid_y; j++)
         {
             if (expected.mazeLayout[i, j].SolutionPath != actual.mazeLayout[i, j].SolutionPath)
                 return false;
         }
     }
     return true;
 }
Exemplo n.º 4
0
        public Maze Solve(Maze maze)
        {
            localMaze = maze;
            var closedTiles = new List<Cell>();
            var openedTiles = new List<Cell>();
            openedTiles.Add(new Cell(localMaze.start_x,localMaze.start_y));

            while (openedTiles.Count > 0)
            {
                //Pop the first value
                Cell cell = openedTiles.OrderByDescending(o => o.F).First();
                openedTiles.Remove(cell);

                closedTiles.Add(cell);

                if (cell.X == localMaze.end_x && cell.Y == localMaze.end_y)
                {
                    //Found the end!
                    //Now to unravel the trace
                    MarkUpTheSolution(cell);
                    break;
                }

                var adjCells = GetAdjacentTiles(cell.X, cell.Y);
                foreach (var adjCell in adjCells)
                {
                    if (localMaze.mazeLayout[adjCell.X,adjCell.Y].Type != TileType.Wall && !closedTiles.Contains(adjCell))
                    {
                        if (openedTiles.Contains(adjCell))
                        {
                            if (adjCell.G > cell.G + 10)
                            {
                                UpdateCell(adjCell, cell);
                            }
                        }
                        else
                        {
                            UpdateCell(adjCell, cell);
                            openedTiles.Add(adjCell);
                        }
                    }
                }
            }

            return localMaze;
        }
Exemplo n.º 5
0
        public Maze Solve(Maze maze)
        {
            localMaze = maze;
            //Object to keep track of the path
            trace = new List<Cell>();

            if (!Search(localMaze.start_x, localMaze.start_y))
            {
                //Couldn't find the end
                throw new ApplicationException("Could not solve the maze");
            }

            //Unwind the trace
            foreach (var cell in trace)
            {
                maze.mazeLayout[cell.X, cell.Y].SolutionPath = true;
            }
            maze.mazeLayout[maze.end_x, maze.end_y].SolutionPath = true;

            return localMaze;
        }
Exemplo n.º 6
0
        private Maze CreateTestMaze()
        {
            var maze = new Maze();
            maze.grid_x = 6;
            maze.grid_y = 5;
            maze.start_x = 1;
            maze.start_y = 1;
            maze.end_x = 4;
            maze.end_y = 3;
            maze.mazeLayout = new Tile[,]
                {
                    { new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall)},
                    { new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.FreeSpace), new Tile(TileType.FreeSpace), new Tile(TileType.Wall)},
                    { new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall)},
                    { new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall)},
                    { new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall), new Tile(TileType.FreeSpace), new Tile(TileType.Wall)},
                    { new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall), new Tile(TileType.Wall)}
                };

            return maze;
        }
        public IHttpActionResult Post([FromBody] string map)
        {
            try
            {
                var lines = (map ?? string.Empty).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length < 1)
                {
                    return(BadRequest("Invalid maze"));
                }

                var maze       = new Solver.Maze(lines);
                var solver     = new Solver.MazeSolver();
                var solvedMaze = solver.Walk(maze);
                return(solvedMaze == null
                    ? Ok(new { steps = solver.Steps, solution = "No solution found" })
                    : Ok(new { steps = solver.Steps, solution = solvedMaze.ToString() }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            string directory = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

            for (int i = 0; i < 3; i++)
            {
                directory = Directory.GetParent(directory).FullName;
            }
            string sourceFile = directory + @"\RPAMaze.txt";

            StreamReader sr = File.OpenText(sourceFile);

            //reading height and width
            string singleLine = sr.ReadLine();

            string[] heightAndWidth = singleLine.Split(' ');
            int      height         = Int32.Parse(heightAndWidth[0]);
            int      width          = Int32.Parse(heightAndWidth[1]);
            Maze     maze           = new Maze(width, height);

            //parsing file line by line
            for (int row = 0; (singleLine = sr.ReadLine()) != null; row++)
            {
                int col = 0;
                foreach (char c in singleLine)
                {
                    if (c != ' ')
                    {
                        maze.array[row, col++] = c - '0';

                        if (c == '2')
                        {
                            maze.SetCurrent(new Point(row, col - 1));
                            //Console.WriteLine("Start position is (" + row + "," + (col - 1) + ")");
                        }
                    }
                }
            }

            Console.Write("Hello. Would you like to select a custom starting position? Type \"yes\" or \"no\": ");
            string customStartAnswer = Console.ReadLine();

            if (customStartAnswer.ToUpper() == "YES")
            {
                Console.WriteLine("Please select a starting position (and remember - index starts at 0): ");
                int newStartCol, newStartRow;
                do
                {
                    Console.Write("Row: ");
                    Int32.TryParse(Console.ReadLine(), out newStartRow);
                    Console.Write("Column: ");
                    Int32.TryParse(Console.ReadLine(), out newStartCol);
                } while (maze.SetNewCurrent(new Point(newStartRow, newStartCol)) != 0);
            }

            Console.WriteLine("Your starting position is (" + maze.current.X + "," + maze.current.Y + ")");

            maze.Print();
            maze.Solve();
            Console.WriteLine("The path was saved to Result.txt. Thanks for playing :)");

            string result = directory + @"\Log.txt";

            //creating Result.txt file
            string mazePrint = "";

            for (int r = 0; r < width; r++)
            {
                for (int c = 0; c < height; c++)
                {
                    if (maze.array[r, c] == 3)
                    {
                        mazePrint += "* ";
                    }
                    else
                    {
                        mazePrint += maze.array[r, c] + " ";
                    }
                }

                mazePrint += Environment.NewLine;
            }

            File.WriteAllText(result, "The path is marked with *" + Environment.NewLine);
            File.AppendAllText(result, mazePrint);
        }
        public string SolveMaze()
        {
            MazeStack = new Stack <MazeCell>();
            MazeCell exitCell    = new MazeCell();
            MazeCell entryCell   = new MazeCell();
            MazeCell currentCell = new MazeCell();

            for (int y = 0; y < Maze.GetLength(0); y++)
            {
                for (int x = 0; x < Maze.GetLength(1); x++)
                {
                    if (Maze[y, x] == 'm')
                    {
                        entryCell.Y = y;
                        entryCell.X = x;

                        currentCell.Y = y;
                        currentCell.X = x;
                    }

                    else if (Maze[y, x] == 'e')
                    {
                        exitCell.Y = y;
                        exitCell.X = x;
                    }
                }
            }

            while (exitCell.X != currentCell.X || exitCell.Y != currentCell.Y)
            {
                if (Maze[currentCell.Y, currentCell.X] == '0')
                {
                    Maze[currentCell.Y, currentCell.X] = '.';
                }

                if (Maze[currentCell.Y - 1, currentCell.X] == '0' || Maze[currentCell.Y - 1, currentCell.X] == 'e')
                {
                    MazeStack.Push(new MazeCell(currentCell.X, currentCell.Y - 1));
                }

                if (Maze[currentCell.Y + 1, currentCell.X] == '0' || Maze[currentCell.Y + 1, currentCell.X] == 'e')
                {
                    MazeStack.Push(new MazeCell(currentCell.X, currentCell.Y + 1));
                }

                if (Maze[currentCell.Y, currentCell.X - 1] == '0' || Maze[currentCell.Y, currentCell.X - 1] == 'e')
                {
                    MazeStack.Push(new MazeCell(currentCell.X - 1, currentCell.Y));
                }

                if (Maze[currentCell.Y, currentCell.X + 1] == '0' || Maze[currentCell.Y, currentCell.X + 1] == 'e')
                {
                    MazeStack.Push(new MazeCell(currentCell.X + 1, currentCell.Y));
                }

                if (MazeStack.Count == 0)
                {
                    return("The exit can't be reached!");
                }

                else
                {
                    currentCell = MazeStack.Pop();
                }
            }

            return("The exit has been reached!");
        }
 public MazeWalkerFitness(Maze maze)
 {
     this.maze = maze;
 }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            int choice;
            string filename;
            string outFilename;

            while (true)
            {
                while (true)
                {
                    Console.Write("Enter input File Name: inputFile[.png or .bmp or .jpg]\n\n");
                    filename = Console.ReadLine();
                    Console.Write("\n");
                    if (filename.EndsWith(".bmp") || filename.EndsWith(".png") || filename.EndsWith(".jpg")) { }
                    else
                    {
                        Console.Write("Argument has invalid file type\n");
                        continue;
                    }
                    Console.Write("Enter output File Name: outputFile[.png or .bmp or .jpg]\n\n");
                    outFilename = Console.ReadLine();
                    Console.Write("\n");
                    if (filename.Equals(outFilename))
                    {
                        Console.Write("File already exists, Please try a different file names \n\n");
                        continue;
                    }
                    if (outFilename.EndsWith(".bmp") || outFilename.EndsWith(".png") || outFilename.EndsWith(".jpg")) { break;}
                    else
                    {
                        Console.Write("Argument has invalid file type\n");
                        continue;
                    }

                }
                while (true)
                {
                    Console.Write("Enter Algorithm choice:  [ '1' for A* and '2' for Mccurdy]\n\n");
                    choice = int.Parse(Console.ReadLine());
                    Console.Write("\n");
                    if (choice > 2 || choice < 1)
                    {
                        Console.Write("Please choose one of the valid choices \n\n");
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

                if (outFilename.EndsWith(".bmp"))
                    {
                        BMP output = new BMP(filename, outFilename);

                        Maze M = new Maze(output, choice);
                        M.solveMaze();
                        output.setOutImage(M.img);
                        output.Save();

                    }
                else if (outFilename.EndsWith(".png"))
                    {
                        PNG output = new PNG(filename, outFilename);

                        Maze M = new Maze(output, choice);
                        M.solveMaze();
                        output.setOutImage(M.img);
                        output.Save();

                    }
                else if (outFilename.EndsWith(".jpg"))
                    {
                        JPG output = new JPG(filename, outFilename);

                        Maze M = new Maze(output, choice);
                        M.solveMaze();
                        output.setOutImage(M.img);
                        output.Save();

                    }
                while (true)
                {
                    Console.Write("Want to solve another maze? yes or no\n\n");
                    string answer = Console.ReadLine();
                    Console.Write("\n");
                    if (answer == "yes") { break; }
                    else if (answer == "no")
                    {
                        Environment.Exit(0);
                    }
                    else
                    {
                        Console.Write("Please type 'yes' or 'no'\n\n");
                    }

                }
            }
        }
Exemplo n.º 12
0
 public Solver(Maze maze, Cell end)
 {
     this.maze   = maze;
     this.end    = end;
     end.IsFinal = true;
 }
Exemplo n.º 13
0
        public void Solve(Maze maze)
        {
            const int   NumberOfGenes = 5000;
            const float MutationRate  = 0.02f;
            const float CrossOverRate = 0.6f;
            var         selection     = new EliteSelection();
            var         crossover     = new UniformCrossover();
            var         mutation      = new UniformMutation(true);
            var         chromosome    = new MazeSolverChromosome(NumberOfGenes);
            var         reinsertion   = new ElitistReinsertion();
            var         population    = new Population(50, 100, chromosome);
            var         fitness       = new MazeWalkerFitness(maze);
            IChromosome best          = chromosome;

            best.Fitness = fitness.Evaluate(best);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ga.MutationProbability = MutationRate;
            ga.Reinsertion         = reinsertion;
            ga.Termination         = new OrTermination(
                new FitnessStagnationTermination(this.stagnationThreshold),
                new TimeEvolvingTermination(TimeSpan.FromSeconds(this.maxRunTimeInSeconds)));
            ga.CrossoverProbability = CrossOverRate;
            ga.TaskExecutor         = new SmartThreadPoolTaskExecutor()
            {
                MinThreads = Environment.ProcessorCount,
                MaxThreads = Environment.ProcessorCount
            };
            ga.GenerationRan += (sender, eventargs) =>
            {
                if (this.generateUpdateImages)
                {
                    if (ga.GenerationsNumber == 1 || ga.GenerationsNumber % this.updateImageFrequency == 0)
                    {
                        var winnerSteps = FillMazeStepsWalked(maze, ga.BestChromosome);
                        ImageDraw(winnerSteps, $"gen{ga.GenerationsNumber}.png");
                    }
                }
                if (ga.GenerationsNumber % 10 == 0)
                {
                    Console.WriteLine(
                        $"{ga.GenerationsNumber} generations completed. Best fitness: {ga.BestChromosome.Fitness}.  Best so far: {best.Fitness}. Time evolving: {ga.TimeEvolving.TotalMinutes} min.");
                }

                if (ga.BestChromosome.Fitness > best.Fitness)
                {
                    best = ga.BestChromosome.Clone();

                    // ga.Population.CurrentGeneration.Chromosomes.Add(best);
                }
            };
            ga.TerminationReached += (sender, eventargs) =>
            {
                Console.WriteLine($"Termination Reached");
                var winnerSteps = FillMazeStepsWalked(maze, best);
                ImageDraw(winnerSteps, "best.png");

                var serializer = new XmlSerializer(typeof(string[]));
                using (var sw = new StreamWriter("bestchromosome.xml"))
                {
                    serializer.Serialize(sw, best.GetGenes().Select(g => g.Value as string).ToArray());
                }

                if (this.animate)
                {
                    File.Delete("output.gif");
                    this.gif.Save("output.gif");
                }
            };

            if (this.generateUpdateImages)
            {
                this.ImageDraw(maze, "gen0.png");
            }

            ga.Start();
        }
Exemplo n.º 14
-1
        public void Show(Maze maze)
        {
            StringBuilder outputMaze = new StringBuilder();

            for (var i = 0; i < maze.grid_x; i++)
            {
                for (var j = 0; j < maze.grid_y; j++)
                {
                    if (i == maze.start_x && j == maze.start_y)
                    {
                        outputMaze.Append("S");
                    }
                    else if (i == maze.end_x && j == maze.end_y)
                    {
                        outputMaze.Append("E");
                    }
                    else if (maze.mazeLayout[i, j].Type == TileType.Wall)
                    {
                        outputMaze.Append("#");
                    }
                    else if (maze.mazeLayout[i, j].SolutionPath)
                    {
                        outputMaze.Append("X");
                    }
                    else
                    {
                        outputMaze.Append(" ");
                    }
                }
                //Move to the next row
                outputMaze.Append(Environment.NewLine);
            }

            Console.WriteLine(outputMaze.ToString());
        }