Jump to content
  • Advertisement
Sign in to follow this  
nayon

Python scoping problem

This topic is 3780 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have the following code:
global mousepos
class SpaceGameWindow(window.Window):


...
    
    def __init__(self, *args, **kwargs):
        self.max_monsters = 20
        mousepos  =[0,0]

...


    def on_mouse_motion(self, x, y, dx, dy):
        mousepos = [x,y]

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        mousepos = [x,y]

    def on_mouse_press(self, x, y, button, modifiers):

        if (button == 1):
            self.bullets.append(Bullet(mousepos,self.ship
                    , self.bullet_image
                    , self.height
                    , x=self.ship.x + (self.ship.image.width / 2) - (self.bullet_image.width / 2)
                    , y=self.ship.y))


but it gives me the following error on the line where I create the bullet object:
... in on_mouse_press
    self.bullets.append(Bullet(mousepos,self.ship
NameError: global name 'mousepos' is not defined

I'm using python 2.5.1 Anyone have any ideas as to how I can solve my problem?

Share this post


Link to post
Share on other sites
Advertisement

In your class __init__ function, mousepos is only declared locally for that function. You have defined it the same way in the on_mouse_motion and on_mouse_drag functions as well.

In order to make mousepos a member of this class, you must explicitly define it as such. The easiest way would be to simply prefix all definitions of mousepos with 'self.'. Basically, do the same thing you did with self.max_monsters.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!