Stop multiple keyboard entries in Pygame - python

I have some python code that uses a pygame window to establish which key is being pressed. When a key is pressed, the code heads off and does things before coming back to see what the next key pressed might be.
The problem I have is that if the user presses a key repeatedly, even while the 'code heads off and does things', pygame seems to remember what has been pressed rather than waiting for the next keypress. What I want is for the code to ignore any keypresses while the 'go and do stuff' is done then once that's finished, get the next keypress. Hope this makes sense!
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((450,282))
screen.fill((0,0,0))
pygame.display.flip()
clock = pygame.time.Clock()
done = False
def go_and_do_things():
print("doing things")
time.sleep(2)
print("things done")
# Loop as long as done == False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.KEYDOWN:
keypressedcode = event.key # This is the ASCII code
print("keypressedcode is " + str(keypressedcode))
go_and_do_things()
elif event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
clock.tick(60)
time.sleep(4)
pygame.quit()

You could use pygame.event.clear. As written below, it will discard any keypresses during go_and_do_things().
while not done:
for event in pygame.event.get(): # User did something
# Any key down
if event.type == pygame.KEYDOWN:
keypressedcode = event.key # This is the ASCII code
print("keypressedcode is " + str(keypressedcode))
go_and_do_things()
pygame.event.clear(eventtype=[pygame.KEYDOWN,
pygame.KEYUP)
elif event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
clock.tick(60)

This is a fairly simple problem, you just need to add another
event.type for keyup. You also need to add a variable to make it stop
running which I will label as stopV if event.type == pygame.KEYUP:
stopV = True This should let you instantly stop it when you want to. edit because I want to reword this:
Re-doing this to make it more clear.
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((450,282))
screen.fill((0,0,0))
pygame.display.flip()
clock = pygame.time.Clock()
done = False
unClick = False
def go_and_do_things():
if unClick == False
print("hello")
# do anything you want in the function here
else
return
while not done:
for event in pygame.event.get(): # User did something
# Any key down
if event.type == pygame.KEYDOWN:
keypressedcode = event.key # This is the ASCII code
print("keypressedcode is " + str(keypressedcode))
go_and_do_things()
if event.type == pygame.KEYUP:
unClick == True
elif event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
clock.tick(60)

Related

how do i make a window quit in pygame?

I want to close the game after was pressed the esc button. how can I do? And where should I place it?
I also found some problems that I can't solve, so if you solve them for me I would be happy
This is the code:
#Import Libraries
import pygame
import random
#PyGame Initialization
pygame.init()
#Images Variables
background = pygame.image.load('images/sfondo.png')
bird = pygame.image.load('images/uccello.png')
base = pygame.image.load('images/base.png')
gameover = pygame.image.load('images/gameover.png')
tube1 = pygame.image.load('images/tubo.png')
tube2 = pygame.transform.flip(tube1, False, True)
#Display Create
display = pygame.display.set_mode((288,512))
FPS = 60
#Define Functions
def draw_object():
display.blit(background, (0,0))
display.blit(bird, (birdx, birdy))
def display_update():
pygame.display.update()
pygame.time.Clock().tick(FPS)
def animations():
global birdx, birdy, bird_vely
birdx, birdy = 60, 150
bird_vely = 0
#Move Control
animations()
while True:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if ( event.type == pygame.KEYDOWN
and event.key == pygame.K_UP):
bird_vely = -10
if event.type == pygame.QUIT:
pygame.quit()
draw_object()
display_update()
Well you do so by implementing below code snippet in your code:
running = True
while running:
# other code
event = pygame.event.wait ()
if event.type == pygame.QUIT:
running = False # Be interpreter friendly
pygame.quit()
Make sure that you call pygame.quit() before you exit your main function
You can also reference this thread
Pygame escape key to exit
You must terminate the application loop when the QUIT event occurs. You have implmented the QUIT event, but you don't terminate the loop. Add a variabel run = True and set run = False when the event occurs.
To terminate the game when ESC is pressed you have to implement the KEYDOWN event. Set run = False when the KEDOWN event occurs and event.key == pgame.K_ESC:
run = True
while run:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pgame.K_ESC:
run = False
elif event.key == pygame.K_UP:
bird_vely = -10
draw_object()
display_update()
pygame.quit()
exit()

Pygame application doesn't close out the first time

I am building a small game in pygame and I wanted a function to exit out. However it takes multiple clicks to exit and it is not consistent either. Also the windows exit function is restarting the program, too Here is the part of the code that deals with exiting
if isKill:
pygame.mixer.music.stop()
gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
rect = gameover.get_rect()
rect.center = screen.get_rect().center
screen.blit(gameover, rect)
if event.type == KEYDOWN:
if event.key == K_r:
gameloop()
and
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
*gameloop() is the whole script
Instead of event.type, you can use the pygame builtin event QUIT
Refer the following code
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Can use pygame.quit() in place of running=False if the above line doesn't work.
This while loop is the starting of gameloop. The contents of the gameloop should be inside it.
Don't call the gameloop() function inside the while loop
Perhaps use sys.exit to stop the program.
Try:
import sys
import pygame
while 1:
#code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
In your game loop, you should always keep the loop running at one level. In your code, the respawn actually freezes the current level and reruns the game at a lower level. This is why several quit commands are required to exit the game.
When the player respawns, reset the game variables, then continue the game loop.
Update your code similar to this:
if isKill: # game is over
pygame.mixer.music.stop()
gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
rect = gameover.get_rect()
rect.center = screen.get_rect().center
screen.blit(gameover, rect)
if event.type == KEYDOWN:
if event.key == K_r:
#gameloop() # remove this
dospawn() # initialize\reset game variables here (can use same function at game start)
isKill = False # start new game
continue # skip rest of game process

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.

Key press is not being recognised by python's 'pygame.key.get_pressed()' module

I am trying to create a function where if a key is pressed, variables are changed. This will be put into a class that moves a sprite on a screen. The while loop is broken when the key is released. However, nothing happens. The while loop is running and I get no error. Does anyone know why this might be happening? I am not sure if I am using the function pygame.key.get_pressed() correctly.
import pygame
from pygame.locals import *
def move():
for event in pygame.event.get():
if event.type == QUIT:
pygame.QUIT()
sys.exit()
while True:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("something happens")
#runs this, but when up arrow key is pressed does nothing
if event.type == KEYUP:
False
screen = pygame.display.set_mode((512,384))
move()
pygame.display.update()
You can do something like this:
def move():
for event in pygame.event.get():
if event.type == QUIT:
pygame.QUIT()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
print("up pressed")
# etc.
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
print("up released")
# etc.
For more key names you can go to the Pygame Key Docs
get_pressed() returns list with information about pressed keys but this list is updated by pygame.event.get() and other event functions so you have to execute pygame.event.get() all the time. And this is why we do it in while-loop
import pygame
pygame.init()
screen = pygame.display.set_mode((512,384))
while True:
# get events and (somewhere in background) update list
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# get current list.
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("UP")

UnboundLocalError: pygame music play and stop not working (on keydown)

I'm trying to play and stop a music in my main page.
It's kind of weird.
From my code,
if the user press "m", suppose, the music should be off.
However, the music didn't off. It continue
UnboundLocalError: local variable 'music_playing' referenced before assignment
Can someone help me with my code?
pickUpSound = pygame.mixer.music.load('test.mp3')
pygame.mixer.music.play(-1)
music_playing = True
def mainMenu():
main = pygame.image.load('menu.jpg')
screen.blit(main,(0,0))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == KEYDOWN:
if event.key == ord('m'):
if music_playing:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1)
music_playing = not music_playing
As it is written, event.type should be simultaneously equal to KEYDOWN and pygame.K_KP_ENTERat the same time. The second should be event.key instead of event.type.
if event.key == pygame.K_KP_ENTER:
EDIT
There seems to be something wrong with the "keypad enter" key, I commented the problematic line (maybe try with another key, for example, I used K_a, and was able to start/stop by pressing "a")
import pygame
def mainMenu():
pygame.display.init()
pygame.display.set_mode([128,128])
screen = pygame.display.get_surface()
#
pygame.mixer.init()
pickUpSound = pygame.mixer.music.load('test.mp3')
pygame.mixer.music.play(-1)
music_playing = True
#
main = pygame.image.load('menu.jpg')
screen.blit(main,(0,0))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
#if event.key == pygame.K_KP_ENTER:
if music_playing:
pygame.mixer.music.stop()
print "stopping"
else:
pygame.mixer.music.play(-1)
print "playing"
music_playing = not music_playing
mainMenu()
n.b. When running this code, I see the messages "playing" and "stopping" each time I press any key.
With if event.key == pygame.K_a: the music should start/stop by pressing "a".

Categories

Resources