使用pygame,我做了一个主菜单上的几个按钮。我可以检测到按钮被按下并做了一些事情。模块没有设置主文件变量内容
但是,控制按钮按下时发生的代码在另一个文件中(使用getattr),这似乎是导致一些问题。
我正在使用变量menu_open
来控制与菜单有关的事情何时应该完成。当游戏启动并且在一次性开发者警告显示(正常工作)之后,它被设置为真。一切都按预期工作,直到我点击我的new game
按钮。这应该只是创建一个空白屏幕。什么都没发生。
我发现menu_open
仍然是True
。看来正在发生的是,控制new game
按钮的代码是在另一个文件中,由于我无法理解的原因似乎与我的主文件是menu_open
不同的版本。 (这不是我的主文件menu_open
设置为False
虽然它的测试打印语句打印False
)控制时,按下该按钮会发生什么
代码:
def new_game():
print('starting a new game')
import main
main.menu_open=False
print(2,main.menu_open)
我的程序的启动:
import pygame,commands #line 1
done = False
menu_open= False #deceleration of menu_open at start of program
game_playing = False
更新菜单的代码(当menu_open
为False时应创建一个白色屏幕):
代码:打印报表
def run_logic(self): #worth noting this is called right before display_frame()
global mouse_pos,mouse_press
mouse_pos = pygame.mouse.get_pos()
mouse_press = pygame.mouse.get_pressed()
for button in button_list:
button.check() #runs the following:
def check(self):
if self.hovered:
if mouse_press[0] == True:
try:
command_to_call = getattr(commands,self.command)
command_to_call()
except:
print('[DEV]: invalid command')
结果:
1 True # button not pressed
1 True # True here is my main files 'menu_open'
1 True
1 True
1 True
1 True
starting a new game #button pressed
2 False #false is the other files 'menu open'
1 True # True here is my main files 'menu_open'
starting a new game
2 False
1 True
starting a new game
2 False
1 True
starting a new game
2 False
1 True #button released, menu still normal
1 True
1 True
1 True
我不是很有经验的多档节目,所以任何帮助表示赞赏。 也可能值得注意我的IDE(pyscripter)在pygame中出现了很多错误。 到目前为止,按钮控件工作正常。我已经使用它做了一个退出按钮。
如果您需要我的程序中的任何更多代码,请随时询问:) 如果我的代码很好,并且这只是python/pyscripter/pygame的错误,请说明。
所以我需要在多个文件中的任何变量都应该在自己的文件中?什么是错误的使用__main__?它是否需要主程序运行才能正常工作? – Thedudxo 2014-11-07 20:04:00
正确,并且正确。如果您将模块用于除关联程序之外的任何其他模块,则行为可能未定义。 – 2014-11-07 20:06:25