Blitz Basic Tute #5 - Shuffle the Cards

Returning to our deck of cards ... we know that

  card_img=LoadImage(n+".png")
  DrawBlock card_img,x,y

will draw card number n for us.

To draw all 52 cards we need a loop that will make n go from 1 to 52. The for-next loop was created just for that sort of task. It looks like this:

for n=1 to 52
  card_img=LoadImage(n+".png")
  DrawBlock card_img,x,y
next

Use graphics 800,600 this time so the cards will spread nicely across the page - a spacing of 14 works perfectly. Come back when you have the 52 cards spread neatly across the screen.

Now it gets tricky ... we want to shuffle the cards. To do this we need another great 'puter thingo ... this may be even better than loops! I'm talking about arrays.

Dim cards(52) will tell BB that we want an array called cards with room for 52 members. Probably easier to show you:

Graphics 800,600
SetBuffer BackBuffer()
Dim cards(52)
For i=1 To 52
  cards(i)=i
Next
x=0
y=0
For i=1 To 52
  n=cards(i)
  card_img=LoadImage(n+".png")
  DrawBlock card_img,x,y
  FreeImage card_image
  x=x+14
Next
Flip
WaitKey
End

Study that one real hard - once you master loops and arrays, you can do almost anything! To shuffle the cards, all we have to do is pick a random pair of cards and swap them. Do this a few hundred times and the cards will be well shuffled:

For i=1 To 500
  r1=Rand(52)
  r2=Rand(52)
  t=cards(r1)
  cards(r1)=cards(r2)
  cards(r2)=t
Next

I set my program to loop so everytime I pressed a key, I saw a new shuffle. I'll leave it to you to do the same.


Valid HTML 4.0 Strict Valid CSS