1

Whenever I run this code the message pygame.error: Couldn't open ship.bmp appears. I am keeping the file ship.bmp in the same place as my code. I would appreciate any help.

import sys
import pygame

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width,screen_height))
bg_color = (0, 13, 114)
pygame.display.set_caption('space invaders')

shipImg = pygame.image.load("ship.bmp")

def ship(x,y):
    screen.blit(shipImg, (x,y))

x = (screen_width * 0.45)
y = (screen_height * 0.8)

crashed = False
while not crashed:

    #keyboard events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
    screen.fill(bg_color)
    ship(x,y)
    pygame.display.flip()
pygame.quit()
quit()
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
Bill
  • 59
  • 2
  • 4
  • 1
    Have you tried using an absolute path? – TigerhawkT3 Apr 24 '16 at 23:39
  • Were you working along to Eric Matthes', 'Python Crash Course' ? I surmise you were running the code from an editor like Notepad++ ? @Finch's comment below will help you discover, the working directory, which would probably be the IDE's binary path. Running it from the command line as #kirill .z suggested would fix your problem. – Nikhil Silveira Aug 20 '19 at 12:23

3 Answers3

1

Do you run this code in Unix OS? If so you need change your working directory to run this file.py! in terminal type with cd command to your directory where files saved! then run python with te same path and will be work fine!

storenth
  • 967
  • 11
  • 18
1

Use print os.getwd() as the first line of your script/py program to see which folder you are actually starting from. If your image happens to be in a sub-directory of the main folder (which happens not to appear on the output of os.getwd()), make sure to include it in your image path such that instead of writing only 'ship.bmp' when loading the image, you write 'subdirectory/ship.bmp' as your path.

Ochibobo
  • 11
  • 2
0

I tried your code and it worked fine. See that the image is in the ROOT DIRECTORY. That is the same folder where you save this script/py file. The other reason could be that there are hidden characters in your file name. This happened to me several times. try rename function, delete the entire name including the file extension and rename the file with the same ext, brand new.

emorphus
  • 550
  • 9
  • 20