Reputation: 4457
I am working on my game, and have made a level class, but my parselevel() method will not let me parse the level, because of "Block" not being a global variable (Block is my block class).
How would I do this? Could I just pass Block and Player to the parseLevel method?
Traceback (most recent call last):
File "C:\Users\Benjamin\Documents\GitHub\ShipGame\level.py", line 3, in <module>
from entity import *
File "C:\Users\Benjamin\Documents\GitHub\ShipGame\entity.py", line 5, in <module>
from blocks import *
File "C:\Users\Benjamin\Documents\GitHub\ShipGame\blocks.py", line 4, in <module>
from level import *
File "C:\Users\Benjamin\Documents\GitHub\ShipGame\level.py", line 4, in <module>
from blocks import Block
ImportError: cannot import name Block
My code:
import pygame
from entity import *
from blocks import *
# Holds the level layout in a list of strings.
levelMap = [
"WWWWWWWWWWWWWWWWWWWW",
"WX W",
"W W",
"W P W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W P W",
"W W",
"WWWWWWWWWWWWWWWWWWWW",
]
class Level(object):
def __init__(self, levelMap):
self.levelMap = levelMap
def parseLevel(self):
x = 144
y = 0
for row in self.levelMap:
for col in row:
if col == "W":
Block((x, y))
if col =="P":
Port((x, y))
if col == "X":
player = Player((x, y), 1, "Player1", 1, 0)
x += 32
y += 32
x = 144
level = Level(levelMap)
level.parseLevel()
Upvotes: 2
Views: 131
Reputation: 65894
The traceback shows that you have a circular import problem. When you have a statement from foo import *
, Python has to finish loading foo
right away (so that it can work out all the imported names). But this means that:
level.py
executes from entity import *
, entity
must be loaded before level
;entity.py
executes from blocks import *
, blocks
must be loaded before entity
;blocks.py
executes from level import *
, level
must be loaded before blocks
.Obviously this can't work!
What you really ought to do is reorganize your code so that each module doesn't need to know about all the others. (For example, why do blocks
need to know about level
?)
But if you are having trouble with that, you can get things working by breaking the circle, for example by writing import level
instead of from level import *
. Obviously you'll then have to write level.foo
instead of foo
, but that should be easy.
(This works because import foo
doesn't need foo
to have finished loading yet.)
See this entry in the Python FAQ for more about circular imports.
Upvotes: 3