Home > front end >  Pygame .blit() not working in class, or in game loop
Pygame .blit() not working in class, or in game loop

Time:11-05

I was following a pygame tutorial, tested to see if the player blit was working and it wasnt, checked for problems but there were none that I could find, and then I tested a .blit() directly in the game loop and that didnt work so I've been stumped for a good bit now.

player class below, "Player_Down" should be irrelevant rn since its just an image

class Player():
    def __init__(self, x, y):
        direction = "down"
        self.image = player_down
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
    def draw(self):
        screen.blit(self.image, self.rect)


ply = Player(SCREEN_WIDTH // 2 , SCREEN_HEIGHT - 150)

Game loop with draw function called

running = True
while running:
    screen.fill((83,90,83))
    ply.draw()
    
    #event handler
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("Game quit via X button")
            running = False
    pygame.display.update()

CodePudding user response:

There is no problem with the code in the question. Your suspicion that blit does not work is wrong (alos see How to draw images and sprites in pygame?). The code works fine.
However, I suggest passing the screen Surface as an argument to draw method. See the minimal and working example:

import pygame

pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 400, 400
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

player_down = pygame.Surface((30, 30))
player_down.fill((255, 0, 0))

class Player():
    def __init__(self, x, y):
        direction = "down"
        self.image = player_down
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
    def draw(self, surf):
        surf.blit(self.image, self.rect)


ply = Player(SCREEN_WIDTH // 2 , SCREEN_HEIGHT - 150)

running = True
while running:
    
    #event handler
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("Game quit via X button")
            running = False

    screen.fill((83,90,83))
    ply.draw(screen)
    pygame.display.update()

pygame.quit()
exit()
  • Related