4.20: Checking Which Box The Mouse Cursor is Over
- Page ID
boxx, boxy = getBoxAtPixel(mousex, mousey) if boxx != None and boxy != None: # The mouse is currently over a box. if not revealedBoxes[boxx][boxy]: drawHighlightBox(boxx, boxy) if not revealedBoxes[boxx][boxy] and mouseClicked: revealBoxesAnimation(mainBoard, [(boxx, boxy)]) revealedBoxes[boxx][boxy] = True # set the box as "revealed"
getBoxAtPixel() function will return a tuple of two integers. The integers represent the XY board coordinates of the box that the mouse coordinates are over. How
getBoxAtPixel() does this is explained later. All we have to know for now is that if the
mousey coordinates were over a box, a tuple of the XY board coordinates are returned by the function and stored in
boxy. If the mouse cursor was not over any box (for example, if it was off to the side of the board or in a gap in between boxes) then the tuple (
None) is returned by the function and
boxy will both have
None stored in them.
We are only interested in the case where
boxy do not have
None in them, so the next several lines of code are in the block following the
if statement on line 2  that checks for this case. If execution has come inside this block, we know the user has the mouse cursor over a box (and maybe has also clicked the mouse, depending on the value stored in
if statement on line 4  checks if the box is covered up or not by reading the value stored in
revealedBoxes[boxx][boxy]. If it is
False, then we know the box is covered. Whenever the mouse is over a covered up box, we want to draw a blue highlight around the box to inform the player that they can click on it. This highlighting is not done for boxes that are already uncovered. The highlight drawing is handled by our
drawHighlightBox() function, which is explained later.
On line 6 , we check if the mouse cursor is not only over a covered up box but if the mouse has also been clicked. In that case, we want to play the "reveal" animation for that box by calling our
revealBoxesAnimation() function (which is, as with all the other functions
main() calls, explained later in this chapter). You should note that calling this function only draws the animation of the box being uncovered. It isn’t until line 8  when we set
revealedBoxes[boxx][boxy] = True that the data structure that tracks the game state is updated.
If you comment out line 8  and then run the program, you’ll notice that after clicking on a box the reveal animation is played, but then the box immediately appears covered up again. This is because
revealedBoxes[boxx][boxy] is still set to
False, so on the next iteration of the game loop, the board is drawn with this box covered up. Not having line 8  would cause quite an odd bug in our program.