I can't load images to my pygame program - python

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.

Related

How to pass directory to pass pygame icon?

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.

Continual listening of a linux device file in Python3

I use device files to read entries with the open() and f.read() functions, but the problem is that read() doesn't stop until there is a new entry. So I can't let my program do anything else...
running = True
with open("/dev/input/js0", "rb") as f:
while running:
event = f.read(8)
pygame.display.flip()
clock.tick(30)
pygame.quit()
For example, here I can only draw the window if the device is used.
Thanks for reading.
One option is to use Python's select.poll method, which lets you check to see if a file descriptor has any input available. We could rewrite your code something like this:
import select
import pygame
pygame.init()
pygame.display.init()
pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
running = True
poll = select.poll()
with open("/dev/input/js0", "rb") as f:
poll.register(f, select.POLLIN)
while running:
events = poll.poll(0)
if events:
event = f.read(8)
print('FLIP!')
pygame.display.flip()
clock.tick(30)
pygame.quit()
For more reading, look for articles on "non blocking io" with Python.
Alternately, you could use Pygame's event handling code rather than reading directly from /dev/input/js0 yourself. For example:
import pygame
pygame.init()
pygame.joystick.init()
pygame.display.init()
pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
js = pygame.joystick.Joystick(0)
js.init()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
if event.type == pygame.JOYHATMOTION:
print('FLIP!')
pygame.display.flip()
clock.tick(30)
pygame.quit()
The above code will only react to hat pressed, but you could easily extend it to listen to axis and button actions as well.

Simple Python Program freezes

I wrote a little Python script that is supposed to run a webcam-preview and exit it when ESC is pressed (using Pygame).
It kind of works, but more often than not it freezes the screen..
Does anyone see any issues with this code?
#!/usr/bin/python3
from picamera import PiCamera
camera = PiCamera()
camera.start_preview()
import pygame
import subprocess
def main():
pygame.init()
screen = pygame.display.set_mode((10, 10))
while True:
pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
camera.stop_preview()
return
main()
You need to have a call to pygame.display.flip() somewhere in your game loop otherwise it'll act like it's frozen.

Window freeze after pygame program runs

I am learning pygame and have been working on examples given in 'Python Crash Course' book by Eric Matthews (https://g.co/kgs/WP5fay). I have installed pygame version 1.9.3 on macOS High Sierra.
When I run the following program, a window opens and when I click 'X' to close it, the window freezes and the curses keeps circling and I get a python not responding error in activity monitor. I have tried a number of option to fix the problem but it is not going away.
import pygame
import sys
def run_game():
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Alien Invasion')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
run_game() #when I run this function, a window opens and freezes a couple of seconds after
You have to terminate the application loop and uninitialize all pygame modules with pygame.quit():
def run_game():
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Alien Invasion')
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.flip()
pygame.quit()
sys.exit()

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