Week 4 - Section 1 - Graphics

Chapter 6.4 - Move as my mouse commands

6.4 - Move as my mouse commands

In the previous chapter we show how we can move a rectangle changing the coordinates of the starting point.

Pygame offers a method for moving objects using the mouse. First of all we must know where the mouse position is. To do so open the file we created to draw a square and a circle from here

Copy the following line to line 46 taking care of indentationCircleSquare

# Get Mouse Position pos = pygame.mouse.get_pos() x = pos[0] y = pos[1] print(x,y)


The first command create a list of two numbers that are the coordinates of the mouse. The following commands assign the x and y coordinates to variables x and y. The print command can be commented out. It exists to view the coordinates as you move the mouse.

Now we will use these coordinates to move the red circle.

Change the line that draws the circle (around line 55)  to

pygame.draw.circle(screen, RED, [ x,  y], 30, 0) 

and run the code

Wow!! Move as i command you.

You can comment the line that prints the position of the mouse (around line 50)

You can download the code from here and test it.

Move the circle near the white square.
Is it on top or the square is on top?

Exercises

  • Can you modify the code to have the square on top?
  • Can you modify the code to move the square?