When writing a game that consists of multiple MicroPython files, import doesn't work as I would expect.
If I have this directory tree:
Games/
MyGame/
MyGame.py
mylib.py
And this is MyGame.py, I would expect this to Just Work™️:
import mylib
Instead, this gives an error that mylib can't be found. This is because the path doesn't get set to include the game's directory. To fix this, each individual game has to do something like this:
# To find files in our directory before anywhere else:
import sys
sys.path.insert(0, '/Games/MyGame')
# Or, to find files in our directory if we can't find it anywhere else:
import sys
sys.path.append('/Games/MyGame')
# and only then...:
import mylib
So far I have not been able to find a more elegant way to load additional files.
Suggestion for a fix
I haven't actually tried this, but I suggest including the game's path before running it from the Thumby "firmware". See comments in code below:
def launchGame():
if(selpos>=0):
gamePath=files[selpos] # <-- Save game name instead of full path
saveConfigSetting("lastgame", gamePath)
import machine
#Address of watchdog timer scratch register
WATCHDOG_BASE=0x40058000
SCRATCH0_ADDR=WATCHDOG_BASE+0x0C
machine.mem32[SCRATCH0_ADDR]=1
machine.soft_reset()
if(mem32[SCRATCH0_ADDR]==1):
mem32[SCRATCH0_ADDR]=0
import sys
gamePath=''
conf = open("thumby.cfg", "r").read().split(',')
for k in range(len(conf)):
if(conf[k] == "lastgame"):
gamePath = conf[k+1]
freq(125000000)
try:
sys.path.insert(0, "/Games/"+gamePath). # <-- Insert game path as the first entry in the path array
__import__("/Games/"+gamePath+"/"+gamePath+".py") # <-- Construct the full game path here
except ImportError:
print("Thumby error: Couldn't load "+gamePath)
Issue
When writing a game that consists of multiple MicroPython files,
import
doesn't work as I would expect.If I have this directory tree:
And this is
MyGame.py
, I would expect this to Just Work™️:Instead, this gives an error that
mylib
can't be found. This is because the path doesn't get set to include the game's directory. To fix this, each individual game has to do something like this:So far I have not been able to find a more elegant way to load additional files.
Suggestion for a fix
I haven't actually tried this, but I suggest including the game's path before running it from the Thumby "firmware". See comments in code below: