Blitz Basic Tutes - Final Jigaw Program

Graphics 640,480
SetBuffer BackBuffer()
SeedRnd MilliSecs()
Global last_n
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)
Dim pieces(n_pieces)
pointer_img=LoadImage("pointer.bmp")
img=LoadImage("hill_castle.jpg")
DrawBlock img,0,0
init()
shuffle()
last_n=0
Repeat
  display()
  DrawImage pointer_img,MouseX(),MouseY()
  Flip
  If MouseHit(1)
    n=which_one()
    If last_n=0 Then
      last_n=n
    Else
      t=piece_imgs(n):piece_imgs(n)=piece_imgs(last_n):piece_imgs(last_n)=t
      t=pieces(n):pieces(n)=pieces(last_n):pieces(last_n)=t
      last_n=0
    End If
  End If
Until KeyHit(1)
End

Function init()
  n=1
  y=0
  For row=1 To n_rows
    x=0
    For col=1 To n_cols
      piece_imgs(n)=CreateImage(piece_size,piece_size)
      GrabImage piece_imgs(n),x,y
      pieces(n)=n
      n=n+1
      x=x+piece_size
    Next
    y=y+piece_size
  Next
End Function

Function display()
  n=1
  y=0
  For row=1 To n_rows
    x=0
    For col=1 To n_cols
      DrawBlock piece_imgs(n),x,y
      If n=last_n Then
        Color 0,255,0
        Rect x,y,piece_size,piece_size,False
      End If
      n=n+1
      x=x+piece_size
    Next
    y=y+piece_size
  Next
  If check() Then
    Color 0,255,20
    Rect 0,0,640,480,False
    Rect 1,1,638,478,False
  End If
End Function

Function shuffle()
  For i=1 To 200
    r1=Rand(n_pieces)
    r2=Rand(n_pieces)
    t=piece_imgs(r1):piece_imgs(r1)=piece_imgs(r2):piece_imgs(r2)=t
    t=pieces(r1):pieces(r1)=pieces(r2):pieces(r2)=t
  Next
End Function

Function which_one()
  n=1
  y=0
  For row=1 To n_rows
    x=0
    For col=1 To n_cols
      If mouse_in(x,y,x+piece_size,y+piece_size) Then piece=n
      n=n+1
      x=x+piece_size
    Next
    y=y+piece_size
  Next
  Return piece
End Function

Function check()
  win=True
  For i=1 To n_pieces
    If pieces(i)<>i Then win=False
  Next
  Return win
End Function

Function mouse_in(x1,y1,x2,y2)
  x=MouseX(): y=MouseY()
  m=True
  If x<x1 Then m=False
  If x>x2 Then m=False
  If y<y1 Then m=False
  If y>y2 Then m=False
  Return m
End Function

Valid HTML 4.0 Strict Valid CSS