How to get mouse position in Pygame?

In this Pygame tutorial, we will explore how we can return the current Mouse Position on our Game Window. Knowing the current position of the mouse is necessary to perform basic tasks, such as interaction with objects (through mouse cursor) or drag and drop features.


How to get current Mouse Position?

To get the mouse position, all we have to do is call the pygame.mouse.get_pos() as shown below.

pygame.mouse.get_pos()

This function returns a Tuple containing two integer values. The first integer value represents the current x-position, and the second value represents the current y-position.

Its also important to remember, that in Pygame the top-left corner is the (0, 0) coordinate. The x values grow from left to right, and y values grow from top to bottom.


Mouse Position with Events

Now that we know which function to use, we need a way to actually call it somehow. The easiest and most practical way of doing so, is with the help Mouse Events.

We will be using the MOUSEMOTION event in Pygame, which triggers whenever the Mouse is moved. If you run the below code, you will observe a continuous stream of coordinate pairs printed out to the console as you move your mouse.

import pygame

pygame.init()
surface = pygame.display.set_mode((600, 400))

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            print(pygame.mouse.get_pos())
        if event.type == pygame.QUIT:
            exit()

    pygame.display.update()

Here is some sample output from our execution of this program.

(336, 58)
(351, 51)
(369, 42)
(387, 32)
(402, 25)
(418, 17)
(431, 10)
(442, 4)
(453, 0)

The slower you move the mouse, the closer together the values will be. Likewise, the opposite is also true.

We can also use several other mouse related events (such as mouse clicks) with the pygame.mouse.get_pos() function.


This marks the end of the How to get mouse position in Pygame? Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments