Function Not getting called

2019-09-18 01:43发布

问题:

I have function which checks the score and will(I haven't finished) increases level if the score hits the given score, my function:

def levels(Score):
 if score >= 100:
   enemies = 6
   velocity = 2

and I'm calling it in the game loop:

levels(score)

The function never gets executed, my source code http://pastebin.com/JPZSTA6a Line: 35-38 and 150

Thank you

回答1:

The function is being called, but you are assigning to enemies and velocity in the function, so they are local to the function, and are then discarded when the function returns. So your function is called, but has no lasting effect.

You need to read about locals and globals in Python. As others point out you also have both Score and score here. Python is case-sensitive, those are different names.



回答2:

You have if score >= 100 when you probably meant if Score >= 100. The function gets executed, it's just that the if statement always evaluates to false.



回答3:

It's a scoping issue, the variables you're referring (enemies and velocity) to are created further down inside a while loop so they're not in scope in the function where you're trying to modify them. You need to read up on Execution model it should be able to clarify scoping rules.



回答4:

Your code, paraphrased:

def game():

    def levels(Score):
        print 'levels!'

    while start == True:
        print 'start is indeed True!'
        while not finish or falling: 
            'I am not Finnish'     
            for i in range(enemies):
                'alas for I am beset by enemies!'
                levels(score)

So, why isn't levels() being called? I suppose one of those many control flow items doesn't go the way you want. I can't say for example whether or not your enemies variable is empty but I can tell you that print is your friend.



标签: python pygame