Blitz Basic Tute #14 - Recursion

What Minesweeper does is this: when you left click on a square with no mine neigbours, the program not only uncovers the clicked square but it repeats this step for each of its non-mine neighbours - i.e. it uncovers each neighbour and, if it has no mine neighbours, repeats this step for each of its neighbours and so on ...

So you can imagine a function reveal(r0,c0) which sets the state of (r0,c0) to 1 (provided it's not a mine) and, if (r0,c0) has no mine neighbours, repeats the process.

Go on ... be brave ... try writing it yourself before reading on.

Function reveal(r0,c0)
  If grid(r0,c0)=0 ; not a mine
    If grid_state(r0,c0)=0 ; not revealed already
      grid_state(r0,c0)=1
      If mines(r0,c0)=0
        For r=r0-1 To r0+1
          For c=c0-1 To c0+1
            reveal(r,c)
          Next
        Next
      End If
    End If
  End If
End Function

This concept of a function calling itself is known as recursion - it needs to be approached with care because, if you're not careful, a recursive function will go round and round without ever stopping. How do I know this one will stop eventually? Because every time "around", another hidden square is revealed - eventually we must run out of squares!

OK - play with your masterpiece then we'll look at making it look a bit better. What? It doesn't work? You did remember to call reveal in the right place I hope! Like this:

Function click(n)
  y=gy0
  For r=1 To gn_rows
    x=gx0
    For c=1 To gn_cols
      If mouse_in(x,y,x+gw,y+gw)
        If n=1 Then reveal(r,c)
        grid_state(r,c)=n
      End If
      x=x+gw
    Next
    y=y+gw
  Next
End Function

Valid HTML 4.0 Strict Valid CSS