How to pass directory to pass pygame icon? - python

I was trying to develop a basic python game
I wonder how can I pass a directory to pygame's pygame.image.load() method
I tried passing directory to the method as a usual way...
import pygame as pg
#Intializing pygame
pg.init()
#Creating screen
screen = pg.display.set_mode((800,600))
pg.display.set_caption("Mario Forever")
icon = pg.image.load('/resources/images/logo.png')
pg.display.set_icon(icon)
#Creating interrupt for exiting game in future
running = True
#Game quit event listener
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
But I am encountering an error
icon = pg.image.load('/resources/images/logo.png')
pygame.error: Couldn't open /resources/images/logo.png
Please suggest me where I am doing it wrong.

The problem is that your path '/resources/images/logo.png' starts with a /. That means that the path starts at the root directory of your harddisk.
When you ommit the first / the directory path 'resources/images/logo.png' is relative to your project directory.

Related

Unknown error shows up in my pygame script with the ""for event in event.get()""

I'm trying right know to begin with the pygame library and I follow a tutorial (you can find it right here:
https://dr0id.bitbucket.io/legacy/pygame_tutorial01.html )
My objective is to display an image on the screen and the transform it (e.g. move it, set alpha, background...)
So far, I've tried to search similar errors as mine, but found no precise examples in internet.
My code looks like this :
from pygame import *
def main():
#initialize
init()
#logo and caption
logo = image.load("logo32x32.png")
display.set_icon(logo)
display.set_caption("minimal game")
#create and size the screen
screen = display.set_mode((1366,700))
#set running var for the main loop
running = True
#Display an image, refresh the screen
blit = image.load("logo32x32.png")
screen.blit(blit, (32,32))
display.flip()
#main loop
while running:
#exit the loop if event is QUIT
for event in event.get():
if event.type == QUIT:
running = False
#run main only if the module execute as a main script
if __name__ == "__main__":
main()
The result I get by executing this script is a window with the image I wanted in the top left-hand corner for like 2 secs and then the application close by itself.
When I come back in VS code, it shows the following error:
PS C:\Users\Sacha PERUCHON\Documents\Cours\SNT\Cycle2\Python Scripts> & "C:/Users/Sacha
PERUCHON/AppData/Local/Microsoft/WindowsApps/python3.9.exe" "c:/Users/Sacha PERUCHON/Documents/Cours/SNT/Cycle2/Python Scripts/pygame_minimal.py"
pygame 2.1.2 (SDL 2.0.18, Python 3.9.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "c:\Users\Sacha PERUCHON\Documents\Cours\SNT\Cycle2\Python Scripts\pygame_minimal.py", line 30, in <module>
main()
File "c:\Users\Sacha PERUCHON\Documents\Cours\SNT\Cycle2\Python Scripts\pygame_minimal.py", line 24, in main
for event in event.get():
UnboundLocalError: local variable 'event' referenced before assignment
Any help is would be appreciated.
Try for event in pygame.event.get()
Also, just do import pygame, not from pygame import *

Why can't I change the python window icon? [duplicate]

This question already has an answer here:
Icons are not displayed properly with pygame
(1 answer)
Closed 2 years ago.
I want to change the pygame window icon with code:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")
icon = pygame.image.load('snake icon.png')
pygame.display.set_icon(icon)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
When I use that code It won't work,
like the window closed on its own,
but when I change the code to:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
It works, but It's still have the default pygame icon, i want to change the pygame icon,
can someone tell me what's wrong with the code?
Make sure that the resource (image) path and the working directory is correct.
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
Furthermore see pygame.display.set_icon():
[...] Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.
Set the icon before screen = pygame.display.set_mode((800, 600)):
icon = pygame.image.load('snake icon.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((800, 600))

Python3 error: "pygame.error: video system not initialized"

I'm trying to learn to make games using pygame module in python.
I'm using the ubuntu terminal in Windows 10. This is my program.
# 1 - Import library
import os
os.environ['SDL_AUDIODRIVER'] = 'dummy'
import pygame
from pygame.locals import *
# 2 - Initialize the game
print("-1")
pygame.init()
pygame.display.list_modes()
print("0")
width, height = 640, 480
print("00")
screen=pygame.display.set_mode((width, height))
print("1")
# 3 - Load images
player = pygame.image.load("resources/images/virus.png")
print("3")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
print("4")
# 6 - draw the screen elements
screen.blit(player, (100,100))
print("5")
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
As soon as I run the program, I get this error.
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
-1
Traceback (most recent call last):
File "pythongame.py", line 10, in <module>
pygame.display.list_modes()
pygame.error: video system not initialized
I looked at many posts but of no use. Please tell me how to resolve this.
If you inizialize the pygame "modules" that need to using pygame.init() and an error is thrown, this error is not displayed or anithyng like that.
You can initialize all "internal pygame modules" using something like pygame.display.init() If you do it this way a traceback get's printed. I also don't have any trouble using pycharm to execute this program.
Maybe it's something with the unbuntu terminal that you use. Try initializing the display class using pygame.display.init()
Here a link about what I said: pygame.org

I can't load images to my pygame program

I'm new to pygame and was copying a simple tutorial. i'm using python 3.4.2. but i'm running into several issues. Here is my code:
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
class Game(object):
def main(self,screen):
clock = pygame.time.Clock()
image = pygame.image.load('player.png').convert()
image_x=320
image_y=240
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN and event.key== pygame.K_ESCAPE:
pygame.quit()
image_x+=10
screen.fill((200,200,200))
screen.blit(image,(320,240))
screen.blit(image,(image_x,image_y))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen=pygame.display.set_mode((640,480))
Game().main(screen)
first problem is that i get an error stating "Couldn't open player.png" i have this image saved within the same folder as my .py game program. secondly when i try to exit the game, the pygame window freezes and stops responding.
It seems after a little debugging that the image file was actually in a subfolder. In order to load the image, you'll need to provide a more exact path to the file by changing this line
image = pygame.image.load('player.png').convert()
like so:
image = pygame.image.load('subfolder' + os.sep + 'player.png').convert()
Don't forget to add an import os line to the top of your file, in order to use the os.sep command, which makes directory separators cross platform.

pygame.error: file not a windows.bmp file (have looked at other similar questions but unsuccessful so far)

I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()

Categories