When using python and pygame in my vscode IDE, I try to reference an image from a folder in the same directory and the program fails to run because is no file or directory with that name is not found.
File "c:\Users\Kris\Desktop\Github\100daysOfCode\Day30\alien_invasion\ship.py", line 12, in init self.image = pg.image.load('Day30\alien_invasion\images\ship.bmp') FileNotFoundError: No such file or directory.
Picture of the directory in vscode:
I have renamed the folder so that there is no space between Day and 30 and I even tried the relative path but I get a Unicode error instead.
File "c:\Users\Kris\Desktop\Github\100daysOfCode\Day30\alien_invasion\ship.py", line 12 self.image = pg.image.load('C:\Users\Kris\Desktop\Github\100daysOfCode\Day30\alien_invasion\images\ship.bmp') ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape PS C:\Users\Kris\Desktop\Github\100daysOfCode>
The absolute and relative path only works for me when I have the images folder in the directory above the one it is in.
images folder moved to upper directory:
alien_invasion.py
import sys
import pygame as pg
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Overall class to handle game assets and behavior"""
def __init__(self):
"""Initialize the game and create resources."""
pg.init()
self.settings = Settings()
self.screen = pg.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pg.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""Start the main loop for the game"""
while True:
#Watch for keyboard and mouse events
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
#Redraw the screen during each pass through
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
#Make the most recently drawn screen visible.
pg.display.flip()
if __name__ == '__main__':
#Mkae a game instace, and run the game
ai = AlienInvasion()
ai.run_game()
settings.py
class Settings:
"""A class to store all the settings for Alien Invasion"""
def __init__(self):
""""Initialize the game's settings."""
#Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230,230,230)
ship.py
import pygame as pg
class Ship:
"""A class to manage the ship"""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position"""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
#Load the ship image and get its rect.
self.image = pg.image.load('Day30\alien_invasion\images\ship.bmp')
self.rect = self.image.get_rect()
#Start each new ship at the bottom center of the screen
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""Draw the ship at its current location"""
self.screen.blit(self.image, self.rect)
Not sure why this is an issue. Are there any extensions for this or am I just organizing the folders wrong?