How to get the mouse position in pygame

We can get the mouse position with pygame.mouse.get_pos()



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code and hover your mouse on the pygame window. This will print mouse position.

We can me this interesting by moving a rectangle based on the mouse position.

We just have to know the mouse position in the coordinate ( x,y)

In the previous program print(mouse_postion) shows the tuble value

so we can get the x, y value by

mouse_position=pygame.mouse.get_pos()
x,y=mouse_position

As we get the x,y value it will be easy to apply in the next example



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	x,y=mouse_position
	screen.fill((255,255,255))
	pygame.draw.rect(screen,(100,100,100),(x,y,60,40),5) #rect(surface,color,(x,y,height,width)
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code you will find that rectangle is attach to the mouse position

Related Posts

Send Desktop notification from pygame
April 29, 2024

For notification handling we will use plyer library We will add this functionality in our pygame code The complete code import pygame import sys from pygame.locals import * from plyer import notification pygame.init() clock = pygame.time.Clock() user_display = pygame.display.Info() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) background = (255, 255, 255) red = […]

Pygame Project: Create the simplest digital clock
April 28, 2024

We will use python datetime module for our clock; We get the current time and separate the time into hour minutes and second. First get the current time Get the time in hour, minute and second Now got our clock time components. It will be like this import datetime current_time = datetime.datetime.now() hour = current_time.hour […]

Simulate Bird Flocking Behavior with pygame: Algorithm and Code Explained
March 23, 2024

Bird flocking is a wonderful example of how simple behaviors can lead to complex, beautiful patterns in nature. We’ll learn the key principles behind this flocking behavior and write a python program to simulate this wonderful phenomenon. The principles Bird Flocking Simulation Algorithm Setting Up the Simulation Each Frame of the Simulation The pygame example […]