What's causing this variable referenced before assignment error?

后端 未结 3 938
深忆病人
深忆病人 2021-01-21 18:58

This is the code that I am working with:

import pygame

global lead_x
global lead_y
global lead_x_change
global lead_y_change

lead_x = 300
lead_y = 300
lead_x_c         


        
3条回答
  •  执笔经年
    2021-01-21 19:41

    Python's handling of "global" variables is indeed a bit weird, especially if you're not accustomed to it.

    The simple fix for your problem is to move your global declarations inside each function that uses those variables. So:

    def playerUpdateMovement():
        global lead_x
        global lead_y
        global lead_x_change
        global lead_y_change
    
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            lead_x_change = -1
    

    This tells Python that your use of lead_x_change within the playerUpdateMovement function is actually a reference to a global variable, and not a use of a local variable (of the same name), which is the default treatment.

提交回复
热议问题