pygame detect which key is pressed - string

I'm working on a scoreboard in a game I am creating and I know how to check if a key is pressed, but is there a way to check WHICH key is pressed, make a varibale that key and then add it to a string?
EDIT: Ok, incase I was unclear: I know that I can check if buttons like h or t can be pressed, but I want a way to just instantly press a button and add that to a string, and I don't want to build an event function for every letter in the alphabet.

if event.type == pygame.KEYDOWN :
print(event.key)
You can transform the given number into ascii with :
pygame.key.name(event.key)

If you have registered a callback to detect when a key has been pressed, UNQUESTIONABLY the identity of the key will be included in the structure passed to the callback's service routine.
Whether that offers the "keyboard code" as well as the plain-Jane ASCII value of the key I cannot tell you.

If you want simple textinput (for example if the user should enter their name for the highscore), take a look at EzText library.
Generally speaking, you can check which key was pressed in two ways.
If you use the event queue, you can check the event.key against the pygame key codes:
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print("spacebar was pressed")
if event.key == pygame.K_q:
done = True
pygame.quit()
All keycodes are listed in the documentation. This will fire one event for every keypress, regardless of how long a single key is being held down.
Alternatively, you can use state checking:
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
state = pygame.key.get_pressed()
if state[pygame.K_SPACE]:
print("spacebar was pressed")
if state[pygame.K_q]:
done = True
pygame.quit()
Notice that this will fire many events if the key is being held down for longer. It may also miss key presses if the key is being pressed and released at a time when your program is busy doing something other than checking for key presses.

A bit late, but I think this is it:
import pygame
pygame.init()
# set screen size
screen = pygame.display.set_mode((100, 100))
# set loop flag
done = False
while not done:
# check events
for event in pygame.event.get():
# end if X was pressed
if event.type == pygame.QUIT:
done = True
# check if event was a key being pressed down
if event.type == pygame.KEYDOWN:
# end if Esc was pressed
if event.key == pygame.K_ESCAPE:
done = True
# unicode returns the char
print(event.scancode, event.key, event.unicode)
# be IDLE friendly
pygame.quit()

What you need is this:
if event.type == pygame.KEYDOWN:
print(event.key, event.unicode)
event.key show the code of an character that are pressed
event.unicode show the character that are preseed
Result would be this:
event.key: 97, event.unicode: a
event.key: 98, event.unicode: b
event.key: 99, event.unicode: c
event.key: 100, event.unicode: d
event.key: 101, event.unicode: e
event.key: 102, event.unicode: f

Related

PyGame. Second composition in modul "mixer.music. doesnt playing, but first plays normally [duplicate]

I tried to use python to display image:
import pygame
win = pygame.display.set_mode((500, 500))
DisplayImage("Prologue.jpg", win)
And when it runs, nothing happened. It also happened for
DisplayImage("Streets.jpg", win)
However, when I tried the exact same thing later on in the code, it ran perfectly.
I checked, the picture was in the same folder as the .py file, and I didn't type the name wrong.
The function is:
def DisplayImage(imageName, screen):
screen.fill((0, 0, 0))
Image = pygame.image.load(imageName).convert()
screen_rect = screen.get_rect()
Image_rect = Image.get_rect().fit(screen_rect)
Image = pygame.transform.scale(Image, Image_rect.size)
screen.blit(Image, [0, 0])
pygame.display.update()
Update:
I commented out all of the lines and copy and pasted that line out so it's the only line that runs. It runs perfectly.
Update 2:
Found the issue. The reason it doesn't work was that the pygame window was "not responding". I don't know what caused it to not respond, but in one of the test runs I didn't make it show "not responding", and the images were loaded fine. The "not responding" always shows up when I type in my player name, and the function looks like this:
def createName():
playerName = input("Enter the player name\n")
desiredName = input("Is "+playerName+" the desired name?[1]Yes/[2]No\n")
if desiredName == "1":
return playerName
elif desiredName == "2":
playerName = createName()
Sometimes when I type the player name nothing happens, and the letters only show up after a while. If this happens, the pygame window is bound to not respond.
You cannot use input in the application loop. input waits for an input. While the system is waiting for input, the application loop will halt and the game will not respond.
Use the KEYDOWN event instead of input:
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_1:
# [...]
if pygame.key == pygame.K_2:
# [...]
Another option is to get the input in a separate thread.
Minimal example:
import pygame
import threading
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
color = "red"
def get_input():
global color
color = input('enter color (e.g. blue): ')
input_thread = threading.Thread(target=get_input)
input_thread.start()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, color, window_center, 100)
pygame.display.flip()
pygame.quit()
exit()

Can't import any pygame functions (E1101)

When I run the following code, a white screen appears and then quickly disappears. I installed pygame on the VSCode terminal with pip3 (I am on mac) and now that I finally got it to import pygame, I get multiple errors for every function called such as "clock" or "pygame.KEYDOWN". They say "Module 'pygame' has no 'KEYDOWN' member" [E1101]. I also get an error with the "init" member.
I've seen other posts that tell me to copy and paste something into the json settings, but when I tried that I got even more errors.
#Game
#By Robert Smith
#Initialize python
import pygame
pygame.init()
#Set the screen
screen = pygame.display.set_mode((640, 480))
background = pygame.Surface(screen.get_size())
background.fill((255,255,255))
background = background.convert()
screen.blit(background, (0 , 0))
#Make the window exitable
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop == False #close the window
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
#Set the framerate
milliseconds = clock.tick(60)#DO NOT GO FASTER THAN THIS FRAMERATE
Try this:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop == False #close the window
elif event.type == keys[pygame.K_DOWN]:
if event.key == keys[pygame.K_ESCAPE]:
mainloop = False
And this:
milliseconds = pygame.time.Clock.tick(60)

How to use keyboard in pygame?

I tried the simple script below, but I get no response. Maybe I don't understand what pygame is capable of doing. I simply want to assign a certain function to a certain key. Like if I press the letter 'h' I want "Bye" to print on the screen or if I press 'g' then play a certain song. And so on and so on...
import pygame
from pygame.locals import *
pygame.init()
print K_h #It prints 104
while True:
for event in pygame.event.get():
if event.type==KEYDOWN:
if event.key==K_h:
print "Bye" #Nothing is printed when I press h key
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480))
clock = pygame.time.Clock()
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == KEYDOWN:
if event.key == K_h:
print "bye"
for what ever reason for me atleast it seems the event command wouldn't work with out the use of a screen even if it has no purpose this will get you the results you want.

Is there a way in pygame to make a programme pause when it's minimized?

I was playing Terraria the other day and in a new update they make the game pause when it's minimized. Obviously it's written in a different programme to python, but I was wondering if it was possible to replicate the effects.
You can use pygame.display.get_active() to check if window is minimized.
In example you can press SPACE to minimize window.
import pygame
import pygame.locals
pygame.init()
screen = pygame.display.set_mode((800,600))
count = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
pygame.display.iconify()
if pygame.display.get_active():
print count
count +=1
else:
print "minimized"
pygame.quit()
Or you can use pygame.ACTIVEEVENT to get information about more events - like minimize, mouse out of the window, etc.
import pygame
import pygame.locals
pygame.init()
screen = pygame.display.set_mode((800,600))
count = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
pygame.display.iconify()
elif event.type == pygame.ACTIVEEVENT:
print 'state:', event.state, '| gain:', event.gain,
if event.state == 1:
if event.gain == 0:
print "| mouse out",
elif event.gain == 1:
print "| mouse in",
elif event.state == 2:
if event.gain == 0:
print "| titlebar pressed",
elif event.gain == 1:
print "| titlebar unpressed",
elif event.state == 6:
if event.gain == 0:
print "| window minimized",
elif event.state == 4:
if event.gain == 1:
print "| window normal",
print
pygame.quit()
Both method work correctly only if pygame.event.get() was executed.
You can use the pygame.APPACTIVE event. From the documentation for the pygame.display.iconify:
Then the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shutdown. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus [This is when the window is minimized]. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn.
Look at the second example in furas' answer below, but don't use the polling approach of the first example for something like this, you don't want to spend time every frame trying to check if the window has been minimized.

Pygame waiting the user to keypress a key

I am searching a method, where the program stops and waiting for a spesific key to be pressed by the user. May I can implement this one with a while loop? I need the best algorithm, if there exist a build-in function of waiting, to avoid the loop.
I found several information on the official website of pygame, but nothing help.
Here is a testing algorithms but won't work:
key = "f"
while key != "K_f":
key = pygame.key.get_pressed()
if key[Keys.K_f]:
do something...
If you are waiting for a key to be pressed you can use the event.wait() function. This is useful, because it does not require a-lot of processing.
import pygame
from pygame.locals import *
pygame.event.clear()
while True:
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key = K_f:
do something...
Note that event.wait() waits for events to appear in the event cache, the event cache should be cleared first.
pygame.event documentation
You could do it with a while loop and an event queue:
from pygame.locals import *
def wait():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN and event.key == K_f:
return

Resources