public MazeSolution Solve(int searchType) { const string ERROR_MESSAGE = "This maze has no solution!"; var solutionPath = new List <int>(); //stores indices of cells that are part of the solution path if (searchType == 0) { bool solutionResult = IsEndIndexReachedRecursive(myMaze.StartIndex, solutionPath); if (!solutionResult) { throw new InvalidOperationException(ERROR_MESSAGE); } } else { solutionPath = TraverseUntilEndIndex(); if (solutionPath == null) { throw new InvalidOperationException(ERROR_MESSAGE); } } solutionPath.Reverse(); //the Solution path cells are stored in backward order, we need to reverse it string mapWithSolution = BuildMapWithSolution(solutionPath); MazeSolution solution = new MazeSolution(solutionPath.Count, mapWithSolution); return(solution); }
public JObject Solve(string mazeName, int typeOfSearch) { MazeSolution sol = model.Solve(mazeName, typeOfSearch); JObject obj = JObject.Parse(sol.ToJSON()); return(obj); }
/// <summary> /// Solves the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public MazeSolution SolveMaze(SolveRequest request) { // if there is a maze with this name if (!mazes.ContainsKey(request.MazeName)) { throw new InvalidOperationException(string.Format("There is no maze with the name \"{0}\"", request.MazeName)); } // if solution exists in the cache if (solutionCache.ContainsKey(request.MazeName)) { return(solutionCache[request.MazeName]); } // initialize the search components MazeAdapter adapter = new MazeAdapter(mazes[request.MazeName]); ISearcher <Position> algorithm = GetAlgorithm(request.Algorithm); // search for the solution Solution <Position> sol = algorithm.Search(adapter); // create the mazeSolution object. MazeSolution path = new MazeSolution(algorithm.GetNumberOfNodesEvaluated(), request.MazeName, sol); // save the solution in the cache solutionCache[request.MazeName] = path; //return the solution return(path); }
public JObject Solve(string name, int alg) { MazeSolution ms = m.SolveMaze(name, alg); JObject obj = JObject.Parse(ms.ToJSON()); return(obj); }
/// <summary> /// Executes the command. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The arguments.</param> /// <returns></returns> public override CommandResult Execute(IClient sender, string[] args) { if (args.Length != 2) { return(new CommandResult(false, Command.Solve, "Usage: solve <name> <algorithm>", true)); } string name = args[0]; byte algorithm; if (!byte.TryParse(args[1], out algorithm)) { return(new CommandResult(false, Command.Solve, "Bad <algorithm> field. Expected: 0 - for bfs, 1 - for dfs", true)); } SolveRequest request = new SolveRequest(name, algorithm); try { MazeSolution sol = _model.SolveMaze(request); //serialize and send the object bool keepCom = _model.IsInGame(sender); return(new CommandResult(true, Command.Solve, sol.ToJSON(), keepCom)); } catch (Exception e) { return(new CommandResult(false, Command.Solve, e.Message, true)); } }
private MazeSolution SolveMaze(string maze) { MazeSolution solvedMaze = new MazeSolution(); maze = "########## #A...#...# #.#.##.#.# #.#.##.#.# #.#....#B# #.#.##.#.# #....#...# ########## "; var mazeArray = MazeArray(maze); for (int i = 0; i < mazeArray.Length; i++) { var row = mazeArray[i]; for (int j = 0; j < row.Length; j++) { if (mazeArray[i][j] == 1) { // Start square found. // Begin traversing through the array to find next step and increment counter and replace . with @ // Will probably require recursion. } } } solvedMaze.Solution = mazeArray.ToString(); solvedMaze.Steps = 0; // this will need to be replaced once traversed and found optimal solution return(solvedMaze); }
public ActionResult <MazeSolution> GetMazeSolution(Guid id) { _logger.LogInformation("GET request for maze solution with maze Id {0}\n\n", id); IDictionary <string, object> payload; try { var accessToken = Request.Headers["Bearer"]; payload = Authorize(accessToken); } catch (ApiException e) { return(Unauthorized(new UnauthorizedError(e.Message))); } MazeSolution solution = _mazeService.GetMazeSolution(id, (string)payload["userId"]); if (solution != null) { return(Ok(solution)); } return(NotFound(new NotFoundError("Maze with id " + id.ToString() + " not in database"))); }
/// <summary> /// Solves this instance. /// </summary> public void Solve() { string cmd = SettingsManager.ReadSetting(SettingName.SearchAlgorithm); string ip = SettingsManager.ReadSetting(SettingName.IP); int port = int.Parse(SettingsManager.ReadSetting(SettingName.Port)); Communicator c = new Communicator(ip, port); cmd = string.Format("solve {0} {1}", Maze.Name, cmd); c.SendMessage(cmd); cmd = c.ReadMessage(); c.Dispose(); Message m = Message.FromJSON(cmd); if (m.MessageType != MessageType.CommandResult) { return; } CommandResult res = CommandResult.FromJSON(m.Data); if (res.Command != Command.Solve) { return; } solving = true; MazeSolution sol = MazeSolution.FromJSON(res.Data); new Task(() => AnimateSolution(sol)).Start(); }
public void MarkSolutionPath_PathToSolutionHasSomeElements_MazeHasSameNumberOfGridpointsOnSolutionPath() { var listOfMazeGridpoints = new List <MazeGridpoint> { new MazeGridpoint(new CartesianCoordinate(2, 0), new DirectionsAvailable(), true, false, false), new MazeGridpoint(new CartesianCoordinate(0, 2), new DirectionsAvailable(), false, false, true), new MazeGridpoint(new CartesianCoordinate(1, 1), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(2, 1), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(3, 1), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(1, 2), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(2, 2), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(3, 2), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(1, 3), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(2, 3), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(3, 3), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(4, 2), new DirectionsAvailable(), false, false, false), new MazeGridpoint(new CartesianCoordinate(2, 4), new DirectionsAvailable(), false, true, false) }; var maze = new Maze(listOfMazeGridpoints.ToDictionary(m => m.Position, m => m)); var solutionPath = new List <MazeSolutionElement> { new MazeSolutionElement { MazeGridpoint = maze.MazeGridpoints[new CartesianCoordinate(2, 0)] }, new MazeSolutionElement { MazeGridpoint = maze.MazeGridpoints[new CartesianCoordinate(2, 1)] }, new MazeSolutionElement { MazeGridpoint = maze.MazeGridpoints[new CartesianCoordinate(2, 2)] }, new MazeSolutionElement { MazeGridpoint = maze.MazeGridpoints[new CartesianCoordinate(2, 3)] }, new MazeSolutionElement { MazeGridpoint = maze.MazeGridpoints[new CartesianCoordinate(2, 4)] } }; var mazeSolution = new MazeSolution(maze); mazeSolution.PathToSolveMaze = solutionPath; mazeSolution.MarkSolutionPath(); Assert.AreEqual( mazeSolution.PathToSolveMaze.Count(), mazeSolution.MazeToSolve.MazeGridpoints.Values.Count(m => m.IsOnSolutionPath)); }
/// <summary> /// Executes the specified arguments to start. /// </summary> /// <param name="args">The arguments.</param> /// <param name="ch">The ch.</param> /// <param name="client">The client.</param> /// <returns>string of the solve maze</returns> public override string Execute(string[] args, ClientOfServer client = null) { string name = args[0]; int typeSolve = int.Parse(args[1]); MazeSolution s = model.Solve(name, typeSolve); client.WriteToClient(s.ToJSON()); client.DisconnectFromServer(); return(s.ToJSON()); }
/// <summary> /// Solves this instance. /// </summary> public void Solve() { Connect(); Writer.WriteLine("solve {0} {1}", maze.Name, defaultSearchAlgorithm); Writer.Flush(); string answer = Reader.ReadLine(); answer = answer.Replace("@", Environment.NewLine); Disconnect(); MazeSolution ms = MazeSolution.FromJSON(answer); RunSolveTask(ms.SolutionString); }
public JObject Solve(string name, int algo) { MazeGame game = Multi.ContainsKey(name) ? Multi[name] : Single[name]; if (game.Solution == null) { ISearcher <Position> searcher = algo == 0 ? (ISearcher <Position>) new BFS <Position, int>((s1, s2) => 1, (i, j) => i + j) : new DFS <Position>(); SearchableMaze smaze = new SearchableMaze(game.Maze); game.Solution = MazeSolution.FromSolution(searcher.Search(smaze)); game.Solution.MazeName = name; } return(JObject.Parse(game.Solution.ToJSON())); }
public Tuple <Score, MazeSolution> GetUserSolution(Guid mazeId, string userId) { Guid userGuid = new Guid(userId); UserMaze um = _userMazeRepository.FindById(mazeId, userGuid); if (um == null) { throw new ApiException(404, "User solution not found"); } string userSolution = um.UserSolution.DecompressString(); Maze maze = _mazeRepository.FindById(mazeId); MazeSolution sol = new MazeSolution(userSolution, maze.Width, '4'); Score userAccuracy = new Score(um.Accuracy.GetValueOrDefault()); return(new Tuple <Score, MazeSolution>(userAccuracy, sol)); }
/// <summary> /// exectue solve command according the arguments. /// </summary> /// <param name="args">The arguments.</param> /// <param name="client">The client that send the command.</param> /// <returns> /// the maze solution /// </returns> public string Execute(string[] args, TcpClient client = null) { if (args.Length != 2) { return("wrong arguments"); } string name = args[0]; bool type; // parse the algorithm and send to model to solve if (!bool.TryParse(args[1], out type)) { Algorithm alg = type ? Algorithm.Dfs : Algorithm.Bfs; MazeSolution solution = _model.SolveMaze(name, alg); return(solution.ToJson()); } return(null); }
/// <summary> /// solve the maze /// </summary> /// <returns>string representation of the solution</returns> public string SolveMaze() { // if the solution is null if (mazeSolution == null) { // ask for a solution from the server Statues stat = ClientSingleton.Client.SendMesseage("solve " + MazeName + " " + searchAlgoritm); // if received null from the server if (stat == null) { return(null); } // return the mazesolution using the solution from the server mazeSolution = MazeSolution.FromJson(stat.Message); } return(mazeSolution); }
// This test was used for tracking the progress of some solver algorithms running in release mode public void ConvertTextOutputToSolutionPathOnMazeImage() { const string mazeImageFilePath = @"..\..\..\SampleMazes\Maze2.png"; const string mazeSolutionTextFilePath = @"..\..\..\SampleMazesSolutions\SampleMaze2\WallHugging.txt"; const string mazeImageSolutionFilePath = @"..\..\..\SampleMazesSolutions\SampleMaze2\Maze2SolutionProgress.png"; var mazeReader = new MazeReaderUtility(mazeImageFilePath); var maze = mazeReader.ReadInMazeImage(); var fileLines = File.ReadAllLines(mazeSolutionTextFilePath); var count = fileLines.Count(); var mazeSolutionPath = new List <MazeSolutionElement>(); for (var i = 0; i < count; i++) { var line = fileLines[i]; var splitLine = line.Split(' ', ','); var xPosition = Convert.ToInt32(splitLine[2]); var yPosition = Convert.ToInt32(splitLine[6]); var coordinate = new CartesianCoordinate(xPosition, yPosition); var mazeGridpoint = maze.MazeGridpoints[coordinate]; var solutionElement = new MazeSolutionElement { MazeGridpoint = mazeGridpoint, }; mazeSolutionPath.Add(solutionElement); fileLines[i] = null; } var mazeSolution = new MazeSolution(maze) { PathToSolveMaze = mazeSolutionPath }; var mazeWriter = new MazeWriterUtility(mazeImageSolutionFilePath, mazeSolution.MazeToSolve); mazeSolution.MarkSolutionPath(); mazeWriter.SaveMazeImage(); }
/// <summary> /// solve a maze /// </summary> /// <param name="name">the name of the maze</param> /// <param name="algo">the algorithm to solve the maze with</param> /// <returns>the solution to the maze</returns> public MazeSolution Solve(string name, int algo) { // solve the maze and return the solution Maze maze = singlePlayerMazes[name]; MazeAdapter mazeAdapter = new MazeAdapter(maze); MazeSolution ms; // solve with the correct algorithm if (algo == 0) { ms = new MazeSolution(new BFS <Position>().Search(mazeAdapter), maze.Name); } else { ms = new MazeSolution(new DFS <Position>().Search(mazeAdapter), maze.Name); } // return the solution return(ms); }
/// <summary> /// click display option button /// </summary> /// <param name="sender">object sender</param> /// <param name="e">event args e</param> private void displaysolution_Click(object sender, RoutedEventArgs e) { string[] parameters = new string[1]; m_name = Name_Maze_sol.Text; if (m_name == "") { MessageBox.Show("The name is empty!"); } else { parameters[0] = m_name; m_view.startEvent(sender, new EventArgMaze(parameters)); Maze new_maze = m_view.GetMaze(); Solution new_sol = m_view.GetSolution(); if (new_maze != null && new_sol != null) { MazeSolution maze_wall_sol = new MazeSolution(new_maze, m_model, m_view, new_sol); display.Children.Add(maze_wall_sol); } } }
/// <summary> /// solve a maze /// </summary> /// <param name="name">the name of the maze</param> /// <param name="searcher">the algorithem to solve with</param> /// <returns>the solution to the maze</returns> public MazeSolution SolveMaze(string name, SearchAlgo searcher) { // checks if the maze exist if (!singlePlayerMazes.ContainsKey(name)) { return(null); } // checks if the solution exist if (singlePlayerSolved.ContainsKey(name)) { return(singlePlayerSolved[name]); } // solve the maze and return the solution Maze maze = singlePlayerMazes[name]; MazeAdapter mazeAdapter = new MazeAdapter(maze); MazeSolution ms = new MazeSolution(searcher(mazeAdapter), maze.Name); // save the current solution singlePlayerSolved.Add(name, ms); return(ms); }
/// <summary> /// Animates the solution. /// </summary> /// <param name="sol">The sol.</param> private void AnimateSolution(MazeSolution sol) { Position = Maze.InitialPos; string str = sol.Solution; for (int i = 0; i < str.Length; i++) { Direction d; switch (str[i]) { //go left case '0': d = Direction.Left; break; //go right case '1': d = Direction.Right; break; //go up case '2': d = Direction.Up; break; //go down case '3': d = Direction.Down; break; default: d = Direction.Unknown; break; } Move(d); Thread.Sleep(500); } GameOver?.Invoke("The maze has been solved :)"); }
public IHttpActionResult GetMazeSolution(MazePostData mazeMap) { if (mazeMap == null || string.IsNullOrWhiteSpace(mazeMap.Map)) { return(BadRequest("Invalid Maze Map!")); } Maze maze = Maze.Parse(mazeMap.Map); Solver solver = new Solver(maze); MazeSolution solution = null; try { solution = solver.Solve(mazeMap.SearchType); } catch (InvalidOperationException ex) { solution = new MazeSolution(0, ex.Message); //it would be nice to add another property to MazeSolution indicating/describing success or failure (or any kind of status and the reason for it):( } return(Ok(solution)); }
/// <summary> /// Solves the maze. /// </summary> /// <param name="name">The name.</param> /// <param name="algorithm">The algorithm.</param> /// <returns> /// the maze solution /// </returns> public MazeSolution SolveMaze(string name, Algorithm algorithm) { MazeSolution solution; // try searching the solution in the cache if (_solutions.TryGetValue(name, out solution)) { return(solution); } Maze maze; if (_mazes.TryGetValue(name, out maze)) { ISearchable <Position> adapter = new MazeAdapter(maze); ISolution <Position> sol = _algorithms[(int)algorithm].Search(adapter); solution = new MazeSolution(name, sol, _algorithms[(int)algorithm].GetNumberOfNodesEvaluated()); _solutions.Add(name, solution); return(solution); } Console.WriteLine("the maze: " + name + "does not exist"); //TODO: handle a case when the maze does not exist return(null); }
public void Subscribe(MazeSolution mazeSolution, MazeWriterUtility mazeWriter) { _mazeWriter = mazeWriter; mazeSolution.MazeToSolve.MazeGridpointUpdated += OnMazeUpdated; }
public void UnSubscribe(MazeSolution mazeSolution) { mazeSolution.MazeToSolve.MazeToBeRedrawn -= OnMazeRedrawn; }
public void Subscribe(MazeSolution mazeSolution, MainWindowViewModel viewModel) { _viewModel = viewModel; mazeSolution.MazeToSolve.MazeToBeRedrawn += OnMazeRedrawn; }
public void UnSubscribe(MazeSolution mazeSolution) { mazeSolution.MazeToSolve.MazeGridpointUpdated -= OnMazeUpdated; }
/// <summary> /// Constructor. /// </summary> public MazeGame() { Players = new Dictionary <string, Position>(); Solution = null; }