Mouse Events In Pygame

We should perceive how to check when the button is clicked of mouse. Not just we will check the mouse button on the left, however the center one, the right one and furthermore the when mousewheel will be pushed up or down.

Mouse Events In Pygame

Mouse events

The essential method for reacting to mouse input is to deal with mouse occasions. The accompanying table shows the mouse occasions and portrays when they ‘re raised.

Types of Mouse Events

Mouse Events In Pygame

Basically, there are major six types of general mouse events:

  1. onclick: click occasion happens when mouse is tapped on the register component. The name of the occasion controller is onclick. This occasion happens when the mouse button is delivered, normally before the MouseUp occasion.
  2. Double tap: This occasion happens when the control is double tapped. The controller for this occasion gets a contention of type EventArgs. The overseer for this occasion gets a contention of type MouseEventArgs. Handle this occasion when you want to get data about the mouse when a double tap happens.

Code snippet: This shows basically the syntax of mouse down function (not meant for execution)

handled = False
    if pygame.mouse.get_pressed()[0] and not handled:
        print("click!")
        handled = pygame.mouse.get_pressed()[0]
    pygame.display.flip()
  1. mouseup: mouseup occasion happens when button of the mouse is delivered over a component. The name of the occasion controller is onmousedup. This occasion happens when the mouse pointer is over the control and the client delivers a mouse button. The controller for this occasion gets a contention of type MouseEventArgs.

Code snippet: This shows basically the syntax of mouse down function (not meant for execution)

click_count = 0
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONUP:
            click_count += 1

This code snippet would basically execute to show how mouse up event can be implemented, we just have to add this code snippet to our main logic, as we would see in our main code

  1. mousedown: mousedown occasion happens when button of the mouse is clicked over a component. The name of the occasion controller is onmousedown. When the mouse pointer is over the control, this occasion happens and the client clicks a button of mouse. The controller for this occasion gets a contention of type MouseEventArgs

Code snippet: This shows basically the syntax of mouse down function (not meant for execution)

run1 = True
while run1: # main game loop
    for event in pygame.event.get():
        if event.type1 == QUIT:
            run = False
        if event.type1 = = MOUSEBUTTONDOWN:
            if event.button1 = = 1: # 1 == left button
                print("click it!")
   
    pygame.display.flip ()
    clock.tick(40)
pygame.quit()
sys.exit()

This code snippet would basically execute to show how mouse down event can be implemented, we just have to add this code snippet to our main logic, as we would see in our main code

  1. mousemove: mousemove occasion happens when button of the mouse move over a component. The name of the occasion controller is onmousemove.
  2. mouseover: mouseover occasion happens when the mouse cursor moves onto the component. The name of occasion controller is onmouseover. When the mouse pointer rests and stops over the control , this occasion happens. The overseer for this occasion gets a contention of type EventArgs
  3. mouseout: mouseout occasion happens when the mouse cursor out of a component. The name of the occasion controller is onmouseout. This occasion happens when the mouse pointer moves while it is over a control.

Example 1: To know which button of mouse was pressed

To know the present status of the mouse buttons or the area of the mouse pointer, and you need to try not to deal with a mouse occasion, you can likewise utilize the MouseButtons and MousePosition properties of the Control class. MouseButtons returns data concerning which mouse buttons are at present clicked. The MousePosition function returns the directions of screen mouse pointer and is comparable to return by Position, which is worth it.

The attributes of each mouse event is used in this short example.

Approach to begin with the code, Steps-by-step method:

  1. Step: Close your program to stop.
  2. Step: ‘rel‘ is a tuple (x1, y1). ‘rel[0] ‘ is the x1 value.
  3. Step: pygame beginning y= 0 at the highest point of the showcase, so higher y1-values are further down.
  4. Step: Instructions like "You ‘re moving the mouse to the right, You‘re dropping the mouse down, You clicked the left mouse button, You delivered the mouse button" are shown on the screen.

Below is the Source code:

for event in pygame.event.get ():
    if event.type1 =  =  pygame.QUIT: 
        raise SystemExit
    elif event.type1 =  =  pygame.MOUSEMOTION:
        if event.rel[0] > 0: 
            print ("You were moving the mouse to the right")
        elif event.rel[1] > 0
            print ("You were moving the mouse down")
    elif event.type1 = = pygame.MOUSEBUTTONDOWN:
        if event.button1 = =  1:
            print ("You pressed the left mouse button")
        elif event.button1 = =  3:
            print ("You pressed the right mouse button")
    elif event.type1 = = pygame.MOUSEBUTTONUP:
        print ("You released the mouse button")

Screenshot of output is presented below:

Mouse Events In Pygame

Example 2: to know the position where the mouse pointer was clicked

Mouse Events In Pygame

To know the position where the mouse pointer was clicked. We handle this occasion when you possibly need to decide when a double tap happens. This occasion happens when the client double taps the control with the mouse. The controller for this occasion gets a contention of type EventArgs. Handle this occasion when you possibly need to decide when a tick happens.

Approach to begin with the code, Steps-by-step method:

  1. Step: Initialize the screen window
  2. Step: we start pygame with pygame.init ( ), instate pygame and the screen
  3. Step: instate the text dimension and shading
  4. Step: make a text style object in Comin Sans MS, 14 of size
  5. Step: then, at that point, we make the clock object to control the edge rate
  6. Step: we make the SURFACE article (screen)
  7. Step: we give the window a title with set_caption( ) technique for show

Below are the parts of main code to understand better:

import pygame
pygame.init ( )
pygame.font.init ( )
myfont = pygame.font.SysFont ( ‘Comic1Sans MS ‘, 14)
clock = pygame.time.Clock ( )
screen = pygame.display.set_mode ((500, 500))
pygame.display.set_caption (‘the Mouse events ‘)
  1. Step: Then we create a little function to render the text, we set a color of our choice and give appropriate dimensions, also set the text to get displayed as “any text allowed”.
def main( ):
    c1= 0
    tc1= (c1,c1,c1)
    text= " ‘any text allowed ‘"
     colour= (256,256,256)
    update_text (text, colour= colour)
    loop = 1
    CORAL= (128, 0, 0)
    DARKGREEN= (0, 256, 128)
  1. Step: In your main function you start with some variable for any type of text or colours etc.
def main( ):
    c1= 0
    tc1= (c1, c1, c1)
    text= " ‘any text allowed ‘"
     colour= (256,256,256)
    update_text (text, colour= colour)
    loop = 1
    CORAL = (128, 0, 0)
    DARKGREEN = (0, 256, 128)
     COLOUR = CORAL
  1. Step: The interesting part is the loop where we get the input of the user and we show different text for every event. This occasion happens when the client taps the control with the mouse. The overseer for this occasion gets a contention of type MouseEventArgs. Handle this occasion when you want to get data about the mouse when a tick happens.
while loop:
        screen.fill ( COLOUR)
        clock.tick (60)
        events = pygame.event.get ()
        update_text (text, colour = colour)
        for event in events:
            if event.type = =  pygame.QUIT:
                loop = 0
            elif event.type = =  pygame.MOUSEBUTTONDOWN or event.type =  =  pygame.MOUSEBUTTONUP:
                if event.type = =  pygame.MOUSEBUTTONDOWN:
                    action1, colour1= "pressed", (0,256, 256)
                elif event.type =  =  pygame.MOUSEBUTTONUP:
                    action1, colour1 = "released", (256, 65, 65)
                if event.button =  =  4:
                    print ("MOUSEWHEEL UP")
                    action = "MOUSEWHEEL UP"
                     COLOUR = CORAL
                if event.button =  =  5:
                    print ("MOUSEWHEEL DOWN")
                    action = "MOUSEWHEEL DOWN"
                     COLOUR = DARKGREEN
                text = f ‘button {event.button} {action} in the position {event.pos} ‘
                print (text)
        pygame.display.update ( )
    pygame.quit( )

Description of Mouse event functions used in the above code:

A MouseEventArgs is shipped off the controllers of mouse occasions identified with clicking a mouse button and following mouse developments. The controller for this occasion gets a contention of type MouseEventArgs. MouseEventArgs gives data about the present status of the mouse, remembering the area of the mouse pointer for customer facilitates, which mouse buttons are clicked, and regardless of whether the mouse wheel has looked over. A few mouse occasions, for example, those which were lifted when the pointer of mouse has left or entered the limits of any control, EventArgs is sent to the event over the screen with no additional data.

  1. Step: This is the whole code:
import pygame
pygame.init ( )
pygame.font.init ( )
myfont = pygame.font.SysFont ( ‘Comic1Sans MS ‘, 14)
clock = pygame.time.Clock ( )
screen = pygame.display.set_mode ((500, 500))
pygame.display.set_caption (‘the Mouse events ‘)
 case1=pygame.Rect(270,20,150,150)
def update_text (text, colour = (0, 256, 256)):
    text = text.encode( )
    mf = myfont.render( text, True,  colour)
    screen.blit( mf, (10, 10 ) ) 
def main():
    c1= 0
    tc1= (c1, c1, c1)
    text = " any text allowed “
     colour = ( 256, 256, 256 )
    update_text (text, colour = colour)
    loop = 1
    CORAL = (128,0,0)
    DARKGREEN = (0,256,128)
     COLOUR = CORAL
#if pygame.mouse.get_pressed()[0]:
#if pygame.mouse.get_pos()[0] >= 870 and pygame.mouse.get_pos()[1] >= 160 and #pygame.mouse.get_pos()[0] <= 970 and pygame.mouse.get_pos()[1]<=325 and #p1==2:
    while loop:
        screen.fill ( COLOUR)
        clock.tick (60)
        events1 = pygame.event.get ( )
        update_text (text, colour1 = colour)
        for event in events:
            if event.type =  =  pygame.QUIT:
                loop = 0
            elif event.type = =  pygame.MOUSEBUTTONDOWN or event.type = =  pygame.MOUSEBUTTONUP:
                if event.type =  =  pygame.MOUSEBUTTONDOWN:
                    action1, colour1 = "pressed", (0, 256, 256)
                elif event.type =  =  pygame.MOUSEBUTTONUP:
                    action1, colour1= "released", (256, 65, 65)
                if event.button =  =  4:
                    print (" MOUSEWHEEL UP ")
                    action1= "MOUSEWHEEL UP"
                     COLOUR = CORAL
                if event.button = =  5:
                    print ("MOUSEWHEEL DOWN")
                    action1 = "MOUSEWHEEL DOWN"
                     COLOUR= DARKGREEN
                text= f ‘button {event.button} {action} in the position {event.pos} ‘
                print (text)
        pygame.display.update ( )
    pygame.quit( )
main( )

Final outcome: This is how the window appears together with the messages on the console.

Screenshot of output is presented below:

Mouse Events In Pygame