PDA

View Full Version : Recursion in Game Maker



cairnswm
15-08-2007, 10:49 PM
How do you do recursion in Game Maker?

Script : FocusCell(argument0 = CellX; argument1 = CellY)

if not global.BlockSel[argument[0],argument[1]] == true then
{

global.BlockSel[argument[0],argument[1]] = true;

px = argument[0];
py = argument[1];

if px > 0 then
{ if global.BlockId[px-1,py] == global.BlockId[px,py] then
{ FocusCell(nx,py); } }

if px < 9 then
{ if global.BlockId[px+1,py] == global.BlockId[px,py] then
{ FocusCell(nx,py); } }

if py > 0 then
{ if global.BlockId[px,py-1] == global.BlockId[px,py] then
{ FocusCell(px,ny); } }

if py < 9 then
{ if global.BlockId[px,py+1] == global.BlockId[px,py] then
{ FocusCell(px,ny); } }
}




What happens is it seems to only execute in one direction - ie it doesn;t seem to do the second FocusCell when called. (So it it needs to focus a cell to left and top, it only does the left one).

herman.tulleken
16-08-2007, 09:26 AM
I had a similar problem once; recursion works, but it seems that once a function returns from the recursive call, your variables (px and py, in your case) have the values assigned to them in the call, and not the values they have in their current scope. This makes sense if the function is called from an object, in which case the variables are attached to the object, and not the function.

I solved it by reassigning them after the recursive call, but it might also be solved by declaring your variables using var.

Hope this helps

ht

dislekcia
16-08-2007, 10:32 AM
Var fixes the scope problem.

A script will use the scope of the object it's running on when it assigns variables, unless you specifically tell it to use a scope limited to the script by using the var keyword. That's how I do all my recursion :)

-D

cairnswm
17-08-2007, 08:57 AM
Works now - Thanks ;)

Looks like I might be ready to do simple GML demos for rAge. My newest game (a 10th rewrite of an old favorite of mine) should be ready sometime next weekend :)