I recently downloaded Kivy as it’s given me the most comprehensible tutorials and documentation, etc. I’ve tried pygame and cocos but never could get a foundation, and with Kivy it’s been easy.
So heres my problem, I’ve made a pong game, and I’m trying to make the game pause by stopping the pong ball, and then starting it again when it’s unpaused (by changing its velocity).
Here’s my code:
class PongGame(Widget):
...
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'escape':
#Why doesnt it work without global?
#If I don't use a global i get "tempBallVelocity referenced before assignment
global tempBallVelocity
tempBallVelocity = self.ball.velocity
self.ball.velocity = 0,0
if keycode[1] == '`':
#Make the ball go again, thus exiting pause
#This is where the error occurs if I don't use global
self.ball.velocity = tempBallVelocity
As you can see in the comments, If I don’t use global, I get referenced before assignment error. But it’s a local variable, I don’t understand why this is happening.
Anyone have any ideas? thanks?
Edit: Just to make sure everyone is clear in my intentions, I do NOT want to use a global, but it’s the only way it will work. I would prefer not to use globals.
If you fix the indentation error again you will see that:You can see that:
the escape
escapeshould work without the global, howevertempBallVelocitywill be considered as a local variable. If you want to modify a global variable you need to add the global declaration to tell python thattempBallVelocityis not local but global.In the second case,
tempBallVelocityis not locally initialized if you do not enter the escape block and thus cannot be used as a local RValue. In this case python should look for the variable outside of the class. IstempBallVelocityreally a global variable ?remark: if the cases are exclusive you should use
elifinstead ofiffor the second case.