This is probably an easy problem to solve but I'm having a bit of difficulty. The error is UnboundLocalError: local: "switch" and that's all the error says. The line refers to the line switch = - switch in the following code:

boundary = game.getBoundary()
game.setBackground(java.awt.Color.black)

level = 1
maxX = -1
maxItem = 0
minX = boundary.getWidth()+1
minItem = 0
change = 0
switch = 1

class shootCollisionListener (events.CollisionListener):
    global switch
    def __init__ (self, item):
        self._item = item
    def collisionDetected(self, event):
        if(event.getSource()==boundary):
            switch = -switch
        elif(event.getSource().getType()=="projectile"):
            game.removeElement(event.getSource())
            game.removeElement(self._item)

I used global so I don't know why I'm getting this error.

When variables are assigned inside a function, they are always bound to the function's local namespace. The global namespace is never checked for name switch, therefore the error.
Example:

>>> switch = -1
>>> def test():
... 	return -switch
... 
>>> switch = test()
>>> switch
1
>>> def test1():
... 	switch = -switch
... 	return switch
... 
>>> test1()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 2, in test1
UnboundLocalError: local variable 'switch' referenced before assignment
>>> def test2():
... 	global switch
... 	switch = -switch
... 	return switch
... 
>>> test2()
-1
>>> test2()
1
>>>

The local namespace of a method doesnt see the namespace of the class. Inside a method, you can only access the variables from the local namespace and the variables defined at module level. So your global switch is misplaced.

That makes sense. Works now! Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.