/// //Inititialize new nodes and construct them accordingly.; //Remember that field[X,Y] are bonded with the For-loop X & Y order (In this case: "field[y,x]"). /// Node[,] ConstructNodes(int width, int height, Node[,] field, int[,] layout) { Node[,] result = field; int i = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Node temp = field[y, x]; temp.x = x; temp.y = y; temp.layoutID = layout[y, x]; temp.id = i; if (temp.layoutID == 2) { startX = x; startY = y; } else if (temp.layoutID == 3) { endX = x; endY = y; } result[y, x] = temp; i++; } } return result; }
Node GetCheapestAdjacent(Node newParent) { Node parent = newParent; List<Node> parentList = new List<Node>(); int cycle = 0; while (cycle < 2) { for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { Node temp = field[y, x]; //Detecting/scanning all the adjecent nodes and then picking the one with the lowest cost. circleArr[0] = (parent.x == (temp.x) && parent.y == (temp.y - 1)); //Upper circleArr[1] = (parent.x == (temp.x + 1) && parent.y == (temp.y - 1)); //Upper-Right circleArr[2] = (parent.x == (temp.x + 1) && parent.y == (temp.y)); //Right circleArr[3] = (parent.x == (temp.x + 1) && parent.y == (temp.y + 1)); //Bottom-Right circleArr[4] = (parent.x == (temp.x) && parent.y == (temp.y + 1)); //Bottom circleArr[5] = (parent.x == (temp.x - 1) && parent.y == (temp.y + 1)); //Bottom-Left circleArr[6] = (parent.x == (temp.x - 1) && parent.y == (temp.y)); //Left circleArr[7] = (parent.x == (temp.x - 1) && parent.y == (temp.y - 1)); //Upper-Left //First cycle if (cycle < 1) { //Looping through the "circle" to detect a present match. for (int c = 0; c < circleArr.Length; c++) if (circleArr[c] == true) //As long as the layoutID is not a wall(1), the starting point(2) or an already foudn node(5), continue if (temp.layoutID != 1 && temp.layoutID != 2 && temp.layoutID != 5) { //Assigning new IDs to searched Nodes if (temp.layoutID != 3) temp.layoutID = 4; //Calculating movement cost(s) if (c % 2 == 0) temp.g += 10; else temp.g += 14; //Setting total cost to move temp.f = temp.g + temp.h; //Adding to parent list for second loop parentList.Add(temp); } } else { //Sort the list so that the lowest node will be at the top. parentList.Sort((Node a, Node b) => (a.f).CompareTo(b.f)); //Looping through the "circle" to detect a present match. for (int c = 0; c < circleArr.Length; c++) if (circleArr[c] == true) if (temp.f == parentList[0].f) { //Get the node and set it as the new parent after setting the old parent as its parent, temp.parent = parent.layoutID; openList.Remove(parent); closedList.Add(parent); parent = temp; //also add it to the openlist after the old parent had been dropped and added to the closed list. openList.Add(parent); //Resetting the loops. x = width - 1; y = height - 1; } } field[y, x] = temp; InitiateSolvedVisualizing(); } cycle++; } return parent; }