1

When i try to load a image with pygame it is like the .load part in pygame.image.load does not exist. I have Initialized it so i dont know why it wont let me use the images.

Code:

# Imports
import os
import time
import random
import pygame
from pygame.locals import *

# Init
pygame.init()

# Loading images
RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png"))
GREEN_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_green_small.png"))
BLUE_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_blue_small.png"))

# Player's Ship
YELLOW_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_yellow.png"))

# Lasers
RED_LASER = pygame.image.load(os.path.join("assets", "pixel_laser_red.png"))
RED_GREEN = pygame.image.load(os.path.join("assets", "pixel_laser_green.png"))
RED_BLUE = pygame.image.load(os.path.join("assets", "pixel_laser_blue.png"))
RED_YELLOW = pygame.image.load(os.path.join("assets", "pixel_laser_yellow.png"))

# Background
BG = pygame.image.load(os.path.join("assets", "background-black.png"))

Error: File "c:/Users/(user)/Desktop/Python Projects/SpaceInvader/main.py", line 12, in RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png")) pygame.error: Couldn't open assets\pixel_ship_red_small.png

It isnt just the red ship when i removed that line its all of them.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

2 Answers2

0

You didn't really initialize pygame.
pygame.init is a function, you should call it with:

pygame.init()
Then it should work.

If it still doesn't work after that, make sure that the paths you supplied to the assets are correct and that Python manage to find them (I.e. You run your game where those paths are relative to you. otherwise you should probably use the utility functions like os.realpath on __file__ to find the locations of those files relative to your script).

Or Y
  • 2,088
  • 3
  • 16
  • Yes the paths i supplied are right, its not the paths that have a problem, i think its pygame since when i hold ctrl i cant press the load but i can press pygame.image – KingRealzYT Aug 23 '20 at 05:55
  • From what directory do you run your game? And how your project's directory tree looks like? – Or Y Aug 23 '20 at 06:10
  • 1
    A friend of mine helped me solve it. It was a Visual Studio Code bug so i had to switch IDE's. – KingRealzYT Aug 23 '20 at 06:13
0

The working directory and the directory of the Python file are not necessarily identical.

Either change the working director:

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)

Or create absolute file paths:

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

RED_SPACE_SHIP = pygame.image.load(
    os.path.join(sourceFileDir , "assets", "pixel_ship_red_small.png"))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174