Jump to content

Python help with imports

I've started developing a game just for fun, and am working on key-handler. More on that in a minute... All problem areas highlighted in bold and underlined

MAIN.PYfrom utility import *  # Also imports pygame as pgimport key_handlerpg.init()screenX = 1280screenY = 720bgColor = hue('#333333')gameName = 'Game'icon = 'assets/misc/windowIcon.png'gameDisplay = pg.display.set_mode((screenX, screenY))bg = pg.Surface(gameDisplay.get_size())bg.fill(bgColor)bg = bg.convert()gameDisplay.blit(bg, (0, 0))clock = pg.time.Clock()set_icon(icon)key_handler.start_key_handler() mainloop = TrueFPS = 60playtime = 10.0while mainloop:    milliseconds = clock.tick(FPS)    # Sets the window title, adds FPS counter    frameTitle = gameName + " FPS: "    frameTitleFPS = repr(clock.get_fps())    pg.display.set_caption(frameTitle + frameTitleFPS[0:2])    # Stops the game when window is closed or escape is pressed    for event in pg.event.get():        if event.type == pg.QUIT:            mainloop = False    pg.display.update()pg.quit()
KEY_HANDLER.PYimport pygame as pgimport maindef start_key_handler():    for event in pg.event.get():        if event.type == pg.KEYDOWN:            # Esc = quit game            if event.key == pg.K_ESCAPE:                mainloop = False            # Key A = print            elif event.key == pg.K_a:                print('Key down!')    return None

Now that you've seen the code: here's my problem. I've messed with it a bit and either one of these happens: A. It errors with AttributeError: 'module' object has no attribute 'start_key_handler' or B.

It launches successfully then hitting the keys escape or a do nothing.
 

 

I've done some googling and it appears I have "mutual top-level imports" ... "almost always a bad idea"

 

Suggestions on both how to resolve this issue and make my code less crappy are appreciated. Thanks.

Link to comment
https://linustechtips.com/topic/411157-python-help-with-imports/
Share on other sites

Link to post
Share on other sites

they both import each other right at the start. that doesn't work. try to rewrite it so the dependencies flow in one direction. more specifically, if you follow the lines that are going to be executed it goes:

 

main -> import utilites

main -> import keyhandler

keyhandler -> import pygame

keyhandler -> import main

main -> rest of main

keyhandler -> rest of keyhandler

 

so you see when main is being executed none of the code in keyhandler has been evaluated yet, so it should not have defined a function start_key_handler yet. I'm not sure why it gives intermittent errors but it doesn't really matter as this is your problem so you know what you need to fix.

 

A solution might be to pass references to any variables you need for start_key_handler as parameters and remove the import main from keyhandler.py

 

Also, your keyhandler doesn't work from what I can see. your program starts, the for loop will enumerate over any key events that it has until the keyevent buffer is empty, then the for loop ends. so it won't be running by the time you actually hit a key, try putting the keyhandler in the main loop so that it is called repeatedly.

Link to comment
https://linustechtips.com/topic/411157-python-help-with-imports/#findComment-5534901
Share on other sites

Link to post
Share on other sites

they both import each other right at the start. that doesn't work. try to rewrite it so the dependencies flow in one direction. more specifically, if you follow the lines that are going to be executed it goes:

 

main -> import utilites

main -> import keyhandler

keyhandler -> import pygame

keyhandler -> import main

main -> rest of main

keyhandler -> rest of keyhandler

 

so you see when main is being executed none of the code in keyhandler has been evaluated yet, so it should not have defined a function start_key_handler yet. I'm not sure why it gives intermittent errors but it doesn't really matter as this is your problem so you know what you need to fix.

 

A solution might be to pass references to any variables you need for start_key_handler as parameters and remove the import main from keyhandler.py

 

Also, your keyhandler doesn't work from what I can see. your program starts, the for loop will enumerate over any key events that it has until the keyevent buffer is empty, then the for loop ends. so it won't be running by the time you actually hit a key, try putting the keyhandler in the main loop so that it is called repeatedly.

I've changed things up a bit

from utility import *  # Also imports pygame as pgimport key_handlerpg.init()screenX = 1280screenY = 720bgColor = hue('#333333')gameName = 'Game'icon = 'assets/misc/windowIcon.png'mainloop = TrueFPS = 60gameDisplay = pg.display.set_mode((screenX, screenY))bg = pg.Surface(gameDisplay.get_size())bg.fill(bgColor)bg = bg.convert()gameDisplay.blit(bg, (0, 0))clock = pg.time.Clock()set_icon(icon)while mainloop:    key_handler.start_key_handler()    milliseconds = clock.tick(FPS)    # Sets the window title, adds FPS counter    frameTitle = gameName + " FPS: "    frameTitleFPS = repr(clock.get_fps())    pg.display.set_caption(frameTitle + frameTitleFPS[0:2])    # Stops the game when window is closed or escape is pressed    for event in pg.event.get():        if event.type == pg.QUIT:            mainloop = False    pg.display.update()pg.quit()
import pygame as pgdef start_key_handler():    import main    while main.mainloop:        for event in pg.event.get():            if event.type == pg.KEYDOWN:                # Esc = quit game                if event.key == pg.K_ESCAPE:                    main.mainloop = False                # Key A = print                elif event.key == pg.K_a:                    print('Key down!')        return None

  File "G:/Files/Github/Python/Game/main.py", line 31, in <module>

    for event in pg.event.get():

pygame.error: video system not initialized

 

Weird, it doesn't work (not detecting keys) but it drops the above error when I close it.

Link to comment
https://linustechtips.com/topic/411157-python-help-with-imports/#findComment-5535013
Share on other sites

Link to post
Share on other sites

where are you calling pygame.init()? if it says its not initalized better check that you called the init(ialize) function ;)

 

Also, moving the import statement is like putting a band-aid on a broken arm. It might stop any bleeding but what you really need to do is set the arm before it heals in the wrong place. a huge part of coding is knowing what to get rid of, if you hold onto a hack or janky fix for too long it will be impossible to get rid of it. Best practices are around because lots of people have made the same mistakes and found the same solution. inheritance is a design pattern for a good reason.

Link to comment
https://linustechtips.com/topic/411157-python-help-with-imports/#findComment-5535205
Share on other sites

Link to post
Share on other sites

where are you calling pygame.init()? if it says its not initalized better check that you called the init(ialize) function ;)

Just as you posted that I got it. I've import pygame as pg in utility.py so pg.init() at the top of main.py is really pygame.init

 

So I moved the start_key_handler call to right above the for loop in main.py, added quit() under both pg.quit() and now it all works great!

 

Code for anyone needing it in the future:

from utility import *  # Also imports pygame as pgimport key_handlerpg.init()screenX = 1280screenY = 720bgColor = hue('#333333')gameName = 'Game'icon = 'assets/misc/windowIcon.png'frameTitle = gameName + " FPS: "mainloop = TrueFPS = 60gameDisplay = pg.display.set_mode((screenX, screenY))bg = pg.Surface(gameDisplay.get_size())bg.fill(bgColor)bg = bg.convert()gameDisplay.blit(bg, (0, 0))clock = pg.time.Clock()set_icon(icon)while mainloop:    milliseconds = clock.tick(FPS)    # Sets the window title, adds FPS counter    frameTitleFPS = repr(clock.get_fps())    pg.display.set_caption(frameTitle + frameTitleFPS[0:2])    key_handler.start_key_handler()    # Stops the game when window is closed or escape is pressed    for event in pg.event.get():        if event.type == pg.QUIT:            mainloop = False    pg.display.update()pg.quit()quit()
import pygame as pgdef start_key_handler():    import main    while main.mainloop:        for event in pg.event.get():            if event.type == pg.KEYDOWN:                # Esc = quit game                if event.key == pg.K_ESCAPE:                    main.mainloop = False                    pg.quit()                    quit()                # Key A = print                elif event.key == pg.K_a:                    print('Key down!')        return None

Link to comment
https://linustechtips.com/topic/411157-python-help-with-imports/#findComment-5535225
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×