Blitz Basic Tute #6 - Mousing Around

Time for you to show that you've mastered everything so far. For this exercise you'll need the new word Rect.

Ex.1: Draw a red rectangle to fill the top left quarter of a 640x480 screen. Your program is to include the mouse pointer.  My solution.

I'm sure that you noticed a bit of a problem with the mouse pointer! We can see its black background! Easily fixed! Use DrawImage instead of DrawBlock and BB will treat the black as transparent.

Here's what I'm aiming for - clicking on the rectangle will change it to green. To get started we'll just accept a click anywhere. The magic word is MouseHit(1) (the 1 means a left-click). It returns True or False to indicate whether the mouse has just been clicked. So we can say something like this:

If MouseHit(1) Then change colour

Of course "change colour" needs a bit of thought - BB isn't quite that friendly!

Again, I think it's easier to show you ... see if you can follow this:

Graphics 640,480
SetBuffer BackBuffer()
pointer_img=LoadImage("pointer.bmp")
red=True
Repeat
  If MouseHit(1) Then red=False
  Cls
  Color 0,255,0
  If red Then Color 255,0,0
  Rect 0,0,320,240
  DrawImage pointer_img,MouseX(),MouseY()
  Flip
Until KeyHit(1)
End

Maybe you're wondering why some BB words have brackets after them. The ones that do are the ones that return a value. eg MouseHit(1) returns either True or False while LoadImage(...) returns the location of the stored image. Such entities are called functions. The most amazing thing is that in BB we can create our own functions. Let me start by giving you one of my favourites that I use all the time. This function checks whether the mouse is in a rectangle with (x1,y1) at top-left and (x2,y2) at bottom-right.

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

Just add this code after the End statement in your program and have a go at:

Ex.2: Modify your program so that it only responds to a click on the rectangle itself.  My solution.

A little bonus for you - if you change red=False to red=not red in your program, clicking the rectangle will change the colour every time rather than just once!


Valid HTML 4.0 Strict Valid CSS