Why does my pygame window freeze and crash? - python

Whenever I try to run my program it freezes up and crashes. I'm not a master pygame coder, but I'm almost sure its something to do with my main loop. It's supposed to allow the user to move left and right using arrow keys. I've tried adding a clock and changing the size of the screen but that didn't work. Here is the code:
import pygame
import sys
import random
import time
pygame.init()
screen = pygame.display.set_mode((500,500))
events = pygame.event.get()
clock = pygame.time.Clock()
x = 50
y = 50
game_over = False
while not game_over:
for event in events:
if event.type != pygame.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
elif event.key == pygame.K_LEFT:
x -= 5
else:
sys.exit()
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
clock.tick(30)
pygame.display.update()

The code needs to process the event queue continuously, otherwise your operating environment will consider your window to be non-responsive (locked up). Your code is almost there, except it only fetches the new events once, but this needs to be done every iteration of the main loop.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
x = 50
y = 50
game_over = False
while not game_over:
events = pygame.event.get() # <<-- HERE handle every time
for event in events:
if event.type != pygame.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
elif event.key == pygame.K_LEFT:
x -= 5
else:
sys.exit()
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
clock.tick(30)
pygame.display.update()

You cant do foe event in events, as when you call pygame.events.get(), you are updating them, you are updating them once and looping over them every frame, you need to use for event in pygame.event.get(): so you are calling the function every frame and updating the events every frame
unless you were trying to do this?
events = pygame.event.get
...
for event in events():
which does the same as above

Related

Quit Algorithm pygame Not working properly [duplicate]

This question already has an answer here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 2 years ago.
In this I want the program to close when they hit the quit button but if I enable my Check_Key_Press() function, the Close() function does not work however If I comment out the Check_Key_Press() function then it works again.
import pygame
pygame.init()
width, height = 500,500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tic Tac Toe(GUI)")
clock = pygame.time.Clock()
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
Tile_dime = 59
Diff = (Tile_dime+1)/2
board_det = [['-',(width/2-3*Diff,height/2-3*Diff)],['-',(width/2-Diff,height/2-3*Diff)],['-',(width/2+Diff,height/2-3*Diff)],
['-',(width/2-3*Diff,height/2-Diff)],['-',(width/2-Diff,height/2-Diff)],['-',(width/2+Diff,height/2-Diff)],
['-',(width/2-3*Diff,height/2+Diff)],['-',(width/2-Diff,height/2+Diff)],['-',(width/2+Diff,height/2+Diff)]]
def draw_board():
for i in range(len(board_det)):
pygame.draw.rect(win, white, [board_det[i][1], (Tile_dime, Tile_dime)])
def Close():
global run
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
def Check_Key_Press():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pass
if event.key == pygame.K_LEFT:
pass
run = True
while run:
clock.tick(60)
draw_board()
Check_Key_Press()
Close()
pygame.display.update()
pygame.event.get() get all the messages and remove them from the queue. If pygame.event.get () is called in multiple event loops, only one loop receives the events, but never all loops receive all events. As a result, some events appear to be missed.
Get the events once and use them in multiple loops or pass the list or events to functions and methods where they are handled:
def Close(event_list):
global run
for event in event_list:
if event.type == pygame.QUIT:
run = False
def Check_Key_Press(event_list):
for event in event_list:
if event.type == pygame.KEYDOWN:
pass
if event.key == pygame.K_LEFT:
pass
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
draw_board()
Check_Key_Press(event_list)
Close(event_list)
pygame.display.update()

Why isn't my sprite moving when i press a specific key in pygame

I was building a simple rocket game and it required moving some sprites. In the code below cloud1 is supposed to move -30 pixels towards the bottom each time i press the K_DOWN key. I have been trying to figure out what is wrong with the code for 3 days but haven't progressed even a little bit. Help would be much appreciated.
import pygame
pygame.init()
DISPLAY_HEIGHT = 700
DISPLAY_WIDTH = 900
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Rocket Game')
clock = pygame.time.Clock()
FPS = 60
#colors
WHITE = (255,255,255)
BLACK = (0,0,0)
SKY_BLUE = (102,178,255)
cloud1 = pygame.image.load('cloud.png')
cloud1_X, cloud1_Y = 100, 50
cloud1_Y_change = 30
def cloud1_display(x, y):
screen.blit(cloud1, (x, y))
running = True
while running:
screen.fill(SKY_BLUE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
cloud1_Y += cloud1_Y_change
cloud1_display(cloud1_X, cloud1_X)
clock.tick(FPS)
pygame.display.update()
There are two problems. The first is that your code is not checking the event.key for the pygame.K_UP. But your code is also painting the cloud at (x, x), not (x, y).
Corrected code:
while running:
screen.fill(SKY_BLUE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP: # <<-- HERE
cloud1_Y += cloud1_Y_change
cloud1_display(cloud1_X, cloud1_Y) # <<-- AND HERE
clock.tick(FPS)
pygame.display.update()
For you main game loop try to use event.key instead of event.type for the second time. Like so:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
cloud1_Y += cloud1_Y_change
Another issue that I have noticed is that your not converting your image to a rect object in pygame and then use .blit to show it onscreen. The .blit function requires a rect object argument, so that's why your having issues.
cloud1 = pygame.image.load('asteroid_pic.bmp')
rect = cloud1.get_rect()
screen.blit(cloud1, self.rect)
I also recommend creating separate classes for your sprites, so that its easier to keep track of them and if you want to create duplicates of the same one but still retain the same characteristics of the single class sprite you can do so by importing the function Group from pygame.sprite.

Event Coding Keyboard Input

I am coding with python on my raspberry pi. Python isn't my best language so bear with me.
I need a simple code that responds to key strokes on my keyboard. I'd doing this so I can set the Pulse Width Modulation, but I don't need that code, I already have it. My main concern is I am struggling to understand the pygame functionality required for my task.
I would like to be able to type a key, such as "up arrow" ↑ and have the program output "up pressed" for every millisecond the up arrow is pressed.
The pseudo-code would look like:
double x = 1
while x == 1:
if input.key == K_UP:
print("Up Arrow Pressed")
if input.key == K_q
x = 2
wait 1ms
pygame.quit()
Again I have no clue what to import or call due to not knowing the syntax.
Here's some code that will check if the ↑ key is pressed:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
print("Up Arrow Pressed")
elif keys[pygame.K_q]:
done = True
clock.tick(1000)
pygame.quit()
Note that clock.tick(1000) will limit the code to one-thousand frames per second, so won't exactly equate to your desired 1 millisecond delay. On my PC I only see a frame rate of around six-hundred.
Perhaps you should be looking at the key down and key up events and toggle your output then?
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
done = False
output = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
output = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
output = False
elif event.key == pygame.K_q:
done = True
pygame.display.set_caption(f"Output Status {output}")
clock.tick(60)
pygame.quit()
If you run this, you'll see the title of the window change whilst the ↑ key is pressed.

Pygame used in VS Code with Pygame Snippets [duplicate]

This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
What all things happens inside pygame when I press a key? When to use pygame.event==KEYDOWN
(1 answer)
Closed 2 years ago.
I have installed vs code and added pygame snippets to use pygame library. My big problem is, every time I try to use any key option of pygame, like pygame.KEYDOWN or pygame.QUIT it tells me that QUIT is not a function of pygame. Can someone help me?
Everything else seems to work, like display or surface
even pygame.key.get_pressed() don’t make problems.
import pygame, random, sys
from pygame.locals import *
from pygame.key import *
def set_Background():
screen = pygame.display.set_mode((500,500))
surface = pygame.image.load('Background.png')
surface = pygame.transform.scale(surface, (500, 500))
screen.blit(surface, (0,0))
pygame.display.update()
return screen
def set_Enemy():
enemy = pygame.image.load('Enemy.png')
enemy = pygame.transform.scale(enemy, (50, 50))
return enemy
def set_Player():
player = pygame.image.load('Player.png')
player = pygame.transform.scale(player, (70, 70))
return player
RUNNING = True
while RUNNING:
background = set_Background()
enemy = set_Enemy()
player = set_Player()
enemy_rect = enemy.get_rect()
player_rect = player.get_rect()
e_x = random.randint(10,450)
e_y = random.randint(10,450)
background.blit(enemy, (e_x, e_y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == key[pygame.K_ESCAPE]:
#module pygame has no K_ESCAPE member
sys.exit()
if event.type == pygame.QUIT:
#says module pygame has no QUIT member
sys.exit()
pygame.key.get_pressed() shouldn't be in the event loop, but in the main while loop. In the event loop you need to check if the event type is pygame.QUIT and then set the running flag to False.
Here's a fixed version:
import pygame
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
running = True # Uppercase names are for constants not variables.
while running:
# The event loop.
for event in pygame.event.get():
# If a pygame.QUIT event is in the queue.
if event.type == pygame.QUIT:
running = False
# To check if it was a `KEYDOWN` event.
elif event.type == pygame.KEYDOWN:
# If the escape key was pressed.
if event.key == pygame.K_ESCAPE:
running = False
# Use pygame.key.get_pressed to see if a key is held down.
# This should not be in the event loop.
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
print('up arrow pressed')
screen.fill((30, 30, 30))
pygame.display.flip()
clock.tick(60)
Add from pygame.locals import * at the top of your code.
You are mixing two types of key presses in one go. You should instead either
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SOMEKEY:
do_something()
or
keys = pygame.key.get_pressed()
if keys[pygame.K_somekey]:
do_something()
so the code above with the pygame.key.get_pressed() should not be in the event loop

How to move an image in pygame/python with keypress?

I am making a Pong game in Python. To do this, I am using pygame. I am trying to make an image move continuously on a keypress. I have tried multiple methods, but none have worked. here is my code for the movement:
import pygame, sys
from pygame.locals import *
import time
try: #try this code
pygame.init()
FPS = 120 #fps setting
fpsClock = pygame.time.Clock()
#window
DISPLAYSURF = pygame.display.set_mode((1000, 900), 0, 32)
pygame.display.set_caption('Movement with Keys')
WHITE = (255, 255, 255)
wheatImg = pygame.image.load('gem4.png')
wheatx = 10
wheaty = 10
direction = 'right'
pygame.mixer.music.load('overworld 8-bit.WAV')
pygame.mixer.music.play(-1, 0.0)
#time.sleep(5)
#soundObj.stop()
while True: #main game loop
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
pygame.mixer.music.stop()
keys_pressed = key.get_pressed()
if keys_pressed[K_d]:
wheatx += 20
#events = pygame.event.get()
#for event in events:
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_p:
# pygame.mixer.music.stop()
# time.sleep(1)
# pygame.mixer.music.load('secondscreen.wav')
# pygame.mixer.music.play()
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Indentation is normal, I am new to stackoverflow! I have an except, which is why the try is there. Thanks for the help!
This code will move the image down upon the down arrow key being pressed and up if the up arrow key is pressed (should you not be changing the Y-axis and wheaty if the user presses the down key rather than altering wheatx ?). Do similar for the other arrow keys.
while True:
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
pygame.mixer.music.stop()
if event.key == pygame.K_DOWN:
wheaty +=20
elif event.key == pygame.K_UP:
wheaty -= 20
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)

Categories

Resources