Making a game, I can't import a background image or sprite

Viewed 52

I'm a new programmer, trying to make a platformer-combat 2D scroller game and I have already created my background and a character sprite, but I'm trying to blit them into my code, but I get an error saying that

The first argument needs to be pygame.Surface()

When I do this, it then tells me

ValueError: size needs to be (int width, int height)

I've looked at quite a few questions about this, tried a bunch of things, and nothing works. Please help.

import pygame
pygame.init()

global X, Y, gameBackground
bg = [pygame.image.load("pygame/gameBackground.png")]
char = [pygame.image.load("pygame/characterStandingRight.png")]
#I have my .png files in a folder named "pygame" inside of my general program folder
windowWidth = 1366
windowHeight = 697
Width = 40
Height = 64
X = 5
Y = windowHeight - (Height + 5)
tick = 30
run = True

def redrawGameWindow():
    window.blit(pygame.Surface(bg), (0, 0)) #draws Window Background
    window.blit(pygame.Surface(char), (X, Y)) #draws Character Sprite
    pygame.display.update()
#above is where I have my errors of "pygame.Surface" and "(int width, int height)"

window = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption("Game")

while run:
    pygame.time.delay(tick)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    #other game code which controls character movement functions
    redrawGameWindow()

pygame.quit()
quit()
2 Answers

I think you are putting the list into blit, which produces an error. It should be:

window.blit(bg[0], (0, 0)) #draws Window Background

The error is caused by pygame.Surface(bg) respectively bygame.Surface(char), where bg and char are lists of objects. There is no constructor of a pygame.Surface by another Surface or even a list of Surface objects.

Note you've a list of backgrounds and a list of characters

bg   = [ pygame.image.load("pygame/gameBackground.png") ]
char = [ pygame.image.load("pygame/characterStandingRight.png") ]

To access an object in a list you've to use the index operator (e.g. char[0]). bg[0] and char[0] are pygame.Surface objects and can be used directly in the method blit(). e.g.:

def redrawGameWindow():
    window.blit(bg[0], (0, 0))
    window.blit(char[0], (X, Y))
    pygame.display.update()

If you need just a single pygame.Surface you would have to skip the square brackets (e.g. bg = pygame.image.load("pygame/gameBackground.png")).

bg   = pygame.image.load("pygame/gameBackground.png")
char = pygame.image.load("pygame/characterStandingRight.png")
def redrawGameWindow():
    window.blit(bg, (0, 0))
    window.blit(char, (X, Y))
    pygame.display.update()
Related