This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 12 months ago.
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()
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")
Related
I am having a problem with displaying an image in pygame. The image is in the same directory/folder but it still has an error. This error popped out of the blue and I'm not sure how to fix it... My code below
import pygame, sys
from pygame.constants import QUIT
pygame.init()
GameSprite = pygame.image.load('GameSprite.png')
GameSprite = pygame.transform.scale(GameSprite,(200, 200))
def main():
x = 100
y = 100
velocity = 0
velocity = pygame.Vector2()
velocity.xy = 3, 0
acceleration = 0.1
DISPLAY = pygame.display.set_mode((570, 570))
pygame.display.set_caption("Flappy Bird Related Game")
WHITE = (255,255,255)
BLUE = (0, 0, 255)
while True:
DISPLAY.fill(WHITE)
#pygame.draw.rect(DISPLAY,BLUE,(x,y,50,50))
DISPLAY.blit(GameSprite,(x,y))
y += velocity.y
x += velocity.x
velocity.y += acceleration
if x + 50 > DISPLAY.get_width():
velocity.x = -3
if x < 0:
velocity.x = 3
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
velocity.y = -4.2
pygame.display.update()
pygame.time.delay(10)
main()
It is not sufficient to copy the image files in the project directory. You also need to set the working directory.
The image file path has to be relative to the current working directory. The working directory can be different to the directory of the python script.
The name and path of the script file can be retrieved with __file__. The current working directory can be set with os.chdir(path).
Add the following lines of code at the beginning of your script to set the working directory to the same as the script's directory:
import os
import pygame, sys
from pygame.constants import QUIT
os.chdir(os.path.dirname(os.path.abspath(__file__)))
pygame.init()
GameSprite = pygame.image.load('GameSprite.png')
To make things simpler instead of writing "GameSprite.png" try adding the path to the file.
Example:
if the GameSprite.png is in the location C://Users/person/Desktop
Replace GameSprite = pygame.image.load('GameSprite.png')
with
GameSprite = pygame.image.load('C://Users/person/Desktop/GameSprite.png')
Just put the file location in pygame.image.load()
Im trying to run my test game-script written in pygame on my raspberry pi zero w on a 3.5" LCD screen (which is working).
But I keep getting this error. And I haven't after ALOT of hours found a fix for this, does anyone know how to fix this?
Im running the latest version of Raspberry Pi OS lite
Script:
import pygame
pygame.init()
win = pygame.display.set_mode()
x = 50
y = 50
width = 40
height = 60
velocity = 10
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= velocity
if keys[pygame.K_RIGHT]:
x += velocity
if keys[pygame.K_UP]:
y -= velocity
if keys[pygame.K_DOWN]:
y += velocity
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()```
Error Message:
pygame 2.1.2 (SDL 2.0.14, Python 3.9.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
The path /dev/dri/ cannot be opened or is not available
The path /dev/dri/ cannot be opened or is not available
The path /dev/dri/ cannot be opened or is not available
The path /dev/dri/ cannot be opened or is not available
Traceback (most recent call last):
File "/srv/Game/main.py", line 4, in <module>
win = pygame.display.set_mode()
pygame.error: No available video device
I think you need to include your params in win = pygame.display.set_mode()
like this:
win = pygame.display.set_mode(size=(x,y), width=width, etc...)
You will need to declare those variables before win = pygame.display.set_mode()
Are you executing from terminal or IDE?
Do you have one or more displays?
I use Python 3.7.4 and Pygame 1.9.6. I'm trying to create just a test game so I can save data like a score per say using pickle this is my first time. But I'll get down that path once I'm done with the test game.
I'm getting an error two separate occasions in ball(ballX[i], ballY[i], i) and in screen.blit(ballImg, (x, y), i). It's a TypeError: arugument 1 must be pygame.Surface, not list.
Full Trace Back:
Traceback (most recent call last):
File "C:Test/main.py", line 128, in <module>
ball(ballX[i], ballY[i], i)
File "C:/Test/main.py", line 66, in ball
screen.blit(ballImg, (x, y), i)
The code:
import pygame
import random
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg, (x, y), i)
running = True
while running:
'''The key stuff and what not'''
'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
pygame.display.update()
I'm not understanding what I'm doing wrong in my function/list or evening bliting the image. I feel like I'm doing everything right filling out the parameters, etc. I appreciate the advice. So thank you.
A few things:
As #Ewong mentioned, you are passing ballImg to blit instead of ballImg[i]
You're not processing OS messages, so the program will freeze
Try this code:
import pygame
import random
scr_width = 800
scr_height = 600
screen = pygame.display.set_mode((scr_width, scr_height))
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
#'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg[i], (x, y))
running = True
while running:
#'''The key stuff and what not'''
#'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
for event in pygame.event.get(): # process OS messages
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.display.update()
I want to know why I get an error in this code.
I am trying to upload a character in JPG format and it gives me an error.
I am using IDLE and it is python 3.7.3
import pygame
pygame.init() #Initialize the game
win = pygame.display.set_mode((1000,700)) # Sets the window size
pygame.display.set_caption("First Game") # Title of window in the string
*walkRight = [pygame.image.load('Person.JPG')]* # load image
x = 100
y = 690
width = 10
height = 10
vel = 5
isJump = False
jumpCount = 5 # timer for mid-air
left = False
right = False
run = True
while run:
pygame.time.delay(100) # waits for 100 miliseconds = 0.1 second
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel: # left
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - width - vel: # right
x += vel
if not(isJump): # not jumping
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -5:
checker = 1 # positive jumpCount
if jumpCount < 0:
checker = -1 # negative jumpcount
y -= (jumpCount ** 2) * 0.5 * checker
jumpCount -= 1
else:
isJump = False # allows the player to jump again
jumpCount = 5 # how long it is in mid air
win.fill((255,255,255)) # Fills the screen black
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update() # updates the screen each time
pygame.quit()
Why does the place marked * give me an error?
As you haven't mentioned what operating system you are using, I will try to help with both Windows and Linux. It doesn't matter which OS you use if you have mentioned the correct path of the file in your code.
There are multiple ways to get absolute file paths in different operating systems:
For example:
On Windows, hold the Shift key and right-click on the image and then click on "Copy as path".
On Linux, just right-click on the image and click "copy".
Now get back to your code and paste the complete image path.
Just to give you an example, the full path should look like "C:\Users\userName\Downloads\image.png" on windows and "/home/username/Desktop/image.png".
To avoid username in Linux, you can replace "/home/username" with "~/", so your full path would look like "~/Desktop/image.png".
Note: It is never recommended to hard code paths if you are planning to share the code or run it on production/a remote server. However, if you are just learning and experimenting, this should do the trick.
I'm working on a time based movement program in pygame. And I keep receiving this error.
Traceback (most recent call last):
File "C:\Documents and Settings\Mohammad Raza\Desktop\Python
Scripts\TimeBasedMovement.py", line 11, in <module>
background = pygame.image.load(background_image_filename).convert()
error: Couldn't open Wolf.jpg
I thought perhaps I deleted the image, but I checked and the image is not deleted. It is saved as the name "Wolf" and stored as a JPEG image.
Here is the entire code below.
background_image_filename = 'Wolf.jpg'
sprite_image_filename = 'Cartoon.jpg'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename)
clock = pygame.time.Clock()
x = 0.
speed = 250
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background,(0,0))
screen.blit(sprite,(x,100))
time_passed = clock.tick()
time_passed_seconds = time_passed_seconds / 1000.0
distance_moved = time_passed_seconds * speed
x += distance_moved
if x > 640.:
x -= 640.
pygame.display.update()
Also make sure the image is in the current working directory.
fullname = os.path.join('data', name)
image = pygame.image.load(fullname)
Also it should be
time_passed_seconds = time_passed / 1000.