private void BuildMazeGrid(ref string maze) { //Reset information about maze grid. _columns = 0; _rows = 0; _openNodes = 0; _closedNodes = 0; Nodes = null; _start = null; _end = null; //Break maze into a string array by splitting carriage returns, while removing empty entries. string[] mazeLines = maze.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.None); //Calculate largest column size for maze for (int i = 0; i < mazeLines.Length; i++) { _columns = Math.Max(mazeLines[i].Length, _columns); } //set rows to length of maze _rows = mazeLines.Length; //Create NodeVisual objects after determining grid size. ResetNodeVisuals(); //Initialize Nodes to size of maze grid Nodes = new Node[_columns, _rows]; //Hide to reduce redraws. //NodeVisualsPanel.Visible = false; //Will hold grid coordinates for the Start and End node. Coordinates startCoordinates = null; Coordinates endCoordinates = null; //First populate the Nodes grid with each for (int row = 0; row < _rows; row++) { //Pad the right of our string with char 0 to fill expected column count. string line = mazeLines[row].PadRight(_columns, (char)0); /* Read each char from 0 to our column count in line. * Since we padded line to match column count, this won't cause errors. */ for (int column = 0; column < _columns; column++) { //Store char data for easy reading char data = line[column]; bool closed = false; Coordinates coordinates = new Coordinates(column, row); /* Determine if data indicates a closed node, the * start of the maze, the end of the maze, or * an open node. */ switch (data) { case ' ': break; case 'S': startCoordinates = coordinates; break; case 'E': endCoordinates = coordinates; break; default: closed = true; break; } if (closed) { _closedNodes++; } else { _openNodes++; } //Create a new node visual and assign it to Nodevisuals column and row. NodeVisual nodeVisual = new NodeVisual(this, coordinates, NodeVisualSize, closed, NodeVisualsPanel); _nodeVisuals[column, row] = nodeVisual; //Create a new node and assign it to our Nodes grid using current column and row. Node node = new Node(coordinates, closed, nodeVisual); Nodes[column, row] = node; } } //Set the Start node using coordinates. if (startCoordinates != null) { _start = Nodes[startCoordinates.Column, startCoordinates.Row]; _start.NodeVisual.ColorNodeVisual(Color.Green); } //Set the End node using coordinates. if (endCoordinates != null) { _end = Nodes[endCoordinates.Column, endCoordinates.Row]; _end.NodeVisual.ColorNodeVisual(Color.BlueViolet); } //Cycle through all nodes in our grid to find their neighboring nodes. for (int column = 0; column < _columns; column++) { for (int row = 0; row < _rows; row++) { //Assign to a local variable to make the code easier to read. Node node = Nodes[column, row]; //If node isn't closed: calls a method which will set the neighbors list to a specified node. if (!node.Closed) { SetNeighbors(node, AllowDiagonalCheckbox.Checked, DontCrossCornersCheckbox.Checked); } } } }