So I am doing a lab regarding pong and I was lost on the concept of collidepoint a function in pygame, which checks whether the center of the circle is inside the paddle. Upon looking at documentation I was still confused since I am very new to programming and I am really having a hard time settling in and getting a grasp of the new skills thrown at me. I would really appreciate if someone could help me out by explaining it a bit more and maybe giving a basic simple example.
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    1 Answers
5
            
            
        The point-collision is documented in the PyGame Rect class.
Essentially you pass a co-ordinate to pygame.Rect.collidepoint(), and it will return True if that point is within the bounds of the rectangle.
import pygame
# Window size
WINDOW_WIDTH=400
WINDOW_HEIGHT=400
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Point Collision")
BLACK = (  50,  50,  50 )
GREEN = (  34, 139,  34 )
BLUE  = ( 161, 255, 254 )
# The rectangle to click-in
# It is window-centred, and 33% the window size
click_rect  = pygame.Rect( WINDOW_WIDTH//3, WINDOW_HEIGHT//3, WINDOW_WIDTH//3, WINDOW_HEIGHT//3 )
rect_colour = BLACK
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
    # Handle all the events
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            mouse_position = pygame.mouse.get_pos()             # Location of the mouse-click
            if ( click_rect.collidepoint( mouse_position ) ):   # Was that click inside our rectangle 
                print( "hit" )
                # Flip the colour of the rect
                if ( rect_colour == BLACK ):
                    rect_colour = GREEN
                else:
                    rect_colour = BLACK
            else:
                print( "click-outside!" )
    # update the screen
    window.fill( BLUE )
    pygame.draw.rect( window, rect_colour, click_rect)  # DRAW OUR RECTANGLE
    pygame.display.flip()
    # Clamp the FPS to an upper-limit
    clock.tick_busy_loop( 60 )
pygame.quit()
Note the use of the collidepoint() in the lower half of the code:
if ( click_rect.collidepoint( mouse_position ) ):  
Here the code is checking that the co-ordinate recently discovered via a mouse-input event is within the click_rect (a pygame.Rect declared before the main loop).  If the co-ordinates are within the rectangle, it is draw in a different colour.
The bulk of the code here is to simply open the window, and run the main input/update loop.
 
    
    
        Kingsley
        
- 14,398
- 5
- 31
- 53
