Search code examples
pythonimagepygamedrawblit

The image drawn in pygame does not match the location it is given


Hello everyone I am learning the basics of pygame. I recently ran into a problem; I decided to load an image and gave it a random location well within the pygame window.But the problem was that sometimes it just wont appear in the window. So I drew a black pointer at the place where the image was to be loaded. Then I found out that the black pointer doesnot coincide with the image and hence the image is not appearing in the location I want it to be in. So I want help solving this problem. Thank you in advance. Code:

import pygame
import random

pygame.init()

#Pygame starters
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Blob runner")
clock = pygame.time.Clock()
targetpng = pygame.image.load("target.png")
#Quit checker
crashed = False
#COLOURS
white = (255, 255, 255)
black = (0, 0, 0)


def draw_environment(x,y):    
    game_display.fill(white)
    #Image
    game_display.blit(targetpng,(x, y)) 
    #Black pointer
    pygame.draw.circle(game_display, black, (x, y), 5 )
    pygame.display.update()

x, y = random.randrange(0,display_width), random.randrange(0,display_height)

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        # print(event)

    draw_environment(x,y)
    clock.tick(30)

pygame.quit()
quit()

Image:enter image description here


Solution

  • The image has a size. it may happen that the image is out of the window at the right or at the bottom. The origin of the blit puts the the top left corner of the image to the specified position.

    If you wan that the image is centered at (x, y), the you have to get a pygame.Rect with the size of the image (get_rect) and set the center of the rectangle to the specified position (keyword argument). Use the rectangle to specify the position for the blit operation.

    img_rect = targetpng.get_rect(center = (x, y))
    game_display.blit(targetpng, img_rect) 
    

    Th image has a size, thus the random position for the image has to be in range [image_size/2, window_sizw - image_size/2].
    The width and height of a pygame.Surface can be get by get_width()/get_height() or get_size(). For instance:

    img_size = targetpng.get_size()
    x = random.randrange(img_size[0]//2, display_width  - img_size[0]//2)
    y = random.randrange(img_size[1]//2, display_height - img_size[1]//2)