public static void GeneratePath(GridPath path, GridArea gridArea) { var start = path.Start; var end = path.Finish; var pathResult = new List <GridAreaLocation>(); pathResult.Add(path.StartEntrance); bool isComplete = false; GridAreaLocation previous = path.StartEntrance; GridAreaLocation currentLocation = path.StartEntrance; while (!isComplete) { var cell = gridArea.GetCell(previous); // for (int i = 0; i < 4; i++) // { // var n = cell.Neighbors[i]; // // } var preferredNext = PathAlgorithm.SemiGeneticGetNextLocation(gridArea, currentLocation, path.FinishEntrance, previous); bool added = false; foreach (var i in preferredNext) { var c = gridArea.GetCell(i.Add(currentLocation)); if (c == null) { continue; } if (c.State == CellState.None) { previous = currentLocation; currentLocation = i.Add(currentLocation); if (currentLocation.X < 0 || currentLocation.Y < 0) { return; } c.State = CellState.Path; pathResult.Add(currentLocation); added = true; break; } } if (!added) { path.Path = pathResult; return; } if (pathResult.Last() == path.FinishEntrance) { path.Path = pathResult; return; } } pathResult.Add(path.FinishEntrance); }
public static void SetCellStates(List <GridPath> gridPaths, GridArea gridArea) { foreach (var path in gridPaths) { ValidatePath(path); GridAreaLocation previousLocation = null; var p = path.Path; int previousIndex = -1; for (int i = 0; i < p.Count; i++) { var currentLocation = p[i]; var cell = gridArea.GetCell(p[i]); if (cell == null) { Console.WriteLine(); } if (previousIndex >= 0) { var previous = gridArea.GetCell(p[i - 1]); if (previousLocation.X != currentLocation.X) { if (previousLocation.X < currentLocation.X) {// previuos is left cell.State = CellState.Path; cell.LeftNeighbor = previous; } else {//previous is right cell.State = CellState.Path; cell.RightNeighbor = previous; } } else { if (previousLocation.Y < currentLocation.Y) {// previous is bottom cell.State = CellState.Path; cell.BottomNeighbor = previous; } else {//previous is top cell.State = CellState.Path; cell.TopNeighbor = previous; } } } if (i == p.Count - 1) { continue; } previousLocation = currentLocation; var nextLocation = p[i + 1]; var next = gridArea.GetCell(nextLocation); if (nextLocation.X != currentLocation.X) { if (nextLocation.X < currentLocation.X)// next is left { cell.State = CellState.Path; cell.LeftNeighbor = next; } else//next is right { cell.State = CellState.Path; cell.RightNeighbor = next; } } else { if (nextLocation.Y < currentLocation.Y)// next is bottom { cell.State = CellState.Path; cell.BottomNeighbor = next; } else//next is top { cell.State = CellState.Path; cell.TopNeighbor = next; } } previousLocation = currentLocation; previousIndex++; } } }