Sign in to follow this  

Python scoping problem

This topic is 3597 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

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

This topic is 3597 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this