Blitz Basic Tute #11 - A Better Jigsaw

The first refinement will be to highlight the first piece clicked. You'd think adding these lines to the display() function would do the trick:

      DrawBlock piece_imgs(n),x,y
      If n=last_n Then
        Color 0,255,0
        Rect x,y,160,160,False
      End If
      n=n+1

In fact, I'd like you to go and try this right now ... then we'll discuss why it doesn't work.

The reason this doesn't work will introduce us to a new and very important concept in programming. You may have noticed that we use x and y and n and so on all over the place and never worry whether they trip over each other or not. In fact, each function has its own set of variables so last_n within the display() function has nothing to do with the last_n outside.

To announce the fact that we want to use last_n throughout our program we use the new word Global right at the start like this:

Graphics 640,480
SetBuffer BackBuffer()
SeedRnd MilliSecs()
Global last_n

Go and try it right now!

Did you notice a bit of serendipity here? When the player clicks on a piece it lights up fine but when they click on the same piece again, the highlight vanishes - a neat way to "undo" that move.

Armed with new concept of global variables, we can work some real magic. You probably feel that the jigsaw could do with more pieces and you probably noticed how we used the numbers 3, 4, 12 and 160 all over the place. Here's an alternative idea:

...
Global n_rows=3
Global n_cols=4
Global n_pieces=n_rows*n_cols
Global piece_size=640/n_cols
Dim piece_imgs(n_pieces)
...

Then change

throughout your program. Come back here when you've got it all working ok.

If you did it all just right, then simply changing two lines will give you an entirely different jigsaw:

Global n_rows=6
Global n_cols=8

And I guess that you've already realised that this program will work with any 640x480 picture!

One last addition to make things perfect ... working out when the player has finished. What I did was to use another array with just the numbers in it (like in Concentration). This array I shuffled in sync with the images. When this array is back in order, the game is over. Here's my final program.


Valid HTML 4.0 Strict Valid CSS