I am currently trying to make a snake pathfinding algorithm. I tried to make something, but a problem came up that I find hard. The problem is that I am implementing the algorithm in a recursive way which does not find one path, but searches for all the available paths which causes stack overflow exception because of the large console window size.
The "Grid" is a two dimensional boolean array which is as big as the console and a value is true if there is something like a part of the snake on the console.
Direction is an enumeration with Up, Down, Left, Right values. Position is a struct with two integers called X and Y.
ScheduledDirections is a list with directions which will be used in the future for the snake's drawing on the console.
What I want to do is to add one available path to that list fast. I know about pathfinding algorithms like A*, but I find it too complex and hard to implement.
This is the method that I am using to find an available path:
private static void FindAvailablePath(Position currentPosition, Direction currentDirection)
{
// break if the snake's path search has ended or it went out of the console
if (currentPosition.X < 0 || currentPosition.X >= Console.WindowWidth ||
currentPosition.Y < 0 || currentPosition.Y >= Console.WindowHeight ||
AIController.isReady)
{
return;
}
// break if there is something that is blocking the snake's path
if (Snake.Grid[currentPosition.X, currentPosition.Y])
{
return;
}
// break if the snake has reached its destination
if (currentPosition.Equals(AIController.Destination))
{
AIController.isReady = true;
return;
}
// if the current path is available, adds it to the collection and checks for the next one
if (!Snake.Grid[currentPosition.X, currentPosition.Y])
{
AIController.scheduledDirections.Add(currentDirection);
FindAvailablePath(new Position(currentPosition.X + 1, currentPosition.Y), Direction.Right); // right
FindAvailablePath(new Position(currentPosition.X, currentPosition.Y - 1), Direction.Up); // up
FindAvailablePath(new Position(currentPosition.X - 1, currentPosition.Y), Direction.Left); // left
FindAvailablePath(new Position(currentPosition.X, currentPosition.Y + 1), Direction.Down); // down
}
}
If someone has some better ideas I will be pleased to hear them. Thanks!