public void MakeTurn() { var graph = new Graph(MapData.Select(x => new MapCell { Location = x.Key, SurfaceType = x.Value }), Start, Finish); var node = graph.GetNodes(Position).FirstOrDefault(n => n.Direction == Direction && n.Speed == Speed); if (node == null) { throw new Exception("Unable to find ourselves in the map graph"); } var paths = new PathMatrix(graph, node); var reachable = paths.GetReachableNodes(); var target = reachable.Where(n => n.node.Location == Finish).Select(n => n.node).FirstOrDefault() ?? reachable.Where(n => n.node.HasNearbyTi) .OrderBy(n => n.node.SurfaceType) .ThenBy(n => n.node.Speed) .ThenBy(n => n.node.TiCount) .ThenBy(n => n.distance) .ThenBy(n => n.node.Location.Distance(Finish)) .Select(n => n.node).FirstOrDefault(); if (target == null) { throw new Exception("Nowhere to go"); } Console.WriteLine($"Chosen {target} as final target"); var path = paths.GetPath(target); if (path == null) { Console.WriteLine("Bug in pathfinder"); } var nextCell = path.First(x => x.Location != Position); Navigate(nextCell); }