0 Favourites

Python noob needs help with syntax

This forum is currently in read-only mode.
  • import random
    
    class RmDef(object):	
    	def __init__(self, x, y, width, height, roomvar):
    		width = 0
    		roomvar = random.randint(1,3)
    			
    		if roomvar == 1:
    			width = random.randint(2, 4)
    		elif roomvar == 2:
    			width = random.randint(4, 6)
    		elif roomvar == 3:
    			width = random.randint(6, 8)[/code:1r9ehp96]
    
    Receiving this error
    
    [code:1r9ehp96]nameError: "width" is not defined[/code:1r9ehp96]
    
    I'm confused cause I'm defining width to be = 0. So why is it saying it's not defined?
  • Construct 3

    Buy Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Buy Now Construct 3 users don't see these ads
  • You are not defining in the right scope. I guess you want x, y, width, height and roomvar being members of the class and to be able to pass values to them when initializing the class?

    When using a variable name you are creating it on a global scope. To make it local you need to use 'self' within the class. Also 'width' and 'self.width' are then two different variables (they have different scope) and 'width' within the parantheses of __init__ is a parameter to that function.

    If you want a class that can be initialized with parameters {by calling something like "rd = RmDef(y=20, width=32)"} do this:

    import random
    
    class RmDef(object):	
        def __init__(self, x=0, y=0, width=0, height=0, roomvar=0):
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.roomvar = roomvar
    
            self.roomvar = random.randint(1,3)
    			
            if self.roomvar == 1:
                self.width = random.randint(2, 4)
            elif self.roomvar == 2:
                self.width = random.randint(4, 6)
            elif self.roomvar == 3:
                self.width = random.randint(6, 8)[/code:1jsbbyde]
    If your class doesn't need initialization parameters, do this:
    [code:1jsbbyde]import random
    
    class RmDef(object):	
        def __init__(self):
            self.x = 0
            self.y = 0
            self.width = 0
            self.height = 0
            self.roomvar = 0
    
            self.roomvar = random.randint(1,3)
    			
            if self.roomvar == 1:
                self.width = random.randint(2, 4)
            elif self.roomvar == 2:
                self.width = random.randint(4, 6)
            elif self.roomvar == 3:
                self.width = random.randint(6, 8)[/code:1jsbbyde]
    
    It is good practice to always set the variables at the start of __init__ even if they won't be used at that moment. This way you don't lose overview.
  • Thank you, I appreciate your help good sir.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)