1

I am a newbie in Python following a tutorial online for making an AI learn to play Flappy bird. My problem is that I can't seem to load the images for the game that I have saved in a folder using this syntax:

BIRD_IMGS = 
[pygame.transform.scale2x(pygame.image.load(os.path.join("imgs","bird1.png"))),
 pygame.transform.scale2x(pygame.image.load(os.path.join("imgs","bird2.png"))),
 pygame.transform.scale2x(pygame.image.load(os.path.join("imgs","bird3.png")))]

The error I get is the following:

pygame.error: Couldn't open imgs\bird1.png

My paths are:

C:\Users\Admin\Documents\Web Development\Python\Flappy_Bird_AI\master.py
C:\Users\Admin\Documents\Web Development\Python\Flappy_Bird_AI\imgs\bird1.png

for the code and image, respectively.

Anyone know why I'm getting this error?

num3ri
  • 822
  • 16
  • 20
Alex Fulop
  • 23
  • 4
  • Does this answer your question? [pygame.error: Couldn't open image](https://stackoverflow.com/questions/32684198/pygame-error-couldnt-open-image) – Amrsaeed Nov 14 '19 at 17:04
  • Hardly.. All I got from that was that I need to switch from VScode, also I don't want to use absolute paths. – Alex Fulop Nov 14 '19 at 17:22

1 Answers1

3

You are probably running your script from a different working directory than the one that has the image.

You can do the following to get the absolute path dynamically within your script

DIR = os.path.dirname(os.path.realpath(__file__))
IMGS_DIR = os.path.join(DIR, "imgs")

BIRD_IMGS = [pygame.transform.scale2x(pygame.image.load(os.path.join(IMGS_DIR,"bird1.png"))),
 pygame.transform.scale2x(pygame.image.load(os.path.join(IMGS_DIR,"bird2.png"))),
 pygame.transform.scale2x(pygame.image.load(os.path.join(IMGS_DIR,"bird3.png")))]
Amrsaeed
  • 316
  • 2
  • 11