1

I am new to pygame and python in general. Today I was trying to code a simplified TopDown movement. I did it and it runs without any issues. But i've got a problem anyways: The "player" is a rectangle but I want him to be an image or something like that. Is there a way to 'convert' a rect to an image?

Oh, and here's the code if you need it, I made it from another question I asked a week ago (or a bit longer):

import pygame

pygame.init()

win = pygame.display.set_mode((700, 700))
pygame.display.set_caption("TopDown")
clock = pygame.time.Clock()

player = pygame.Rect(350, 350, 40, 60)
vel = 1

run = True
while run:
    clock.tick(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    player.x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel
    player.y += (keys[pygame.K_s] - keys[pygame.K_w]) * vel
            
    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 255, 255), player)
    pygame.display.update()

pygame.quit()
0

1 Answer 1

1

Load the image with pygame.image.load(). This function returns a pygame.Surface object:

player_image = pygame.image.load("player_image.png").convert_alpha()
player_rect = player_image.get_rect(center = (350, 350))

Put the Surface onto the display with pygame.Surface.blit:

win.blit(player_image, player_rect)

Minimal example:

import pygame
pygame.init()

win = pygame.display.set_mode((700, 700))
pygame.display.set_caption("TopDown")
clock = pygame.time.Clock()

player_image = pygame.image.load("player_image.png").convert_alpha()
player_rect = player_image.get_rect(center = (350, 350))
vel = 5

run = True
while run:
    clock.tick(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    player_rect.x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel
    player_rect.y += (keys[pygame.K_s] - keys[pygame.K_w]) * vel
            
    win.fill((64, 238, 255))
    win.blit(player_image, player_rect)
    pygame.display.update()

pygame.quit()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.