Siddharth Nand Siddharth Nand - 4 years ago 107
Python Question

Can't figure out why sprite doesn't show up on my screen

I'm working on a game, and In this game I need a yellow rectangle to show up on the game window, but when I ran the code the yellow rectangle didn't show up. I'm drawing the rectangle in the

Player()
class. Can anyone help me?

main.py

# IMPORTS
import pygame
from config import *
from sprites import *

# GAME
class Game():
def __init__(self):
# INIT PYGAME
pygame.init()
pygame.mixer.init()

pygame.display.set_caption(TITLE)

self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
self.running = True

# NEW GAME
def new(self):
self.allSprites = pygame.sprite.Group()
self.player = Player()
self.allSprites.add(self.player)
self.run()

# RUN GAME
def run(self):
self.playing = True

while self.playing:
self.clock.tick(FPS)

self.events()
self.update()
self.draw()
self.animate()
self.collision()

# DRAW
def draw(self):
self.screen.fill(WHITE)

pygame.display.update()

# ANIMATE
def animate(self):
pass

# DETECT COLLISION
def collision(self):
pass

# CHECK FOR EVENTS
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.playing:
self.playing = False

self.running = False

# UPDATE GAME
def update(self):
self.allSprites.update()

# GAME OVER
def gameOver(self):
pass

# START SCREEN
def startScreen(self):
pass

# END SCREEN
def endScreen(self):
pass

game = Game()
game.startScreen()

while game.running:
game.new()
game.gameOver()

pygame.quit()
quit()


sprites.py

import pygame
from config import *

class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)

self.img = pygame.Surface((30, 40))
self.img.fill(YELLOW)
self.rect = self.img.get_rect()
self.vx = 0;
self.vy = 0;

def update(self):
self.vx = 0

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.vx -= 5
if keys[pygame.K_RIGHT]:
self.vx += 5
if keys[pygame.K_UP]:
self.vy -= 5
if keys[pygame.K_DOWN]:
self.vy += 5

self.rect.x += self.vx
self.rect.y += self.vy


config.py

# IMPORTS
import pygame

# ENTIRE GAME VARIABLES
TITLE = "Sky Jumper"
WIDTH = 480
HEIGHT = 600
FPS = 60

# COLORS
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)

Answer Source

You're not drawing your player at all. The only drawing is happening in your game's draw method, so try adding this:

def draw(self):
    self.screen.fill(WHITE)
    self.allSprites.draw(self.screen)
    pygame.display.update()

Also, btw, your Player's update() method won't run because it's indented under the init method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download