Pygame Problems Rect

Viewed 47

I am a new pygame user and I have a problem. I want to move an image with pygame.Rect but it's not working. I learn pygame from Tech With Tim. Here is the whole code.

import pygame
win = pygame.display.set_mode((800,600))
run = True
image = pygame.image.load("spaceship.png")
image = pygame.transform.scale(image,(50,50))
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    win.fill((255,255,255))
    red = pygame.Rect(50,50,50,50) 
    win.blit(image,(red.x,red.y))
    red.x += 1
    pygame.display.update()

Thanks!

2 Answers

Actually the object is recreated continuously at its initial position in the aplicaition loop. You have to create the pygame.Rect object before the loop. Additionally I recommend to limit the frames per second:

import pygame
win = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()

image = pygame.image.load("spaceship.png")
image = pygame.transform.scale(image,(50,50))
red = pygame.Rect(50,50,50,50) 

run = True
while run:
    clock.tick(6ß)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    win.fill((255,255,255))
    win.blit(image,(red.x,red.y))
    pygame.display.update()

    red.x += 1

pygame.quit()

The answer above is totally coorect, i just wanna give you a tip for your future development being to use Rect objects like so:

red = image.get_rect()  #so the rect has exactly the dimension of the image

red.topleft = (tuple(coords))  #to change position

This has several advantages:

  • you can use methods like collidepoint to check collisions with the image and other objects ( red.collidepoint(tuple(coords)) );

  • using a Rect like a tuple just loses its meaning;

  • you can also adjust the positions with topright, center, bottomleft, midright... ;

  • it's more intuitive to read and so to debug;

  • it's common practice.

It also has many other advantages.

Also read the Rect documentation on the pygame website, it's quite useful!


The last advice i'll give you is to find other more adequate sources to learn pygame since Tech With Tim tutorials are good but only for your first experience, to make a full game you need to acquire better knowledge. In C:\Program Files\Python38\lib\site-packages\pygame\examples you can find some really good and commented examples to get going.

Related