Home > database >  pygame "move_ip" method seems not working
pygame "move_ip" method seems not working

Time:01-03

I'm doing a simple script, using pygame, that simply moves a rectangle, but the method move_ip seems it is not doing anything (I followed the code found on a RealPython tutorial ). In sum, I got a class Player, as follows:

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pygame.Surface((75, 25))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect()

    def update(self, pressed_k):
        if pressed_k[K_UP]:
            self.rect.move_ip(0, -5)
        if pressed_k[K_DOWN]:
            self.rect.move_ip(0, 5)
        if pressed_k[K_LEFT]:
            self.rect.move_ip(-5, 0)
        if pressed_k[K_RIGHT]:
            self.rect.move_ip(5, 0)

Then I got an instance player of the class previously descripted, that is used in a loop, as follows:

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False

    pressed_keys = pygame.key.get_pressed() 
    player.update(pressed_keys)
    screen.fill((0, 0, 0))
    screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)) 
    pygame.display.flip()

When I run the code it creates the windows properly (displaying a white rectangle, representing the player) and it seems that the program read the keyboard input but the block representing the player does not make any move.

(The instance method .update is called properly and also the various 'if' statements work as they should but the relatives self.rect.move_ip don't make any change to the position of the player)

CodePudding user response:

The player is constantly drawn at (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)

screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)) 

You have to drag the player to the position stored in the rect attribute. The 2nd argument of pygame.Surface.blit) can be a rectangle. In this case the upper left corner of the rectangle will be used as the position for the blit:

screen.blit(player.surf, player.rect)

However, if you are using pygame.sprite.Sprite then you should also use pygame.sprite.Group.e.g.:

player_group = pygame.sprite.Group(player)

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False

    pressed_keys = pygame.key.get_pressed() 
    player_group.update(pressed_keys)

    screen.fill((0, 0, 0))
    player_group.draw(screen)
    pygame.display.flip()
  • Related