-2

maze game - previous said walls was not defined until I moved walls=[] out of the game loop(while True:)

class Wall (object):
    def __init__(self,pos):
        walls.append(self)
        self.rect = pygame.Rect(pos[0], pos[1], 16, 16)



    x = 0
    y = 0

    for row in level:
        for col in row:
            if col == 'W':
                Wall((x, y))
            if col == "E":
                end_rect = pygame.Rect (x, y,16,16)
            x = x + 16
        y = y + 16
        x = 0
tess123
  • 11
  • 2
    `walls` is not defined here. Where is `walls=[]`? – HavelTheGreat Mar 04 '15 at 19:48
  • that isn't the whole code. walls = [] is defined at the top although that might not be the right place for it. – tess123 Mar 04 '15 at 19:52
  • Where is the error that you're getting? I don't see a `wall` to be undefined. – krillgar Mar 04 '15 at 19:53
  • You can't instantiate an object inside the class's scope outside the methods. The code on the bottom should be global. See [here](http://stackoverflow.com/questions/14841203/python-instantiate-class-within-class-definition) for more. – Malik Brahimi Mar 04 '15 at 19:56

1 Answers1

2

Try this, half your code should be global, this is a scope issue. See here for more.

class Wall (object):
    def __init__(self,pos):
        walls.append(self)
        self.rect = pygame.Rect(pos[0], pos[1], 16, 16)

x = 0
y = 0

for row in level:
    for col in row:
        if col == 'W':
            Wall((x, y))
        if col == "E":
            end_rect = pygame.Rect (x, y,16,16)
        x = x + 16
    y = y + 16
    x = 0

Basically, the code in the class body is executed before the class is even created; thus, you would not be able to instantiate an object of the given class inside the class scope.

Community
  • 1
  • 1
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70