Click for Points ================ Goals ----- - Use events to detect mouse clicks - Use Pythagorean theorem to calculate the distance between the mouse and the ball - Update the score if they click the ball. - Display the score as text in the Pygame window Starter code ------------ .. literalinclude:: code/bouncing_ball_solution.py Video Tutorial -------------- .. raw:: html What you need to do ------------------- - Add a second ball. *Do not* copy and paste! **Final code** .. literalinclude:: code/click_for_points_solution.py :linenos: :emphasize-lines: 2, 6, 9, 26, 28, 41-48, 71-72 **Breakdown** .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 6 If we want to handle mouse click events, we most likely want to use the ``MOUSEBUTTONDOWN`` event. This should imported from ``pygame.locals``. This will allow us to use the ``MOUSEBUTTONDOWN`` event type on line ``41``. .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 41-48 .. note:: Sometimes the imports from ``pygame.locals`` can get a little long. You can also reference the ``MOUSEBUTTONDOWN`` event directly from ``pygame.locals`` right in the if statement. .. code-block:: python elif event.type == pygame.locals.MOUSEBUTTONDOWN: # handle the click You can also reference anything else from ``pygame.locals`` like this as well. Let's breakdown how points are scored: .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 43-48 Line ``43`` does a convenient Tuple-unpacking for us to separate out the ``x`` and ``y`` component of the mouse coordinate. Then, we set up the Pathagorean Theorem to get the distance between the mouse and the center of the circle. We then check to see if the distance is less than the circle's radius. If it is, then that means it's a click on the circle. Next we can draw some text to the screen to show the score. The first step is to initialize pygame's ``font`` module. .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 9 The next step is to actually load a font from the system. If the font you choose is not on your system, pygame will give you some default alternative. .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 28 Once the font is loaded, we can use it to render some text. Because this text may change from frame to frame, it must be rendered in the game-loop. .. literalinclude:: code/click_for_points_solution.py :lineno-match: :lines: 71-72 Finally, the renderd text gets "blitted" to the screen (whatever that means) at the location provided. .. note:: If you have text that won't change from frame to frame, you could demonstrate your keen insight by rendering the text only once, outside the game-loop. Of course, you must still "blit" the rendered text in the game-loop or else it won't show.