I've just started programming in Python. I've been reading the book called "Making Games with Python & Pygame" and it's been very helpful so far, but I cannot find the reason why this simple program freezes. It should display an image and then move it by pressing left or right. It's strange, since it was working properly --I didn't change anything. I have tried everything so I'd really appreciate your help! Thanks in advance!
import pygame, sys
from pygame import *
# VARIABLES
x_res = 400
y_res = 300
DISPLAYSURF = 0
event = 0
person = 0
posx = 50
posy = 50
pygame.init()
DISPLAYSURF = pygame.display.set_mode((x_res, y_res))
pygame.display.set_caption("Test")
person = pygame.image.load("Person.png")
while True: # main game loop
DISPLAYSURF.blit(person, (posx, posy))
if event in pygame.event.get():
if event.type == KEYUP and event.key == K_RIGHT:
posx = posx + 5
DISPLAYSURF.fill((0,0,0))
if event.type == KEYUP and event.key == K_LEFT:
posx = posx - 5
DISPLAYSURF.fill((0,0,0))
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
pygame.display.update()
I'm not sure what you mean by "freezing" in this case, but I guess the problem is because you don't have an image called "Person.png", since when I tried out your code without an image on my file system called "Person.png" it also froze and gave me the error on the IDLE:
Traceback (most recent call last):
File "/Users/me/Desktop/your_program.py", line 17, in <module>
person = pygame.image.load("Person.png")
pygame.error: Couldn't open Person.png
Instead, if I have an image called "Person.png", it works properly.
Try writing "(wilst) true" instead of while? :)
Related
Okay, so I am writing a script that controls the motors using a sbc motor shield board with my raspberry pi 3b.
The issue I am having is that if I just run the script a window will pop up for a split second allowing to press the a key to move the motor forward or any other keys that I have already defined within the script but it only last for a second before the window auto exits and I am returned to the terminal.
Now when I attempt to add a loop to keep the code running the window will stay open however it no longer recognizes when I press a key defined in the script.. I have spent hours researching and modifying the script I have wrote and have not been able to find a solution. I am very new to python and I appreciate any input given.
Also I am running python 3.6 thanks in advance
import pygame
import sys
import pygame.locals
import PiMotor
import time
m1 = PiMotor.Motor("MOTOR1",1)
m2 = PiMotor.Motor("MOTOR2",1)
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Johnny, motor controls!')
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
m1.stop()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
m1.forward(100)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
m1.stop()
You just need to add a while True: when you get the events and check when to quit.
If you tried it and it didn't work maybe you had your indentation wrong? I see that it is wrong now in the code that you posted.
Something like:
while True:
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0) # BTW, do you really need this sleep?
[... Rest of your code ...]
It says this when I'm trying to use event.type. I have not used the event module before though, but it says in my book that it is supposed to work. I looked this up, on google and on stack overflow, but I didn't find anything like this (I used Javascript for the code snippet, because i didn't know how to get the code into python.)
import pygame
from pygame import *
pygame.init()
pygame.event.get()
black = (0,0,0)
white = (255,255,255)
playercoords_a = (275,425)
playercoords_b = (275,475)
playercoords_c = (225,475)
playercoords_d = (225,425)
playertotalcoords = (playercoords_a, playercoords_b, playercoords_c, playercoords_d)
windowSurface = pygame.display.set_mode((500, 500),0,32)
windowSurface.fill(black)
xmod = 0
ymod = 0
pygame.draw.polygon(windowSurface,white,((275,425),(275,475),(225,475),(225,425)))
pygame.display.update()
while True:
if event == KEYDOWN:
if event.key == K_LEFT:
print('it works')
windowSurface.fill((black,))
pygame.draw.polygon(windowSurface,white,((275 + xmod,425 + ymod),(275 + xmod,475 + ymod),(225 + xmod,475 + ymod),(225 + xmod,425 + ymod)))
pygame.display.update()
line 19, in
if event.type == KEYDOWN:
AttributeError: 'module' object has no attribute 'type'
In pygame, you usually have a for loop for event handling, and in your case it should look like this:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print('it works')
...
In this case, event is an event object returned from pygame.event.get() and not an module.
What you do is importing pygame's event module into the global namespace with from pygame import *. So when you run
while True:
if event == KEYDOWN:
event is actually this very module, and not an acutal event object.
Never do from pygame import *.
Currently trying to run a pygame script. The Script itself is fine however I think the installation is causing me some problems. I am using a mac and my script is located on my desktop. If I would like to load images on to the script I must place this in '/users/himansu' In addition I am using spyder (anaconda) when running this. I have tried terminal which keeps bringing up the error:
AttributeError: module 'pygame' has no attribute 'init'
When I hit run in spyder it loads the pygame script however my keys are not moving the object on screen rather the cursor remains inside the spyder application.. This I know hasn't got anything to do with the code which is posted below:
import pygame
import os
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('A bit Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load('racecar.png')
def car(x,y):
gameDisplay.blit(carImg,(x,y))
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
print(x_change)
gameExit = False
while not gameExit:
#event handling loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
#one way to exit the loop
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x,y)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
The code worked (the keys moved the object) when I was moving some files around however it is now back to normal. My working directory inside spyder is '/users/himansu'. I feel like if I can get this script running in terminal it may function. Thank you.
The code is fine i ran it and it worked. Try reinstalling pygame or adding sys to the import
import pygame, sys, os
direct download link ----> http://pygame.org/ftp/pygame-1.9.2a0.win32-py3.2.msi
This question already has answers here:
Lag when win.blit() background pygame
(2 answers)
Closed 2 years ago.
I have been making a simple python game using pygame and after I added the feature of switching guns the game started to lag. I have no idea why it is lagging. I have tried rebooting but it didn't work. The code is really short so maybe it is just my computer, but if there is anything that may help run it faster please let me know. Here is the code:
import sys, pygame, pygame.mixer
from pygame.locals import *
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Blue Screen of Death')
#variables
x = 100
y = 200
gun_type = "gun1"
gun = pygame.image.load("gun1.png")
gun = pygame.transform.scale(gun,(500,250))
gun_sound = pygame.mixer.Sound("gun_sound.wav")
clock = pygame.time.Clock()
while 1:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
gun_sound.play()
elif event.type == KEYDOWN and event.key == K_1:
gun = pygame.image.load("gun1.png")
gun = pygame.transform.scale(gun,(500,250))
gun_type = "gun2"
elif event.type == KEYDOWN and event.key == K_2:
gun = pygame.image.load("gun2.png")
gun = pygame.transform.scale(gun,(500,250))
gun_type = "gun2"
elif event.type == KEYDOWN and event.key == K_TAB:
if gun_type == "gun2":
gun_type = "gun2_aimed"
elif gun_type == "gun2_aimed":
gun_type = "gun2"
elif gun_type == "gun2_aimed":
gun = pygame.image.load("gun2_aimed.png")
gun = pygame.transform.scale(gun,(500,250))
#frames per second
clock.tick(60)
hallway = pygame.image.load("hallway.png")
hallway = pygame.transform.scale(hallway,(600,400))
screen.blit(hallway,(0,0))
screen.blit(gun,(mx-100,y))
pygame.display.flip()
Thanks for your help.
This is probably the most important thing you can learn in Pygame.
For many years, I've had lagging issues in Pygame. I was frustrated, and almost switched to Pyglet. My game was only running at 9 fps.
Then I found some Pygame documentation on my computer. It had some advice from David Clark, and he suggested you add .convert_alpha() at the end of all Pygame image loads. This increased my framerate to 32!
Here's the website:
https://www.pygame.org/docs/tut/newbieguide.html
I always just create a function to do it for me, so I don't have to keep typing '.convert_alpha()' too many times:
def loadify(imgname):
return pygame.image.load(imgname).convert_alpha()
Just replace pygame.image.load( to loadify( when using this function.
Have fun with Pygame!
You could try to load the images of your guns before the while loop and save a reference to them, this way you don't have to load the image on the fly every time.
Don't call pygame.image.load from your event handler.
Instead, call it on all of your resources at startup and just switch out which one you use.
Can anyone tell me why my app quits with:
pygame error: display Surface quit.
I had similar problem and discovered that Surface objects don't like to be deepcopied. When I used copy.deepcopy() on such object and then accessed the copy, I got that strange error message (without calling pygame.quit()). Maybe you experience similar behavior?
I had a similar problem in a very simple piece of code:
import sys, pygame
pygame.init()
size = width, height = 640, 480
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("Golfball.png")
ballrect = ball.get_rect()
while 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
pygame.time.delay(5)
Error message was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bounce.py", line 22, in <module>
screen.fill(black)
pygame.error: display Surface quit
So I put
import pdb
at the top after
pygame.init()
and used
pdb.set_trace()
after the line with
pygame.quit()
Now I ran the program, clicked to close the window and was actually a bit surprised to see that I fell into the debugger (after all, I expected the quit to completely take me out immediately). So I concluded that the quit doesn't actually stop everything at that point. Looked like the program was continuing beyond the quit, was reaching
screen.fill(black)
and this was causing the problem.
So I added
break
after the
pygame.quit()
and all works happily now.
[ Added later: It occurs to me now that
pygame.quit()
is quitting the module, and not the program that is running, so you need the break to get out of this simple program. ]
Just for the record, this means the good version is
import sys, pygame
pygame.init()
size = width, height = 640, 480
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("Golfball.png")
ballrect = ball.get_rect()
while 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
break
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
pygame.time.delay(5)
Replace if event.type == pygame.quit(): by if event.type == pygame.QUIT:
Make sure if you write pygame.QUIT: and not pygame.quit():
I know it sounds weird, but I had the same problem.
import pygame, sys
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
sys.exit()
call sys.exit() after pygame.quit() to stop the program so you can not change the surface after you have quit pygame and not get the error
From http://archives.seul.org/pygame/users/Nov-2006/msg00236.html :
On Thu, 2006-11-30 at 21:27 -0300, Nicolas Bischof wrote:
pygame.error: display Surface quit
what does that mean?, i can't fix it
This means a call was made to pygame.display.quit() or pygame.quit(). If
you try to do anything to the display surface after quit you will get
this error.
I had this problem too, but got it from another origin.
I had a class defined like this:
class PauseMenu(pygame.Surface)
i got the error when forgetting to initialize the pygame.Surface and trying to blit it, making pygame.screen crash and gave me this error.
so i just added this obviously
pygame.Surface.__init__(self, (width, height))
I had the similar problem just right now and I have found a solution to it.
Because it seems like pygame.quit() will just quit the pygame module and not the entire program, use sys.exit() method on the following line.
After this:
pygame.quit()
Place this:
sys.exit()
Complete snippet:
pygame.quit()
sys.exit()
I too had this problem, and similar to Maciej Miąsik's answer mine had to do with copy.deepcopy()-ing an image.
I had:
import copy,pygame,sys
from pygame.locals import *
EMPTY_IMG= pygame.image.load('C:super/fancy/file/path/transparent.png')
held_image=copy.deepcopy(EMPTY_IMG)
my_rect=held_image.get_rect()
my_rect.center = (50,50)
screen.blit(held_image,my_rect)
And I got the same error.
I simply changed the copy.deepcopy(EMPTY_IMG) to just EMPTY_IMG.
import copy,pygame,sys
from pygame.locals import *
EMPTY_IMG= pygame.image.load('C:super/fancy/file/path/transparent.png')
held_image=EMPTY_IMG
my_rect=held_image.get_rect()
my_rect.center = (50,50)
screen.blit(held_image,my_rect)
Then it all worked fine.
Just update the display in the infinite loop.
Type this:
pygame.display.update()