0

Hey everybody, I am making a pixel runner style game, and when I try to load a random image using a method I always use, it comes up with the error:

Traceback (most recent call last): File "c:\Users\name\Documents\Python\PixelRunnerMain\PixelRunner.py", line 22, in png1 = pygame.image.load("1.png") FileNotFoundError: No file '1.png' found in working directory 'C:\Users\chizl\Documents'.

The file is in the exact same directory as the images! Please help. (also, I want HELP, dont just come here to correct my question.)

import pygame, random

#initialise pygame
pygame.init()

#window values
win = pygame.display.set_mode((416,256))
pygame.display.set_caption("Pixel Runner")
run = True

#player values
x = 192
y = 144
width = 16
height = 16
vel = 12

#enemy values
e_x = 0
e_y = 0
e_vel = 12
png1 = pygame.image.load("1.png")
png2 = pygame.image.load("2.png")
e_types = [png1, png2]
e_type = random.choice(e_types)

#while loop (all main code goes here)
while run:
    pygame.time.delay(80)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    #key presses
    keys = pygame.key.get_pressed()
    
    if keys[pygame.K_LEFT] and x > vel-16:
        x -= vel

    if keys[pygame.K_RIGHT] and x < 390:
        x += vel
    
    #gravity
    e_y = e_y + e_vel
    if e_y > 256:
        e_y = 0

    #player gravity or something
    if win.get_at((x,y)) == (0,0,0) or win.get_at((x+16,y)) == (0,0,0):
        y += 12
        e_type = random.choice(e_types)

    #more window stuff
    win.fill((255,255,255))
    pygame.draw.rect(win, (255,0,0), (x, y, width, height))
    win.blit(win, e_type, (0,e_y))
    pygame.display.update()
   
pygame.quit()
  • What matters is NOT the directory that contains the code. What matters is the current directory when you run the app. In your case, the current directory is `C:\Users\chiz\Documents`. You can find the script's name in the `__file__` variable, and use that to build the path to your image. – Tim Roberts Mar 01 '22 at 07:37

1 Answers1

0

how about get a current directory?

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

and check your directory if it is correct

# Print the current working directory
print("Current working directory: {0}".format(cwd))

if everything is correct, replace the code where you call the image with :

png1 = pygame.image.load(cwd+"1.png")
YMG
  • 498
  • 6
  • 15
  • Well, if the current directory is correct, then there's no need to prepend it to the filename. The point here is that he is not IN the proper directory. – Tim Roberts Mar 01 '22 at 07:36