Recursion is one of the harder topics to grasp for a lot of intro programmers. The idea is you have a function that calls itself. This can get problematic because you can easily create an infinite recursion where the program gets stuck. To prevent this you need a condition in the function to prevent it from calling itself infinitely. Here's a simple recursive function.
- Code: Select all
int
factorial (int number)
{
if(number<=1) // this is the condition that prevents the recursion from happening forever
{
return 1; // when this is returned, the recursion stops, and it unfolds
}
else
{
return number*factorial(number-1); // in all other cases, recurse on this function
}
}
// to call this function you just do this
int value = factorial(3);
The function calculates a factorial. Here's how it works.
factorial(3)
returns the value 3*factorial(2)
factorial(2)
returns the value 2*factorial(1)
factorial(1)
returns 1 (notice recursion ends)
All of that expanded out looks like
3*2*1
Which equals 6.
That's a very cursory explanation of recursion, which is something you'll need to understand before implementing minimax for your game. If you need any more explanation feel free to ask.