Marko Scekic
Marko Scekic

Reputation: 101

Cannot draw sprite to screen

I started creating my first pygame game that uses multiple modules(.py files) for easier understanding the code so here we go.

main.py

import pygame,sys
from Player import *
from groups import *
from constants import *
from Events import *

pygame.init()
screen = pygame.display.set_mode(size)
player = Player()
player.add_to_group()

while True:
    player.draw(screen)
    event = Event()

Player.py

import pygame
from groups import *


class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([30,30])
        self.image.fill([255,0,0])
        self.rect = self.image.get_rect()

    def move_player(self):
        key = pygame.key.get_pressed()
        if key[pygame.K_DOWN]:
            self.rect.y += 1
        elif key[pygame.K_UP]:
            self.rect.y -= 1
        elif key[pygame.K_RIGHT]:
            self.rect.x += 1
        elif key[pygame.K_LEFT]:
            self.rect.x -= 1

    def add_to_group(self):
        all_sprite_list.add(self)

    def remove_from_group(self):
        all_sprite_list.remove(self)

    def draw(self,surface):
        surface.blit(self.image,(0,0))

groups.py

import pygame
all_sprite_list = pygame.sprite.Group()

constants.py

import pygame

size = width,heighth = 700,400

Events.py

import pygame,sys

class Event(object):
    def __init__(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

And the result should be a red square in the top left corner representing the player. But no matter I do it, I don't get any errors but it only just shows a blank black window.

I tried to fix it several times (like using .draw to draw the entire "all_sprite_list") but nothing worked.

Upvotes: 3

Views: 2115

Answers (1)

pmoleri
pmoleri

Reputation: 4449

You need to update or flip the display:

while True:
    player.draw(screen)
    event = Event()
    pygame.display.update()

Also I recommend you to handle the events at the main loop or at least not in an init method, prehaps you can create the Events object and call a method always in the same object.

The order should be:

  1. Handle events to update game state
  2. Clean background screen.fill()
  3. Draw
  4. update display
  5. Use Clock to keep a fps rate.

Upvotes: 1

Related Questions