Error Global Variable not defined when importing class

前端 未结 2 1601
温柔的废话
温柔的废话 2021-01-28 20:45

I am trying to implement a movement system where the player move\'s towards the click position. But I have been running into some problems with the arguments of the movement met

2条回答
  •  庸人自扰
    2021-01-28 21:04

    Your problem is that "global" variables in python are not actually global, but rather local to the module in which they were defined in. Thus, you cannot reference globals decalred in the main.py file in the classes.py file.

    There are three possible solutions:

    1. (not recomended) Move the declarations of screen and background to the classes.py file, which would put them seemingly out of place.

    2. (also not recommended) Add a from main import screen, background to the classes.py file, which creates circular import problems, forcing the main.py module to do its from classes import * after defining screen and background

    3. Add a third display.py or screen.py file, where the screen and background variabled are defined and import it from main.py and classes.py

    The mouse_pos variable is totally unnecessary and misused:

    1. You could just use pygame.mouse.get_pos() directly in the classes.py file, but
    2. Using pygame.mouse.get_pos() itself is extranious because pygame.MOUSEBUTTONDOWN events have a pos attribute pointing to the position of the mouse when the event was fired.

提交回复
热议问题