private static MazeInfo GenerateOrGetExistingMaze(int size) { MazeInfo retVal; if (!mazes.TryGetValue(size, out retVal)) { var generator = new MazeGenerator(); generator.Generate(size, size); generator.Solve(); retVal = new MazeInfo() { GoalPosition = generator.GoalLocation, Grid = generator.TheMazeGrid, Name = $"{size}x{size}", PerfectGameMovesCount = generator.PerfectGameMovesCount, StartingPosition = generator.StartingPosition, Height = size, Width = size }; mazes.Add(size, retVal); } return(retVal); }
void RevertPath(MazeInfo input, string originFileName) { MazeInfo WL = new MazeInfo(); WL.wallPos = input.wallPos; List <Vector2i> collectPosList = new List <Vector2i>(input.collectTaskPos); collectPosList.Reverse(); WL.collectTaskPos = collectPosList.ToArray(); List <SpatialTaskInfo> spatialTaskList = new List <SpatialTaskInfo>(input.spatialTaskInfo); spatialTaskList.Reverse(); for (int i = 0; i < spatialTaskList.Count; i++) { Vector2i temp = spatialTaskList[i].startPos; spatialTaskList[i].startPos = spatialTaskList[i].endPos; spatialTaskList[i].endPos = temp; } WL.spatialTaskInfo = spatialTaskList.ToArray(); string filePath = Path.Combine(Application.streamingAssetsPath, "Levels/" + originFileName + "_Revert" + ".json"); string dataAsJson = JsonUtility.ToJson(WL, true); File.WriteAllText(filePath, dataAsJson); }
public void GenerateMaze(MazeInfo inf) { SetValues(inf); m_regions = new int[inf.Map.GetLength(0), inf.Map.GetLength(1)]; bounds = new Rectangle(0, 0, inf.Map.GetLength(0), inf.Map.GetLength(1)); for (int x = 0; x < m_stage.GetLength(0); x++) for (int y = 0; y < m_stage.GetLength(1); y++) m_stage[x, y] = 1; AddRooms(); for (var y = 1; y < bounds.Height; y += 2) { for (var x = 1; x < bounds.Width; x += 2) { Point pos = new Point(x, y); if (m_stage[x, y] != 1) continue; _growMaze(pos); } } Connect(); RemoveDeadEnds(); }
/// <summary> /// When the solve button is pressed beginning either a normal or threaded solve, /// changing the solve button to a cancel button and if its clicked again cancelling the solve /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UI_btn_Solve_Click(object sender, EventArgs e) { if (UI_btn_Solve.Text == "Solve") //if the button is in solve mode { UI_btn_Solve.Text = "Cancel"; //changing the text to cancel if ((_maze._xWidth * _maze._yHeight > 4000) || speed > 4) //if the maze is larger than 4000 sqr^2 or the speed is larger than 4 starting a threaded solve { //telling the user a threaded solve is being used UI_LB_MessageViewer.Items.Insert(0, $"Threaded Maze Starting for file: {_file}"); //starting a thread and setting the stack memory to 30mb Thread mazeThread = new Thread(new ParameterizedThreadStart(threadStart), 30000000); //sending the maze information to the thread as an object mazeThread.Start(_maze); } else { //teling the user that a non threaded solve has been started UI_LB_MessageViewer.Items.Insert(0, $"Non-threaded Maze Starting for file: {_file}"); //calculating the start time of the solve int startTime = Environment.TickCount; //calling the recursive solve function _maze = recSolve(_maze, _maze._mStart); //sending the results to a function that will display everything to the user solveResults(_maze._steps, startTime, _maze._solved); } } else { //if cancel was clicked setting the text to solve UI_btn_Solve.Text = "Solve"; //enabling the cancel stated cancel = true; } }
// constructor for Encog public WindowLessTraining(int mazeId, int totalIterations, int maxTemp, int minTemp, int encogCycles) { InitializeComponent(); mazerepo = new MazeRepo(); maze = mazerepo.GetByID(mazeId); MazeId = mazeId; TotalIterations = totalIterations; this.maxTemp = maxTemp; this.minTemp = minTemp; this.encogCycles = encogCycles; isEncog = true; lbl1.Content = "# of Iterations:"; lbl2.Content = "Iterations done:"; lbl3.Content = "# of Cycles per:"; lbl4.Content = "Cycles done:"; lbl5.Visibility = Visibility.Hidden; lblMazeName.Content = maze.Name; lblSessionCount.Content = totalIterations.ToString(); lblCurrentSession.Content = 0; lblMoveCount.Content = encogCycles.ToString(); lblSessionsCompleted.Content = 0; lblRandomness.Visibility = Visibility.Hidden; this.Title = "No Maze Encog Learning"; }
public void GenerateMaze(MazeInfo inf) { SetValues(inf); m_regions = new int[inf.Map.GetLength(0), inf.Map.GetLength(1)]; bounds = new Rectangle(0, 0, inf.Map.GetLength(0), inf.Map.GetLength(1)); for (int x = 0; x < m_stage.GetLength(0); x++) { for (int y = 0; y < m_stage.GetLength(1); y++) { m_stage[x, y] = 1; } } AddRooms(); for (var y = 1; y < bounds.Height; y += 2) { for (var x = 1; x < bounds.Width; x += 2) { Point pos = new Point(x, y); if (m_stage[x, y] != 1) { continue; } _growMaze(pos); } } Connect(); RemoveDeadEnds(); }
//*********************************************************************************************************************************************** //Purpose: recursive method as an attempt to solve a loaded maze, checking surrounding positions to find the valid path. //Parameter:MazeInfo maze - used to determine the current state of maze (solved or not) and the steps taken to solve the maze // Point curPos - the moved position to check if the current position is a valid path to take //Returns: The maze's updated detail will be returned to check if the maze was solved or not //*********************************************************************************************************************************************** private MazeInfo MazeSolver(MazeInfo maze, Point curPos) { if (!_mazeDets.result && !_cancel) { Thread.Sleep(_throttle); //exit conditions if (curPos.X == maze.endPos.X && curPos.Y == maze.endPos.Y) { _stop.Stop(); _mazeDets.result = true; //changes the state and label of buttons this.Invoke(new MethodInvoker(delegate() { btnSolve.Enabled = false; })); this.Invoke(new MethodInvoker(delegate() { btnSolve.Text = "Solve"; })); this.Invoke(new MethodInvoker(delegate() { btnLoad.Enabled = true; })); //adds the collected final information to the listbox this.Invoke(new MethodInvoker(delegate() { listMazeLog.Items.Insert(0, $"The maze is solved in {maze.steps} steps / {_stop.ElapsedMilliseconds}ms"); })); return(maze); } //out of bounds -> return to previous position //wall/visited -> return to previous position if (curPos.X < 0 || curPos.X >= maze.mazeWidth || curPos.Y < 0 || curPos.Y >= maze.mazeHeight || _state[curPos.Y, curPos.X] == Wall.wall || _state[curPos.Y, curPos.X] == Wall.visited) { return(maze); } //will not colour the starting green pixel to another colour if (curPos.X != maze.startPos.X || curPos.Y != maze.startPos.Y) { _canvas.SetBBScaledPixel(curPos.X, curPos.Y, maze.livePath); _canvas.Render(); } maze.steps += 1; _state[curPos.Y, curPos.X] = Wall.visited; //attempt to move position MazeSolver(maze, new Point(curPos.X + 1, curPos.Y)); MazeSolver(maze, new Point(curPos.X - 1, curPos.Y)); MazeSolver(maze, new Point(curPos.X, curPos.Y - 1)); MazeSolver(maze, new Point(curPos.X, curPos.Y + 1)); //reached a dead end, colour the return path to grey if (_mazeDets.result == false) { _canvas.SetBBScaledPixel(curPos.X, curPos.Y, maze.deadPath); _canvas.Render(); } } return(_mazeDets); }
public void SetPanelComponents(MazeInfo info, int index) { mazeTitle.text = info.name; if (info.topView != null) { mazeView.sprite = info.topView; } mazeIndex = index; }
public static void updateMazeNum(int mazeNumber) { desiredMazeNum = mazeNumber; maze = listOfAllMazes[desiredMazeNum]; startPos = maze.robotStartPos; startRot = maze.robotStartRot; Camera.main.transform.position = maze.cameraPos; Camera.main.transform.rotation = maze.cameraRot; }
private void SetValues(MazeInfo inf) { MapInformation = inf; m_stage = MapInformation.Map; m_rooms = MapInformation.Rooms; roomtries = MapInformation.Roomtries; ConnectorChance = MapInformation.ConnectorChance; roomExtraSize = MapInformation.RoomExtraSize; windingPercent = MapInformation.WindingPercent; }
/// <summary> /// the function that will control the thread while the maze is solving /// </summary> /// <param name="maze"> the maze information must be cast back to MazeInfo</param> private void threadStart(object maze) { //importing the maze information and casting it to the correct struct MazeInfo tMaze = (MazeInfo)maze; //calculating the start time int startTime = Environment.TickCount; //calling the recursive solve function with the mazes information tMaze = recSolve(tMaze, _maze._mStart); //invoking the delegate to pass the results to a function that will display the results to the user Invoke(new delVoidIntIntBool(solveResults), tMaze._steps, startTime, tMaze._solved); }
void PrintToJson(List <WallPos> wallPosList, List <Vector2i> collectPosList, List <SpatialTaskInfo> spatialInfoList) { MazeInfo WL = new MazeInfo(); WL.wallPos = wallPosList.ToArray(); WL.collectTaskPos = collectPosList.ToArray(); WL.spatialTaskInfo = spatialInfoList.ToArray(); string filePath = Path.Combine(Application.streamingAssetsPath, "Levels/" + saveFileName + ".json"); string dataAsJson = JsonUtility.ToJson(WL, true); File.WriteAllText(filePath, dataAsJson); }
/****************************************************** * Function: private void SolveMaze(object objdata) * Parameter: joined structure (including point and maze structure * return: void * Funtionality: called by the threading to solve the larger maze * recursively. * *****************************************************/ private void SolveMaze(object objdata) { if (objdata is MazeInfo) { MazeInfo maze_s = (MazeInfo)objdata; Point p_ = maze_s.p_start; MazeInfo maze_returned = ((Recursive_Method(p_, maze_s))); //invoke to update the steps Invoke(new delVoidVoid(Update), maze_returned.steps, maze_returned.solved); } }
private void btnSaveMaze_Click(object sender, RoutedEventArgs e) { var repo = new MazeRepo(); // check name for duplicate if (repo.HasDuplicate(txtBoxMazeName.Text) && !editMode) { MessageBox.Show($"'{txtBoxMazeName.Text}' maze name already exist.", "Warning", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } else if (String.IsNullOrWhiteSpace(txtBoxMazeName.Text)) { MessageBox.Show("Please provide a name for the maze."); return; } var maze = new MazeInfo() { Name = txtBoxMazeName.Text, StartingPosition = generator.StartingPosition, GoalPosition = generator.GoalLocation, PerfectGameMovesCount = generator.PerfectGameMovesCount, Grid = generator.TheMazeGrid, Width = width, Height = height }; if (editMode) { repo.UpdateMaze(MazeId, maze); } else { repo.CreateMaze(maze); } //var newMaze = repo.CreateMaze(maze); MessageBox.Show("Maze successfully saved!"); this.Close(); //try get by id //var mazefromdb = repo.GetByID(newMaze.ID); // try to update maze //newMaze.PerfectScore = 100; //repo.UpdateMaze(newMaze.ID, newMaze); // try to get ID Name dic //var result = repo.GetIDNameDictionary(); }
/// <summary> /// This is where RLM is being configured and trained. Call this method and pass the needed parameters to start the training. /// </summary> /// <param name="maze">Contains all the details of the maze that encog will be going to solve.</param> /// <param name="gameTimeout">The given time for solving the maze per session.</param> public static void MazeTrain(MazeInfo maze, int gameTimeout) { Console.WriteLine("RLM network settings:"); int sessions = Util.GetInput("Number of sessions [default 50]: ", 50); //Gets user input for the number of sessions int startRandomness = Util.GetInput("Start randomness [default 100]: ", 100); //Gets user input for the start randomness int endRandomness = Util.GetInput("End randomness [default 0]: ", 0); //Gets user input for the end randomness int randomnessThrough = Util.GetInput("Number of sessions to enforce randomness [default 1]: ", 1); Console.WriteLine(); try { RLMMazeTraveler traveler = new RLMMazeTraveler(maze, true, randomnessThrough, startRandomness, endRandomness); //Instantiate RlmMazeTraveler game lib to configure the network. traveler.SessionComplete += SesionComplete; System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //Start the training (Play the game) for (int i = 0; i < randomnessThrough; i++) { traveler.Travel(gameTimeout); } // set to predict instead of learn for the remaining sessions traveler.Learn = false; for (int i = 0; i < sessions - randomnessThrough; i++) { traveler.Travel(gameTimeout); } watch.Stop(); Console.WriteLine($"Elapsed: {watch.Elapsed}"); traveler.TrainingDone(); Console.ReadLine(); } catch (Exception e) { if (e.InnerException != null && e.InnerException is RlmDefaultConnectionStringException) { Console.WriteLine($"Error: {e.InnerException.Message}"); } else { Console.WriteLine($"ERROR: {e.Message}"); } } }
public override void Init(Transform playerController) { CollectTaskPosList = new List <Vector3>(); SpatialInfoList = new List <SpatialTaskData>(); // build maze by map if (AutoGenerate) { GenerateMaze(); Debug.Log("generate done, file name: " + saveFileName); return; } MazeInfo mazeInfo = ReadFromJson(); float scale = 2.0f; ExperimentManager.VRRig.position = new Vector3(entryIndex.x * scale, RigHeight, entryIndex.y * scale); ExperimentManager.VRRig.Rotate(new Vector3(0, entryRotation, 0)); Vector3 initialPos = playerController.position; List <WallPos> wallPosList = new List <WallPos>(mazeInfo.wallPos); for (int i = 0; i < wallPosList.Count; i++) { Vector3 position = new Vector3(wallPosList[i].x, 0, wallPosList[i].y) * scale; Quaternion rotation = (wallPosList[i].direction) ? Quaternion.identity : Quaternion.Euler(0, 90, 0); Instantiate(wallPrefab, position, rotation); } List <Vector2i> collectTaskPosList = new List <Vector2i>(mazeInfo.collectTaskPos); for (int i = 0; i < collectTaskPosList.Count; i++) { CollectTaskPosList.Add(new Vector3(collectTaskPosList[i].x * scale, initialPos.y, collectTaskPosList[i].y * scale)); } List <SpatialTaskInfo> spatialInfoList = new List <SpatialTaskInfo>(mazeInfo.spatialTaskInfo); for (int i = 0; i < spatialInfoList.Count; i++) { SpatialTaskData data = new SpatialTaskData(); data.startPos = new Vector3(spatialInfoList[i].startPos.x * scale, initialPos.y, spatialInfoList[i].startPos.y * scale); data.endPos = new Vector3(spatialInfoList[i].endPos.x * scale, initialPos.y, spatialInfoList[i].endPos.y * scale); SpatialInfoList.Add(data); } return; }
private void Save() { var path = EditorUtility.SaveFilePanel("Save Xml", "", "", "xml"); if (path.Length != 0) { var go = m_FlexGOParent.transform.GetChild(m_Flexs[0].idx).gameObject; var startPos = m_Flexs.Count > 0 ? go.transform.position : Vector3.zero; var startDir = m_Flexs.Count > 0 ? go.transform.forward : Vector3.forward; var musicPath = AssetDatabase.GetAssetPath(m_Clip).Replace("Assets/Resources/", string.Empty); musicPath = musicPath.Split('.')[0]; var mazeInfo = new MazeInfo(m_Flexs.Values.ToList(), m_Scale, m_ReactTime, startPos, startDir, musicPath); var xmlStr = XmlUtil.Serializer(typeof(MazeInfo), mazeInfo); File.WriteAllText(path, xmlStr); } AssetDatabase.Refresh(); }
MazeInfo ReadFromJson() { LevelData levelData = loadLevelList[(int)loadLevel]; mapsize = levelData.mapSize; entryIndex = levelData.entryPos; entryRotation = levelData.entryRotation; string filePath = Path.Combine(Application.streamingAssetsPath, "Levels/" + levelData.fileName + ".json"); string dataAsJson = File.ReadAllText(filePath); MazeInfo WL = JsonUtility.FromJson <MazeInfo>(dataAsJson); //RevertPath(WL, levelData.fileName); //StartPathFrom(52, 9, WL, levelData.fileName); return(WL); }
public Solution <Position> SolveMaze(string nameOfGame, int algorithm) { MazeInfo mazeInfo = GetMazeInfoOf(nameOfGame); if (mazeInfo == null) { throw new Exception($"There is no game with the name '{nameOfGame}'"); } if (mazeInfo.Solution == null) { // Solution is not inside the cache, so create one. ISearchable <Position> searchableMaze = new SearchableMaze(mazeInfo.Maze); ISearcher <Position> searcher = SearcherFactory <Position> .Create(algorithm); mazeInfo.Solution = searcher.Search(searchableMaze); } return(mazeInfo.Solution); }
/// <summary> /// Return the maze-info of the specified game. /// </summary> /// <param name="nameOfGame">Name of game.</param> /// <returns>MazeInfo, null if the game is not exist.</returns> private MazeInfo GetMazeInfoOf(string nameOfGame) { MazeInfo mazeInfo = null; // Search in all dictionaries. if (SPGames.ContainsKey(nameOfGame)) { mazeInfo = SPGames[nameOfGame].MazeInfo; } else if (availablesMPGames.ContainsKey(nameOfGame)) { mazeInfo = availablesMPGames[nameOfGame].MazeInfo; } else if (unAvailablesMPGames.ContainsKey(nameOfGame)) { mazeInfo = unAvailablesMPGames[nameOfGame].MazeInfo; } return(mazeInfo); }
void StartPathFrom(int firstCollectIndex, int firstSpatialIndex, MazeInfo input, string originFileName) { MazeInfo WL = new MazeInfo(); WL.wallPos = input.wallPos; List <Vector2i> collectPosList = new List <Vector2i>(input.collectTaskPos); List <Vector2i> new_collectPosList = collectPosList.GetRange(firstCollectIndex, collectPosList.Count - firstCollectIndex); new_collectPosList.AddRange(collectPosList.GetRange(0, firstCollectIndex)); WL.collectTaskPos = new_collectPosList.ToArray(); List <SpatialTaskInfo> spatialTaskList = new List <SpatialTaskInfo>(input.spatialTaskInfo); List <SpatialTaskInfo> new_spatialTaskList = spatialTaskList.GetRange(firstSpatialIndex, spatialTaskList.Count - firstSpatialIndex); new_spatialTaskList.AddRange(spatialTaskList.GetRange(0, firstSpatialIndex)); WL.spatialTaskInfo = new_spatialTaskList.ToArray(); string filePath = Path.Combine(Application.streamingAssetsPath, "Levels/" + originFileName + "_StartAt" + firstCollectIndex + ".json"); string dataAsJson = JsonUtility.ToJson(WL, true); File.WriteAllText(filePath, dataAsJson); }
// constructor for RNN public WindowLessTraining(int mazeId, Boolean learn, int totalIterations, int temp_num_sessions, int startRandomness = 1, int endRandomness = 1) { InitializeComponent(); mazerepo = new MazeRepo(); maze = mazerepo.GetByID(mazeId); MazeId = mazeId; Learn = learn; TotalIterations = totalIterations; Temp_num_sessions = temp_num_sessions; StartRandomness = startRandomness; EndRandomness = endRandomness; isEncog = false; lblMazeName.Content = maze.Name; lblCurrentSession.Content = 1; lblSessionCount.Content = totalIterations.ToString(); lblMoveCount.Content = 0; this.Title = "No Maze RNN Learning"; }
/// <summary> /// This is where encog is being configured and trained. Call this method and pass the needed parameters to start the training. /// </summary> /// <param name="maze">Contains all the details of the maze that encog will be going to solve.</param> /// <param name="gameTimeout">The given time for solving the maze per session.</param> public static void MazeTrain(MazeInfo maze, int gameTimeout) { Console.WriteLine("Encog network structure:"); int defHiddenLayers = maze.Width * maze.Height; //This is the default number of hidden layer neurons if not specified. int hiddenLayers = Util.GetInput("Number of hidden layers [default 1]: ", 1); //Getting user input for the number of hidden layers, will be set to 1(default) if not specified. int hiddenLayersNeurons = Util.GetInput($"Hidden layers rneurons [default {defHiddenLayers}]:", defHiddenLayers); //Getting user input for the number of hidden layer neurons, will be set to "defHiddenLayers"(default) value if not specified. var em = new EncogMaze(maze, hiddenLayers, hiddenLayersNeurons); //Create an instance of encog maze game to configure the network. em.EncogCycleComplete += SesionComplete; em.TrainingIterationComplete += Em_DoneTrainingIteration; int mode = Util.GetInput("Select Encog learning method [Annealing - 0, Genetic - 1 default]: ", 1); //Gets user input for the type of encog training method, e.g. (Simulated Annealing, MLGeneticAlgorithm) int epochs = Util.GetInput("EPOCHS to execute [default 10]: ", 10); //Gets user input for the number of epochs int cycles = Util.GetInput((mode == 0) ? "Cycles per epoch [defualt 10]: " : "Population size [default 10]: ", 10); //Gets user input for the number of cycles int maxTemp = 0; int minTemp = 0; if (mode == 0) { maxTemp = Util.GetInput("Max temperature [default 10]: ", 10); //Gets user input for the starting temperature minTemp = Util.GetInput("Min temperature [default 2]: ", 2); //Gets user input for the ending temperature } Console.WriteLine(); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); em.Train(mode, epochs, maxTemp, minTemp, cycles, gameTimeout); //Call the Train() method from encog game lib to start the training. watch.Stop(); Console.WriteLine($"Elapsed: {watch.Elapsed}"); Console.ReadLine(); }
public MazeSolver(IAmazeingClient client, MazeInfo maze) { _client = client; this._maze = maze; }
/* Calls the recursive Funtions to solve the required maze * comprised of 2 methods, the event handler for the button and an additional recursive method that will * actually solve the maze. the event handler will do nothing more than call your recursive method * /passing MazeInfo object and the current maze point, * the return value of type MazeInfo indicates that the * Solve attempt is complete – true=success, false=no solution and the number of steps to the exit */ private void buttonSolve_Click(object sender, EventArgs e) { stop = false; string[] filename = filename_[7].Split('_'); //indicate a point struct Point_Val Point_struct; Point_struct.pointVal_ = new Point(0, 0); //set the steps to zero MazeInfo_struct.steps = 0; //assign the initial start points to the pount value Point_struct.pointVal_ = MazeInfo_struct.p_start; //set the solved to false MazeInfo_struct.solved = false; if (buttonSolve.Text == "Solve") { //For implementation, provide 2 paths to maze solutions.\ //If the maze overall area is larger than 4000 or if the current sleep value is greater than 4, //use the threaded solver, //otherwise directly solve the maze without a thread. if ((MazeInfo_struct.height * MazeInfo_struct.width < 4000) && numericUpDownSpeed.Value <= 4) { MazeInfo maze_s = ((Recursive_Method(Point_struct.pointVal_, MazeInfo_struct))); if (maze_s.solved == true) { listBoxData.Items.Add($"Solved in {maze_s.steps}"); } else { listBoxData.Items.Add($"Maze is not solved!"); } } else { try { listBoxData.Items.Add($"We are now using threading to solve the maze. "); listBoxData.Items.Add($"Attempting threaded solve of maze {filename[1]} maze "); if (numericUpDownSpeed.Value >= 1) { stop = false; buttonSolve.Text = "Cancel"; } //Increase the maximize stack size in a thread spawn ( 2nd argument overload ), //to 20MB to allow solving larger mazes. maze_thread = new Thread(new ParameterizedThreadStart(SolveMaze), 20000000); maze_thread.IsBackground = true; maze_thread.Start(MazeInfo_struct); } catch (Exception message) { MessageBox.Show($"{message.Message}"); } } } else if (buttonSolve.Text == "Cancel") { stop = true; buttonSolve.Text = "Solve"; listBoxData.Items.Add($"Thread has been canceled "); } }
/* ******************************************************************** * Funtion: private MazeInfo Recursive_Method(Point p_, MazeInfo maze_s) * Parameters: Point p_, MazeInfo maze_s * Return: Maze info object that indicates maze is solved or not * Funtionality: Solves the maze recursively if the dead end is reached it backtracks and showing a backtracking * in a different color ***********************************************************************/ private MazeInfo Recursive_Method(Point p_, MazeInfo maze_s) { if (stop == true) { maze_s.solved = true; return(maze_s); } //check if the point is out of bounds if it is return if (p_.X >= canvas.ScaledWidth || p_.X < 0 || p_.Y >= canvas.ScaledHeight || p_.Y < 0) { maze_s.solved = false; return(maze_s); } //check if the point has reached the end if it is return and set solved to true if (p_ == MazeInfo_struct.p_end) { maze_s.solved = true; return(maze_s); } //if there is obstacle wall or the obstacle has been visited set the maze solved to false if ((Obs_array[p_.X, p_.Y] == Obstacle.wall) || ((Obs_array[p_.X, p_.Y] == Obstacle.visited))) { maze_s.solved = false; return(maze_s); } //increase the steps or count the total number of steps it took to solve the masze maze_s.steps++; //if we are checking the point that means it has been visited Obs_array[p_.X, p_.Y] = Obstacle.visited; //set the speed if (p_ != MazeInfo_struct.p_end && p_ != MazeInfo_struct.p_start) { if (numericUpDownSpeed.Value > 0) { maze_s.solved = true; int speed = (int)numericUpDownSpeed.Value * 10; Thread.Sleep(speed); } } //If it is not equal to start draw the correct solution if (p_ != maze_s.p_start) { canvas.SetBBScaledPixel(p_.X, p_.Y, maze_s.Sol_color); canvas.Render(); } //recurse in all directions if the maze is solved set the flag to solved //and return //checks x+1 direction if maze is solved true is returned maze_s = Recursive_Method(new Point(p_.X + 1, p_.Y), maze_s); if (maze_s.solved) { maze_s.solved = true; return(maze_s); } //checks the x -1 direction if maze is solved true is returned maze_s = Recursive_Method(new Point(p_.X - 1, p_.Y), maze_s); if (maze_s.solved) { maze_s.solved = true; return(maze_s); } //checks y +1 direction if maze is solved true is returned maze_s = Recursive_Method(new Point(p_.X, p_.Y + 1), maze_s); if (maze_s.solved) { maze_s.solved = true; return(maze_s); } //checks y -1 direction if maze is solved true is returned maze_s = Recursive_Method(new Point(p_.X, p_.Y - 1), maze_s); if (maze_s.solved) { maze_s.solved = true; return(maze_s); } //if no solution was found that means there is a dead end. //show the dead end in a dead end color //this is basically backtracking. if (p_ != maze_s.p_start) { canvas.SetBBScaledPixel(p_.X, p_.Y, maze_s.Dead_color); canvas.Render(); } //no solution was found return false maze_s.solved = false; return(maze_s); }
/// <summary> /// gets maze from server /// </summary> public void GetMazeInfo() { MazeInfo mazeInfo = new MazeInfo(40, 50, 36, 34, 8, 48, 36, 34, "00000000000100000000000100010001000000011111011111011111011111010111010101111101000001000100010001000101000001010001010101110101011101011101010111111101111101010001010100010100010101000001000100000001010111011101011101010111110101110111111101010001000100010001010000010001010000010101011101111101110101110111110101011101010000010000010001010001000000010001000101111101111101110111110111111101111101110100010001010100000001000100010001000101010101110101011111110111010111110101110101010001000100010001000001000000010000011101110111110101011111111101111111111101000101010001010100000000010101000001000101110101010111010111011101010101110101110001010101000001000100010101010101000101110101010111111111011101110101010111110100010001000101000001010000010101000000010111110111010101111101111111010111011101010001000001010001010000000001000001010101010111111101110101010111110111111101010001000100000000010001000001000100000101111111011111110111110111110101110101110100000101000001000001000100010100010000010111010101110111110111110111010111111111010000010001000001000001010001010000010101011111110111110111110101011101010101010101000100010000010100000100010101010101010101010111011111010111111101011101010101010100000100000100010000010100000100010111011111111111011111011101111111111101010000010001000100010001010000000000010101011111010101010101011101111111011111010001010001000101010100000101000001000001011101011111110111011111010101110101111100000101000001000001000001010100010100011101110101110111111101111101010111011101010100010101000000000100000101000100010101010111010111111111110111010111011101010001000100000100010001010001000101010101011111011111010101010111010111010101010100010100000100010001010001010101000101011101011101011111111101011101010111010101010001010100000000010001000101000101000101110101011101111111111101110111011111010100010101000100000100010100000101000001010111010111110111010101011101010101111100000001000000000100010000000101000000011111111111111111111111111111111111111111"); mazeDisplay = new MazeDisplay(mazeInfo); }
/// <summary> /// moving through the maze recursively to find the correct path through the maze /// </summary> /// <param name="maze">the information about the maze</param> /// <param name="curPo">the starting position of the recursive function</param> /// <returns></returns> private MazeInfo recSolve(MazeInfo maze, Point curPo) { //if the cancel button is pressed escaping the function //setting the steps to zero and that the maze was not solved if (cancel == true) { maze._steps = 0; maze._solved = false; return(maze); } //if the maze exit is reached marking the maze as solve and escaping the function if (curPo == maze._mEnd) { maze._solved = true; return(maze); } //if the current position of the function is out of bounds backing up if ((curPo.X >= maze._xWidth) || (curPo.X < 0) || (curPo.Y >= maze._yHeight) || (curPo.Y < 0)) { return(maze); } //if the current position of the function is in a wall backing up if (mazeArray[curPo.X, curPo.Y] == state.wall) { return(maze); } //if the current position of the function is a pixel that has been visited already backing up if (mazeArray[curPo.X, curPo.Y] == state.visited) { return(maze); } //if the current position is not the start of the maze if (curPo != maze._mStart) { mazeArray[curPo.X, curPo.Y] = state.visited; //setting that pixel to visited _canvas.SetBBScaledPixel(curPo.X, curPo.Y, maze._cSol); //setting the color to the solution color _canvas.Render(); //rendering the canvas } //incrementing the step counter maze._steps += 1; //if the speed is not zero sleeping the solver if (speed != 0) { Thread.Sleep(speed); } //attempting to move the solver in each direction in the order (up, right, down, left) moving down 1 level of recursion if ((maze = recSolve(maze, new Point(curPo.X, curPo.Y + 1)))._solved) { return(maze); } if ((maze = recSolve(maze, new Point(curPo.X + 1, curPo.Y)))._solved) { return(maze); } if ((maze = recSolve(maze, new Point(curPo.X, curPo.Y - 1)))._solved) { return(maze); } if ((maze = recSolve(maze, new Point(curPo.X - 1, curPo.Y)))._solved) { return(maze); } //if the maze wasn't solve moving down the chain of recursion if (curPo != maze._mStart) { _canvas.SetBBScaledPixel(curPo.X, curPo.Y, maze._cDed); //setting the current path to the visited color _canvas.Render(); //rendering the canvas } //decrementing the steps maze._steps -= 1; //moving up 1 level of recursion return(maze); }
async void Init(MazeInfo mazeInfo) { if (!Learn) { CurrentIteration = 1; Temp_num_sessions = 1; StartRandomness = 0; EndRandomness = 0; } replayMemory = new object[Temp_num_sessions]; StatusText.Content = "Initializing RLM engine..."; await Task.Run(() => { RLMMazeTraveler traveler = new RLMMazeTraveler(mazeInfo, Learn, Temp_num_sessions, StartRandomness, EndRandomness); //Instantiate RlmMazeTraveler game lib to configure the network. traveler.SessionComplete += Traveler_SessionComplete; traveler.MazeCycleComplete += Traveler_MazeCycleComplete; traveler.SessionStarted += Traveler_SessionStarted; traveler.MazeCycleError += mazecycle_error; game.traveler = traveler; if (Learn) { RunUIThread(() => { StatusText.Content = "Training started..."; }); //Start the training (Play the game) for (int i = 0; i < RandomnessOver; i++) { locations = new List <Location>(); RunUIThread(() => { lblCurrentSession.Content = 1; }); CurrentIteration = i + 1; traveler.Travel(10000); } // set to predict instead of learn for the remaining sessions traveler.Learn = false; for (int i = 0; i < Temp_num_sessions - RandomnessOver; i++) { CurrentIteration++; locations = new List <Location>(); RunUIThread(() => { StatusText.Content = $"Training started... {CurrentIteration * 100 / Temp_num_sessions}%"; }); traveler.Travel(10000); } //traveler.TrainingDone(); RunUIThread(() => { StatusText.Content = $"Training done... 100%"; }); } else { RunUIThread(() => { StatusText.Content = $"RLM preparing to play..."; }); locations = new List <Location>(); RunUIThread(() => { StatusText.Content = $"RLM Playing..."; }); traveler.Learn = false; traveler.Travel(10000); } }).ContinueWith(async(t) => { //show AI playing game Stopwatch watch = new Stopwatch(); foreach (dynamic obj in replayMemory) { RunUIThread(() => { lblCurrentSession.Content = (int)obj.cycleNum + 1; lblRandomness.Content = (int)obj.randomnessLeft; }); watch.Start(); foreach (Location loc in obj.moves as List <Location> ) { var x = loc.X; var y = loc.Y; RunUIThread(() => { maze.ChangeCellColor(new TravelerLocation() { X = loc.X, Y = loc.Y }, true); }); await Task.Delay(TimeSpan.FromMilliseconds(2)); //If game is not solved within 5s, go to the next session. if (watch.Elapsed.TotalSeconds >= 10) { break; } } watch.Reset(); RunUIThread(() => { lblScore.Content = (double)obj.score; lblMoves.Content = (int)obj.movesCnt; if (!Learn) { StatusText.Content = $"RLM done playing..."; } else { StatusText.Content = $"Showing rlm replay..."; } maze.setGoalRect(); }); } RunUIThread(() => { StatusText.Content = $"Done. Close the window to return back to the menu and train again..."; }); }, TaskContinuationOptions.OnlyOnRanToCompletion); }
public MainWindow(int mazeId, PlayerType type, Boolean learn = false, int temp_num_sessions = 1, int currentIteration = 1, int totalIterations = 1, int startRandomness = 1, int endRandomness = 1) { InitializeComponent(); mazerepo = new MazeRepo(); mazeInfo = mazerepo.GetByID(mazeId); RandomnessOver = temp_num_sessions; ClosedDueToGameOver = false; Learn = learn; Type = type; if (Type == PlayerType.Human) { this.Title = "Human Player"; StatusText.Visibility = Visibility.Visible; } else if (Type == PlayerType.RNN) { if (learn) { Temp_num_sessions = totalIterations; StartRandomness = startRandomness; EndRandomness = endRandomness; this.Title = "RNN Learning"; statGrid.Visibility = Visibility.Visible; lblMazeName.Content = mazeInfo.Name; lblTotalSession.Content = totalIterations; lblCurrentSession.Content = CurrentIteration = currentIteration; lblScore.Content = LastScore; lblMoves.Content = LastMovesCount; } else { this.Title = "RNN Player"; } } else { this.Title = "Encog Player"; } game = new MazeGameLib.MazeGame(); maze = new Maze(); game.InitGame(mazeInfo); //Initialize Grid game.TheMazeGrid = mazeInfo.Grid; maze.InitializeMaze(game, mazeGrid); //Init Game //game.InitGame(this.MainGrid, new RunThreadUI_Delegate(RunUIThread)); //Send Keys to Game if (Type == PlayerType.Human) { this.KeyDown += MainWindow_KeyDown; } // reset static session count if (currentIteration == 1) { //RNNMazeTraveler.ResestStaticSessionData(); } //Send shutdown event to game //this.Closed += MainWindow_Closed; }
public void RegenMaze(MazeInfo inf) { m_mazeGen.GenerateMaze(inf); Map = m_mazeGen.MapInformation.Map; m_LayerSize = new Point(Game1.TILESIZE, Game1.TILESIZE); Rectangle temprect = m_mazeGen.m_rooms[Game1.RNG.Next(0, m_mazeGen.m_rooms.Count)]; m_StartPos = temprect.ReturnRandom(1); Rectangle tmprect = temprect; do { temprect = m_mazeGen.m_rooms[Game1.RNG.Next(0, m_mazeGen.m_rooms.Count)]; } while (tmprect == temprect); m_WinPos = temprect.ReturnRandom(1); for (int i = 0; i < inf.NoOfChests; i++) { Rectangle room = m_mazeGen.m_rooms[Game1.RNG.Next(0, m_mazeGen.m_rooms.Count)]; Point possiblechest = room.ReturnRandom(1); if (possiblechest != m_StartPos && possiblechest != m_WinPos) { if (m_chests.Contains(possiblechest)) { i--; } else { m_chests.Add(possiblechest); } } } VisualMap = new Tile[Map.GetLength(0), Map.GetLength(1)]; for (int x = 0; x < Map.GetLength(0); x++) { for (int y = 0; y < Map.GetLength(1); y++) { int[,] m_base = new int[3, 3]; for (int xt = 0; xt < 3; xt++) { for (int yt = 0; yt < 3; yt++) { m_base[xt, yt] = 1; } } for (int currx = -1; currx < 2; currx++) { for (int curry = -1; curry < 2; curry++) { if (x + currx < 0) { currx++; } if (y + curry < 0) { curry++; } if (x + currx > Map.GetLength(0) - 1) { break; } if (y + curry > Map.GetLength(1) - 1) { break; } Point copycord = new Point(x + currx, y + curry); m_base[currx + 1, curry + 1] = Map[copycord.X, copycord.Y]; } } if (Map[x, y] == 0) { VisualMap[x, y] = new Tile(TileType.Floor); } else if (Map[x, y] == 1 && m_base[2, 1] == 0) { VisualMap[x, y] = new Tile(TileType.LWall); } else if (Map[x, y] == 1 && m_base[0, 1] == 0) { VisualMap[x, y] = new Tile(TileType.RWall); } else if (Map[x, y] == 1 && m_base[1, 0] == 0) { VisualMap[x, y] = new Tile(TileType.TWall); } else if (Map[x, y] == 1 && m_base[1, 2] == 0) { VisualMap[x, y] = new Tile(TileType.BWall); } else { VisualMap[x, y] = new Tile(TileType.EmptyRegion); } } } }