5.2.2 - Move as my mouse commands

In the previous module we learned how to 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 previously created to draw a square and a circle from here

Copy the following line to line 36 taking care of indentation

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

The first command creates a tuple 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 54)  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?


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