private void initTrack(int startX, int startY, char[][] grid) { //Place a "ghost" cart on the track that will ride the entire length of the track, acting as a "rail layer" so-to-speak //since we are starting at the top left, we can safely go right OR down. But we are gonna choose right. var track = new Track(new Coord(startX, startY)); track.AddRail(startX, startY, grid[startX][startY], true); //Now, starting from our initial position, "ride" along the track, "laying" the rails and turning as needed until we get back //to our initial position. var nextX = startX; var nextY = startY + 1; var currentDirection = Direction.Right; //In our array of arrays, "Down" is when X is INCREASING. "Right" is when Y is INCREASING. while (!track.IsComplete) { var nextRail = grid[nextX][nextY]; if (!nextRail.IsCurve()) { if (nextRail.IsIntersection()) { track.AddRail(nextX, nextY, nextRail, IntersectionMap); } else { track.AddRail(nextX, nextY, nextRail); } switch (currentDirection) { case Direction.Right: nextY++; break; case Direction.Left: nextY--; break; case Direction.Down: nextX++; break; case Direction.Up: nextX--; break; } } else { track.AddRail(nextX, nextY, nextRail); if (nextRail == '\\') { switch (currentDirection) { case Direction.Right: currentDirection = Direction.Down; nextX = nextX + 1; break; case Direction.Left: currentDirection = Direction.Up; nextX = nextX - 1; break; case Direction.Down: currentDirection = Direction.Right; nextY = nextY + 1; break; case Direction.Up: currentDirection = Direction.Left; nextY = nextY - 1; break; } } else if (nextRail == '/') { switch (currentDirection) { case Direction.Down: currentDirection = Direction.Left; nextY = nextY - 1; break; case Direction.Up: currentDirection = Direction.Right; nextY = nextY + 1; break; case Direction.Right: currentDirection = Direction.Up; nextX = nextX - 1; break; case Direction.Left: currentDirection = Direction.Down; nextX = nextX + 1; break; } } } } Tracks.Add(track); }