Well, I was happy starting on Pygame with a bit of knowledge on python, But while i was following some starter tutorials i noticed that, At the moment of running my code the Pygame window didn't see to respond, so i put some "print" commands to see how far did it get, I noticed that it stopped on the Loop, Any ideas on how i can fix it? I will leave the code around here
import pygame
pygame.init()
print("First Fase")
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("Test")
print("Second Fase")
x = 50
y =50
width = 40
height = 60
vel = 7
print("Third Fase")
done = False
while not done:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_ESC:
done = True
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
print("NoErrors")
It has to be pygame.KEYDOWN and pygame.K_ESC rather than KEYDOWN and K_ESC.
But fist of all you have to respect the Indentation. In the following code the loops are not nested:
done = False
while not done:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
The for loop is not in the while, it is a separate loop after the while loop.
You have to format your code like this:
import pygame
pygame.init()
print("First Fase")
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("Test")
print("Second Fase")
x = 50
y =50
width = 40
height = 60
vel = 7
print("Third Fase")
done = False
while not done:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESC:
done = True
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
print("NoErrors")
Related
Ask for any more information if needed!
I am using vscode's ide and python 3. When I run script.py the display will pop-up, but a half of a second later the display will disappear and will give this error pyagame.error: Video not intiialized.
import pygame
pygame.init()
run = True
while run:
screen = pygame.display.set_mode([500, 500])
pygame.display.set_caption("TicTac")
pygame.quit()
x = 250
y = 250
width = 40
height = 60
vol = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT():
run = False
run = False
pygame.QUIT()
You do pygame.quit() immediately after pygame.display.set_mode(). pygame.quit() terminates all pygame modules. Remove it:
screen = pygame.display.set_mode([500, 500])
pygame.display.set_caption("TicTac")
# pygame.quit() <--- DELETE
pygame.QUIT is not a function, it is an enumerator constant. You can't invoke pygame.QUIT:
if event.type == pygame.QUIT():
if event.type == pygame.QUIT:
You need just one application loop, not 2 of them. Furthermore you have to update the window by either pygame.display.flip() or pygame.display.update()
import pygame
pygame.init()
screen = pygame.display.set_mode([500, 500])
pygame.display.set_caption("TicTac")
x, y = 250, 250
width, height = 40, 60
vol = 5
run = True
while run:
pygame.time.delay(100)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# clear dispaly
screen.fill((0, 0, 0))
# draw the scene
pygame.draw.rect(screen, (255, 0, 0), (x, y, width, height))
# update display
pygame.display.flip()
pygame.quit()
Im trying to make a simple image gallery which loads images with keystrokes using pygame in python, and this is how far i got
import pygame
pygame.init()
width=1366;
height=768
screen = pygame.display.set_mode((width, height ), pygame.NOFRAME)
pygame.display.set_caption('Katso')
penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()
x = 0; # x coordnate of image
y = 0; # y coordinate of image
*keys = pygame.event.get()
for event in keys:
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
screen.blit(mickey,(x,y)); pygame.display.update()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
screen.blit(penguin,(x,y)); pygame.display.update()*
running = True
while (running): # loop listening for end of game
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#loop over, quit pygame
pygame.quit()
i expect to press the arrow keys to load certain images
the screen opens but no image gets loaded
Program never wait for keypress so you have to check keys inside while loop.
import pygame
# --- constants --- (UPPER_CASE)
WIDTH = 1366
HEIGHT = 768
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
pygame.display.set_caption('Katso')
# - objects -
penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()
x = 0 # x coordnate of image
y = 0 # y coordinate of image
# - mainloop -
running = True
while running: # loop listening for end of game
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
#screen.fill( (0, 0, 0) )
screen.blit(mickey,(x,y))
pygame.display.update()
elif event.key == pygame.K_RIGHT:
#screen.fill( (0, 0, 0) )
screen.blit(penguin,(x,y))
pygame.display.update()
# - end -
pygame.quit()
I'm having a hard time with pygame blitting text onto the screen. Right now before quitting I just want to have a message show up for 2 seconds, then have the game quit. To do this I use time.sleep(2). However, and I believe most other people don't have this issue from questions I've looked up on Stackoverflow, the text just doesn't show up until what seems to be the last moment before the window closes. Rather, the screen remains white after pressing the close button. My code is below. Please note that this is not a duplicate of this question.
import pygame
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
clock = pygame.time.Clock()
FPS = 30
font = pygame.font.SysFont(None, 25)
x = False
while not x:
for event in pygame.event.get():
if event.type == pygame.QUIT:
x = True
gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)
screen_text = font.render('Test', True, red)
gameDisplay.blit(screen_text, (0, 0))
pygame.display.update()
time.sleep(2)
pygame.quit()
I ended up using the pygame.time.set_timer workaround #CodeSurgeon mentioned.
This worked for me - replacing time.sleep(2), with:
pygame.time.set_timer(pygame.USEREVENT, 2000)
should_quit = False
while not should_quit:
for event in pygame.event.get():
if event.type == pygame.USEREVENT:
should_quit = True
I actually have the exact same problem and found that if I moved time.sleep(2) directly after pygame.quit() it worked as intended. I'm new to pygame and not sure why this works
screen_text = font.render('Test', True, red)
gameDisplay.blit(screen_text, (0, 0))
pygame.display.update()
pygame.quit()
time.sleep(2)
You could try replacing time.sleep(2) with
for i in range(0, 200, 1):
time.sleep(0.01)
This can be useful in other situations with long sleeps if you want to be able to use CTRL-C to stop the program. It also might be more convenient to use a function:
def MySleep(duration, resolution=10):
"""Sleep, without freezing the program. All values in ms"""
for i in range(0, int(duration), int(resolution)):
time.sleep(resolution / 1000)
for some reason, stdlib time.sleep() does not work in pygame.
However, pygame does have its own time function.
Here is the code I wrote to print out a message, character by character.
message = ""
font = pygame.font.Font("freesansbold.ttf", 32)
message_text_x = 0
message_text_y = 550
message_text_speed = 35
inF = open("chapter_1.txt")
lines = inF.readlines()
def write_message(char, x, y):
# first render the value as text so it can be drawn on the screen using screen.blit
message_text = font.render(char, True, (0, 0, 0))
screen.blit(message_text, (x, y))
running = True
while running:
for line in lines:
for char in line:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
running = False
if event.key == pygame.K_SPACE:
message_text_speed = 10
message += char
write_message(message, message_text_x, message_text_y)
pygame.event.pump()
pygame.time.delay(message_text_speed)
pygame.display.update()
clock.tick(60)
When spacebar is clicked the speed of the text becomes faster
I have two problems with my program:
When I close my program it has error: keys = pygame.key.get_pressed() pygame.error: video system not initialized
Square moves while I'm pressing 'd' and when I press something (or move mouse)
Important part of code is:
import pygame
from pygame.locals import*
pygame.init()
screen = pygame.display.set_mode((1200, 700))
ticket1 = True
# ...
c = 550
d = 100
# ...
color2 = (250, 20, 20)
while ticket1 == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
pygame.quit()
pygame.display.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
If I write keys = pygame.key.get_pressed() in just while loop it doesn't have error but it seems slower.
I also have another error: pygame.error: display Surface quit, but I always and in all my pygame programs have it and it isn'n so important but other things are important.
1.--------------
After pygame.quit() you don't need pygame.display.quit() but sys.exit().
pygame.quit() doesn't exit program so program still try to call screen.fill() and other function below pygame.quit()
Or you have to put pygame.quit() outside while ticket == True: (and then you don't need sys.exit())
You can use while ticket1: in place of while ticket == True: - it is more pythonic.
while ticket1: # it is more pythonic
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
pygame.quit()
2.--------------
if keys[pygame.K_d]: c += 1 is inside for event loop so it is call only when event is happend - when mouse is moving, when key is pressed or "unpressed". Move it outside of for event loop.
while ticket1: # it is more pythonic
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
keys = pygame.key.get_pressed()
# outside of `for event` loop
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
pygame.quit()
Some people do it without get_pressed()
# clock = pygame.time.Clock()
move_x = 0
while ticket1 == True:
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
ticket1 = False
elif event.key == pygame.K_d:
move_x = 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d:
move_x = 0
# variable modification
c += move_x
# ...
# draws
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
# 60 FPS (Frame Per Second) to make CPU cooler
# clock.tick(60)
pygame.quit()
BTW: use pygame.time.Clock() to get the same FPS on fast and slow computers. Without FPS program refresh screen thousends times per second so CPU is busy and hot.
If you use FPS you have to add to c bigger value to get the same speed then before.
This is my code:
import pygame, sys
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((800, 600))
pygame.display.set_caption('window')
black = (0,0,0)
white = (255, 255, 255)
logo = pygame.image.load('logo.png').convert_alpha()
clock = pygame.time.Clock()
# Sprites
m1 = pygame.image.load('m1.png').convert_alpha()
m2 = pygame.image.load('m2.png').convert_alpha()
mci = 1
x, y = 0, 0
run = True
while run:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
x -= 10
if event.type == pygame.K_RIGHT:
x += 10
if event.type == pygame.K_UP:
y -= 10
if event.type == pygame.K_DOWN:
y += 10
window.fill(white)
pygame.draw.rect(window, black,(x,y, 50, 50))
pygame.display.flip()
clock.tick(10)
Everything shows up, but I can't move the rectangle with my arrow keys, and I always get an error after I quit out of it, help.. Thanks in advance!
P.S I'm obviously copying from a tutorial, but i'm not sure what I've done wrong?
As you worked out, you need to use event.key == .... You probably also want to watch the nesting of your loop, currently you have:
while running:
for event in list_of_events:
process_event
draw_to_screen
wait_a_while
This caused a problem in another question (https://stackoverflow.com/a/13866804/2372604). What you probably want is something more like:
while running:
for event in list_of_events:
process_event
draw_to_screen
wait_a_while
You might also want to change pygame.quit(); sys.exit() to run = false and then add pygame.quit() at the end of the program.
The mistake what I wrote event.type instead of event.key.