Blitz Basic Tute #7 - Card Clicking

All 52 cards, shuffled and laid out in 6 rows with 9 in each row. The secret is one loop inside another.

Notice the use of comments - they start with ;

Note also the highlighted line which shows how to break out of a loop before we run into trouble.

Graphics 800,600
SetBuffer BackBuffer()
SeedRnd MilliSecs()
; initialise
Dim cards(52)
For i=1 To 52
  cards(i)=i
Next
; shuffle
For i=1 To 500
  r1=Rand(52)
  r2=Rand(52)
  t=cards(r1)
  cards(r1)=cards(r2)
  cards(r2)=t
Next
;display
n=1
y=8
For row=1 To 6
  x=68
  For col=1 To 9
    card=cards(n)
    card_img=LoadImage(card+".png")
    DrawBlock card_img,x,y
    FreeImage card_img
    x=x+74
    n=n+1
    If n=53 Then Exit
  Next
  y=y+98
Next
Flip
WaitKey
End

We can make our programs a lot easier to manage by creating lots of functions.
Try rewriting this program using functions ... it should look like this:

Graphics 800,600
SetBuffer BackBuffer()
SeedRnd MilliSecs()
; initialise
Dim cards(52)
For i=1 To 52
  cards(i)=i
Next
; shuffle
cards_shuffle()
;display
cards_display()
Flip
WaitKey
End
Function cards_shuffle()
  For i=1 To 500
    r1=Rand(52)
    r2=Rand(52)
    t=cards(r1)
    cards(r1)=cards(r2)
    cards(r2)=t
  Next
End Function
Function cards_display()
  n=1
  y=8
  For row=1 To 6
    x=68
    For col=1 To 9
      card=cards(n)
      card_img=LoadImage(card+".png")
      DrawBlock card_img,x,y
      FreeImage card_img
      x=x+74
      n=n+1
      If n=53 Then Exit
    Next
    y=y+98
  Next
End Function

Ok ... so where am I going with all this? I'm hoping to lead up to the game of Concentration where you have to find the pairs when all the cards are face down. Which leads us to:

Ex.3: Develop the above program so that the cards are dealt face down at first. Then as the player clicks on a card, the card turns over. Hint: you'll need another array to keep track of whether a card is face up or not. You'll actually need a third array for the card images - to reload them each cycle will thrash your hard drive severely! Note that cards_img(0) can be used to store the back of the card.  My solution.


Valid HTML 4.0 Strict Valid CSS