Python Forum

Full Version: Sprite not rendering
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to pygame. I've read a few examples on sprites, but I've missed some small, key point. This code raises no errors, but the intended sprite will not render. Instead I just see the blank, white background. What I should see is a green square with a '7' in the center. This block should be moving to the right.

import sys
import pygame

pygame.init()

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)
WHITE = (255, 255, 255)

main_surface = pygame.display.set_mode((500,500), 0, 32)
clock = pygame.time.Clock()
fps = 30
SYS_FONT = pygame.font.SysFont(None, 95)

class Block(pygame.sprite.Sprite):
    def __init__(self, color, text):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((80, 80))
        self.rect = self.image.get_rect()
        self.image.fill(color)
        self.text_surf = SYS_FONT.render(text, False, WHITE)
        self.text_rect = self.text_surf.get_rect(center=self.rect.center)
        self.image.blit(self.text_surf, self.text_rect)

    def update(self):
        self.rect.x += 5

sprites = pygame.sprite.Group()
block_7 = Block(GREEN, '7')
sprites.add(block_7)

sprites.draw(main_surface)

while True:
    main_surface.fill(WHITE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    sprites.update()
    clock.tick(fps)
here is the modified section of your code. You need to add the draw method to the main game loop and put pygame.display.update() after that.
#sprites.draw(main_surface)
 
while True:
    main_surface.fill(WHITE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    sprites.update()
    sprites.draw(main_surface)
    pygame.display.update()
    clock.tick(fps)
Cheers for using classes and pygame rects. Wink
(Oct-03-2019, 11:18 AM)metulburr Wrote: [ -> ]here is the modified section of your code. You need to add the draw method to the main game loop and put pygame.display.update() after that.
#sprites.draw(main_surface)
 
while True:
    main_surface.fill(WHITE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    sprites.update()
    sprites.draw(main_surface)
    pygame.display.update()
    clock.tick(fps)
Cheers for using classes and pygame rects. Wink

Thank you. I knew it was a simple mistake.