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()
Related
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")
Well, this is my first program I write with Pygame. Before opening this thread I read two other thread without any positive result. I almost copied a program to resolve this problem without success. Here is my code:
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
car = pygame.image.load('car.png')
def car(x,y):
gameDisplay.blit(car,(x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(blue)
car(x,y)
pygame.display.update()
clock.tick(24)
pygame.quit()
quit()
I thought there could be a problem with directories, but I don't think so. I create a folder in the desktop named "Nuova Cartella" (New Folder in italian, and I wrote it in italic ahah) and I put there two files, the first one is the program that I've just post here and the second one is "car.png", that's the image I'd like to load in pygame, of course.
Sorry for my english, I did my best.
A few errors in your code. the most important one was noticed by #PRMoureu. Your definition is called car, and the variable for your image is also called car. Since you created the image variable first, then created a function with the same name you erased the image, and replaced it with the function. So simply change 'car' to something like 'carImage' or anything different than the function name. Also you fill the screen with the color blue, which if you look back you actually haven't defined. after debugging these errors. Here is the code:
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
carImage = pygame.image.load('car.png')
def car(x,y):
gameDisplay.blit(carImage,(x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(white)
car(x,y)
pygame.display.update()
clock.tick(24)
pygame.quit()
quit()
But Dont try it just yet!
From the title it appears that your error is 'couldnt open car.png'
however the issues in your code that i described should give a different error. I find that pretty wierd, and the only explanation to that(considering the fact that the directory is fine and python has permission to access the image) is that your file extension is NOT a png file, but maybe a jpg or something else.
If that's true, then copy the code i have above but change '.png' in
carImage = pygame.image.load('car.png')
to the correct extension of your image. That should do it.
If none of this works, then i'm afraid this is all the help i can really think of. Maybe more details may help.
I hope this proves helpful anyway. It did work with me, so... Good Luck!
How do I convert an image to another image in pygame without using sprite class? Also how can I remove the previous image after I convert it to another one?
I wrote a small program today that shows how I switch an objects image(it may help/answer your question). It has notes for most of the code's use so it is easier to understand how and why it works(for all I know, anyone could have started programming yesterday).
Anyway, here is the code:
import pygame, sys
#initializes pygame
pygame.init()
#sets pygame display width and height
screen = pygame.display.set_mode((600, 600))
#loads images
background = pygame.image.load("background.png").convert_alpha()
firstImage = pygame.image.load("firstImage.png").convert_alpha()
secondImage = pygame.image.load("secondImage.png").convert_alpha()
#object
class Player:
def __init__(self):
#add images to the object
self.image1 = firstImage
self.image2 = secondImage
#instance of Player
p = Player()
#variable for the image switch
image = 1
#x and y coords for the images
x = 150
y = 150
#main program loop
while True:
#places background
screen.blit(background, (0, 0))
#places the image selected
if image == 1:
screen.blit(p.image1, (x, y))
elif image == 2:
screen.blit(p.image2, (x, y))
#checks if you do something
for event in pygame.event.get():
#checks if that something you do is press a button
if event.type == pygame.KEYDOWN:
#quits program when escape key pressed
if event.key == pygame.K_ESCAPE:
sys.exit()
#checks if down arrow pressed
if event.key == pygame.K_DOWN:
#checks which image is active
if image == 1:
#switches to image not active
image = 2
elif image == 2:
image = 1
#updates the screen
pygame.display.update()
I am not sure how your code is set up or if this is what you need (I don't entirely understand classes either so it might be a sprite class), but I hope this helps!
Converting one image to another is as simple as reassigning the variable
firstImage = pygame.image.load("firstImage.png")
secondImage = pygame.image.load("secondImage.png")
firstImage = secondImage
del secondImage
I'm not sure what exactly you mean by removing the image. You could use "del secondImage" to delete the reference in your code and send it to garbage collection. Once you clear the screen and blit the updated image there should no longer be any sign of the outdated image.
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.
I got a problem with a python programm, using pygame. I want to make a sun in a solar system spin (rotate). It works partially: the problem about some strange "stuttering" of the sun when running the programm. This stuttering occurs again and again, in a loop. Heres the code:"
# -*- coding: utf-8 -*-
import pygame as pg
import pygame.locals as local
import sys
def rot_center(image, angle):
"""rotate an image while keeping its center and size"""
orig_rect = image.get_rect()
rot_image = pg.transform.rotate(image, angle)
rot_rect = orig_rect.copy()
rot_rect.center = rot_image.get_rect().center
rot_image = rot_image.subsurface(rot_rect).copy()
return rot_image
pg.init()
#deklaration
xres=0
yres=0
#auflösungseinstellungen
try:
xres=int(sys.argv[1]) #auflösung von der kommandozeile, parameter 1
yres=int(sys.argv[2]) #auflösung von der kammondozeile, parameter 2
except IndexError:
xres=800
yres=600
screen = pg.display.set_mode((xres,yres)) #coords nicht hart coden, variablen nutzen
pg.display.set_caption("future rpg prepreprepalphawhatever")
pg.mouse.set_visible(1)
pg.key.set_repeat(1,30)
clock = pg.time.Clock()
running = 1
rotation_stat = 0.0
while running:
planet01 = pg.image.load("grafik/menu/planet02.png")
planet01.set_colorkey((251,0,250), local.RLEACCEL) #load planet01
sun = pg.image.load("grafik/menu/sun.png") #load sun
bg = pg.image.load("grafik/menu/bg.png") #load background
#den hintergrund skalieren, falls auflösung zu hoch
sizedbg = pg.transform.smoothscale(bg, (xres, yres))
rotation_stat += 1
clock.tick(30)
screen.fill((0,0,0))
screen.blit(sizedbg, (0,0))
screen.blit(planet01, (xres/5-planet01.get_width()/2,yres/2-planet01.get_height()/2))
orig_rect = sun.get_rect()
sun = pg.transform.rotate(sun, rotation_stat)
screen.blit(sun, (xres/2-sun.get_width()/2,yres/2-sun.get_height()/2))
rot_rect = orig_rect.copy()
rot_rect.center = sun.get_rect().center
sun = sun.subsurface(rot_rect).copy()
for event in pg.event.get():
if event.type == local.QUIT:
running = 0
if event.type == local.KEYDOWN:
if event.key == local.K_ESCAPE:
pg.event.post(pg.event.Event(local.QUIT))
pg.display.flip()
Put the code for loading the images outside the loop
I'm not entirely sure but it seems like you are loading the images every time your loop runs which is heavily intensive on your CPU
I have rewritten my answer based on your comments and after having glanced over the pygame docs
You really do only need to load your images once. What I am doing here is always rotating the originally loaded sun to a new surface, using the incrementing rotation. The rotation always wraps back to 0 degrees. As for the jitter, I am sure that related to an aliasing artifact and maybe even your centering math. But my goal was to address the biggest performance hit which was reading your sun image from disk every frame (30 times a second)
import pygame as pg
import pygame.locals as local
import sys
def main():
pg.init()
xres=800
yres=600
try:
xres=int(sys.argv[1])
yres=int(sys.argv[2])
except IndexError:
pass
screen = pg.display.set_mode((xres,yres))
pg.display.set_caption("future rpg prepreprepalphawhatever")
pg.mouse.set_visible(1)
pg.key.set_repeat(1,30)
clock = pg.time.Clock()
rotation_stat = 0.0
planet01 = pg.image.load("earth.png")
planet01.set_colorkey((251,0,250), local.RLEACCEL) #load planet01
sun = pg.image.load("sun.png") #load sun
bg = pg.image.load("bg.png") #load background
sizedbg = pg.transform.smoothscale(bg, (xres, yres))
planet_pos = (xres/5-planet01.get_width()/2,yres/2-planet01.get_height()/2)
running = 1
xres_cent, yres_cent = xres/2, yres/2
while running:
clock.tick(30)
for event in pg.event.get():
if event.type == local.QUIT:
running = 0
if event.type == local.KEYDOWN:
if event.key == local.K_ESCAPE:
pg.event.post(pg.event.Event(local.QUIT))
rotation_stat += 1
if rotation_stat % 360 == 0:
rotation_stat = 0.0
screen.blit(sizedbg, (0,0))
screen.blit(planet01, planet_pos)
sun_rect = sun.get_rect()
sun_rotated = pg.transform.rotate(sun, rotation_stat)
center = sun_rotated.get_rect().center
sun_pos = (xres_cent-center[0], yres_cent-center[1])
screen.blit(sun_rotated, sun_pos)
pg.display.flip()
pg.quit()
if __name__ == "__main__":
main()