Search code examples
pygamespritepygame-surface

How do I draw an object on the screen inside of a sprite class?


So I'm trying to draw a rectangle with another rectangle on top, using Sprites. I made a class for the player and did some basic setup, but when I tried to blit the second rectangle on top, it didn't work. I did some testing and found out that I can't even draw lines or rectangles from inside this player class.

Here's my basic testing code:

import pygame as pg
pg.init()

width, height = 800, 800
screen = pg.display.set_mode((width, height))
run = True


class Player(pg.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pg.image.load("test_image.png")
        self.rect = self.image.get_rect()

    def update(self):
        pg.draw.rect(screen, [0, 255, 0], (200, 200, 100, 50))
        print("test")


def draw_window():
    screen.fill((255, 255, 255))
    playerGroup.draw(screen)
    pg.display.update()


playerGroup = pg.sprite.GroupSingle()
playerGroup.add(Player())

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

    playerGroup.update()
    draw_window()

This is what i get: image

The blue thing is the player image that gets drawn normally in the top left corner. The rect that i'm trying to draw inside the update() method however is nowhere to be seen, even though i can clearly see the method gets called with the print("test"). This isn't just true for pg.draw() but also for surface.blit()

Why is this and how do i fix it?


Solution

  • screen.fill((255, 255, 255)) fills the entire display with a white color. Anything previously drawn will be lost. You must call playerGroup.update() after clearing the display and before updating the display. e.g.:

    def draw_window():
        screen.fill((255, 255, 255))
        playerGroup.update()
        playerGroup.draw(screen)
        pg.display.update()