2016-02-14 42 views
0

我的任务是制作一个游戏,应该有多个模块以避免在一个脚本中混乱。我遇到了从其中一个模块导入变量的问题。到目前为止,我有一个设置和一个主要设置。这些设置是相当简单的,去:python - 使用从模块导入的类的问题

class Settings(): 
def __init__(self): 
    self.screen_width = 1920 
    self.screen_height = 1080 
    self.bg_color = (230, 230, 230) 

很简单,但是当我尝试引用这些变量,它说类“未解决属性引用‘SCREEN_WIDTH’‘设置’

主,就如同:

import sys, pygame 
from game_settings import Settings 

def run_game(): 
    #Initialize the game and create the window 
    pygame.init() 
    screen = pygame.display.set_mode((Settings.screen_width,Settings.screen_height), pygame.FULLSCREEN) 
    pygame.display.set_caption("Alien Invasion") 

while True: 

    #Listening for events 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 
    screen.fill(Settings.bg_color) 
    pygame.display.flip() 

run_game() 

我想,也许这将是一个PyCharm问题,但发现它在空闲所以这将是导入变量的正确方法是一回事吗?

感谢您花时间阅读本文!

+0

但它运行的权利? – danidee

+0

我绝对不是专家,但不是'bg_color','screen_width'和'scree_height'部分的实例而不是类本身?换句话说,我不认为你可以访问Settings.bg_color,我认为你需要创建一个Settings对象,像's = Settings()',然后你可以执行'.bg_color'。 –

+0

@danidee没有它不起作用 –

回答

2

您需要创建一个Settings类的实例,因为at您在其__init__方法中设置的贡品是实例属性。

尝试这样:

def run_game(): 
    my_settings = Settings() # create Settings instance 
    pygame.init() 
    screen = pygame.display.set_mode((my_settings.screen_width, # lookup attributes on it 
             my_settings.screen_height), 
            pygame.FULLSCREEN) 
    # ... 
+0

谢谢!这工作完美。 –

0

您需要创建设置对象的实例:s = Settings()

用法:s.bg_color

OR

改变你的设置类,像这样和性能都可以访问静态:

class Settings(): 
    screen_width = 1920 
    screen_height = 1080 
    bg_color = (230, 230, 230) 
0

两个文件必须在同一文件夹中,你必须创建Settings类的一个实例。然后你可以访问你的实例的属性。

main.py:

from game_settings import Settings 
s = Settings() 
print(s.bg_color) 

game_settings.py:

class Settings(): 
    def __init__(self): 
     self.screen_width = 1920 
     self.screen_height = 1080 
     self.bg_color = (230, 230, 230) 

当您运行main.py,输出将是:

(230, 230, 230)