2017-03-15 27 views
0

改變,我想在其他文件中使用全局變量和更改此變量的值: settings.py:Python的全局變量不會在我的功能

mort = False 

platforms1.py :

class Platform(pygame.sprite.Sprite): 
    #.......... 
class Spike(Platform): 
player = None 
def invisible(self): 
    if not pygame.sprite.collide_rect(self, self.player): 
     self.image.set_alpha(0) 
def update(self): 
    global mort 
    if pygame.sprite.collide_rect(self, self.player): 
     self.image.set_alpha(256) 
     mort = True 
     print(mort) 
>>>True 

,我可以在我的級別一樣,添加尖峯: levels1.py:

import pygame 
from settings import * 
from platforms1 import * 

#add a spike (image, width, height) 
block = Spike(spikes,1,1) 
block.rect.x = 1360 #pos en x 
block.rect.y = 696 #pos en y 
block.player = self.player 
Spike.invisible(block) 
self.background_list.add(block) 

並加入我的主循環: main.py:

while mort == True: 
    #................. 
active_sprite_list.update() 
current_level.update() 
print(mort) 
>>>False 

就像你看到的「病危」留在main.py假,obvsly不同時莫特==真執行:迴路platforms1時。 py「mort」是真的。

Idk如果你需要更多的代碼,我想我在這裏得到最重要的,但我可以粘貼你更多,如果你想。

感謝您的建議和抱歉,我的英語不好,我是法國人!

回答

0

當你

from platforms1 import * 

綁定當前模塊中platforms1新變量的對象。現在你有2個對這些對象的引用。當platforms1中的代碼重新綁定其本地參考(例如,mort = True)時,其他模塊中的參考不受影響。如果你想在多個模塊中使用同一個對象,不要做import *。相反

import platforms1 
while platforms1.mort: 
    ...