Python list not returning correct value of complex object

Viewed 45

I am writing a platformer game using python 3.6.9 & the pygame library. I'm trying to create all of the game objects, then put them all in a list in order to blit them all to the screen in a for x in gameObjectList loop.

Each of the game objects in question has an attribute img, which I assign to pygame.image.load("slime-character.gif"). This stores the image as a pygame.Surface object. The window (screen) has a function blit, that takes a Surface object (which is an image) and either an x and y coordinate pair or a pygame.Rect, which it takes the x and y from.

My code does:

for x in gameObjects:
        screen.blit(x.img, x.rect)

but it throws an error, saying that x.img is an int. Printing this, it appears to be 200. Printing this without the iterator print(gameObjects[0].img) gives me the same thing.

BUT, if I print the object's value itself print(object1.img) I get out a pygame.Surface object, which is what I need to blit.

It's impractical for me to hardcode every possible object to appear, so I need to refer to their images from a list of the objects. But when I do, it gives me an incorrect datatype. Does anyone know why this is happening/a workaround so I can access the data I need?

Thanks in advance. Link to full code (89ish lines) on Google Drive.

EDIT: solved thanks to a comment by Chris Doyle: I'd forgotten to put screen as a parameter for movableObjs. I'm leaving this question up though, in case anyone can explain the program's behavior (working without list but failing when referred to from a list).

1 Answers

First of all Class names should normally use the CapWords convention. See Style Guide for Python Code - Class Names.
Use rename gameObjectRef by GameObjectRef, gameObj by GameObj and movableObj by MovableObj.


The issue is object2 respectively the class movableObj. The class movableObj is derived from the class gameObj. The first argument to the constructor of gameObj is screen. You have to pass screen to the constructor of gameObj in the super call o fht constructor:

Do

gameObj.__init__(self, img, xpos, ypos, w, h, visible, active)

gameObj.__init__(self, screen, img, xpos, ypos, w, h, visible, active)

in

class movableObj(gameObj):
    def __init__(self, screen, img, xpos, ypos, w, h, gravity=1, xvel=0, yvel=0,
                 visible=False, leaveScreen=False, active=True):
        gameObj.__init__(self, screen, img, xpos, ypos, w, h, visible, active)
        self.gravity = gravity
        self.xvel = xvel
        self.yvel = yvel
        self.leaveScreen = leaveScreen

Further more you have to pass screen to the constructor when you create an instance of movableObj:

object2 = movableObj(imgslime, 600, 200, 20, 20, 0, 2, 0)

object2 = movableObj(screen, imgslime, 600, 200, 20, 20, 0, 2, 0)
Related