[Tutor] invalid literal for int error in Game loop
Dave Angel
d at davea.name
Thu Dec 20 22:53:05 CET 2012
On 12/20/2012 04:34 PM, Ciaran Mooney wrote:
> Thanks for the feedback.
>
> Steve, If I set the FPS to a default of say 30, the game seems to run at this default FPS=30 regardless of the key pressed in the function.
>
> Dave, If I remove the the default value at the start of the function and add it to elif in the loop I get the following error:
>
>
> Traceback (most recent call last):
> File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 139, in <module>
> FPS = difficultyLevel()
> File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 50, in difficultyLevel
> return FPS
> UnboundLocalError: local variable 'FPS' referenced before assignment
>
Please don't top-post. Your message is now out of order with whatever
you're quoting below.
You don't show your new version of code, but clearly, your else is NOT
in the right place. If it were, then there would be no way that FPS
would be undefined.
And this is exactly why it's a good thing to use else rather than
defining FPS at the top. The error message shows you your error, or at
lest makes you think more about the problem.
You have a for-loop here. Is it possible that it's not executing at
all? If so, what value do you want for FPS? Do you just want to wait
till the user causes SOME event? or what?
And what about if you go around the loop multiple times? Do you want
the last value of FPS, or the first?
Assuming you want to take the first matching event that's waiting, you
could do this. The breaks get you out of the loop
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('b'):
FPS = 30
break
elif event.key == ord('m'):
FPS = 70
break
elif event.key == ord('h'):
FPS = 120
break
else:
FPS = 30 #default value
return FPS
This doesn't address the problem of the user not being fast enough at
hitting that key. Perhaps you want to wait till he hits something, or
till a timeout has passed, or something?
Without a clear spec in your head, the fact that we could help you get
your code to not crash is not the same as getting it right.
--
DaveA
More information about the Tutor
mailing list