Recursion really isn't a loop. You could say, any loop is a subset of recursion. Any loop of the form...
Code:
loop(N) {
for (i = 0; i < N; ++i) {
fn(i);
}
}
Could be expressed recursively as
Code:
recurse(N) {
recurse(N - 1);
fn(N);
}
To really get into what recursion entails sort of involves some CS theory, but a good working definition is "A Recursive Function is Defined in Terms of Itself". A recursive function is very analogous to a mathematical proof that uses induction.
A friend and I were messing around with server code for an open source game, long ago. The code which caused an enemy to 'aggro' one of the players was killing it (the game was quite fast otherwise). Our solution was thus:
How to check an area for aggro...
- Split the map into four quadrants.
- For each quadrant without players, ignore it.
- For each quadrant with players, check that quadrant for aggro.
Code:
// aggro_mobs(area) is slow when area is large,
// So split it into smaller areas.
Check_Aggro (RECT area) {
if (contains_players(curr_quad) == FALSE)
// Quad contains no players, abort.
return;
if (area.x < MIN_RESOLUTION_SIZE) {
// We've zoomed in closely enough, let the mobs aggro.
aggro_mobs (area);
return;
}
// Area is too big, but not empty. Break it down.
Check_Aggro (NORTHWEST_QUAD(curr_quad));
Check_Aggro (SOUTHWEST_QUAD(curr_quad));
Check_Aggro (NORTHEAST_QUAD(curr_quad));
Check_Aggro (SOUTHEAST_QUAD(curr_quad));
}
This could fundamentally not be done only using a loop.