Keys in Pygame instead of numbers in the actual key - python

I want to make a menu point where I can change the hotkeys and also show which are used, but when I put them into a variable the output is in numbers. I had the idee to set the varibles when pressing the key as following:
if event.key == pygame.K_d:
varibleright = d
This I would have to do for all the keys is there a better way or should I just do it for all the keys?

The KEYDOWN and KEYUP event provides the unicode attribute (see pygame.event module). The unicode attribute provides the Unicode representation of the keyboard input. A user friendly name of a key can be get by pygame.key.name():
if event.type == pygame.KEYDOWN:
print(event.unicode)
print(pygame.key.name(event.key))
You can use the functions to compare the key with a unicode character or string:
if event.type == pygame.KEYDOWN:
if event.unicode == 'a':
print('a')
if event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == 'd':
print('d')
if pygame.key.name(event.key) == 'right':
print('right')
This allows you to define variables for the keys
key_up = 'up'
key_down = 'down'
if event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == key_up:
print('move up')
if pygame.key.name(event.key) == key_down:
print('move down')
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
rect = pygame.Rect(190, 190, 20, 20)
key_left = 'left'
key_right = 'right'
key_up = 'up'
key_down = 'down'
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == key_left:
rect.x -= 20
if pygame.key.name(event.key) == key_right:
rect.x += 20
if pygame.key.name(event.key) == key_up:
rect.y -= 20
if pygame.key.name(event.key) == key_down:
rect.y += 20
window.fill(0)
pygame.draw.rect(window, 'red', rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()

Related

key.event confusion // pygame.K_a doesn't work

I'm new in this python industry, when i press 'd' my character should go right, but this isn t hapening, same thing to the 'a'. When I change K_a and K_d with K_LEFT and K_RIGHT it works, my character is moving well, but if I wanna make the character move with 'a' and 'd', it doesn't work, what's wrong with my code:
import pygame
import sys
import os
pygame.init()
screen = pygame.display.set_mode((1366,768))
pygame.display.set_caption("Adventure in the Woods")
icon = pygame.image.load('tree.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('ninja.png')
playerX = 100
playerY = 650
velocity = 0.1
run = True
while run:
screen.fill( (9, 66, 2) )
screen.blit(playerImg, (playerX,playerY) )
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity
pygame.display.update()
Problem Insight
The problem lies in the scope of your if event.type == pygame.KEYDOWN: ... as it should be within the for-loop for event in pygame.event.get(): ... :
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: #<-------------- From here
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity #<-------------- to here
Solution
This can be fixed by indenting the code block starting from if event.type == pygame.KEYDOWN: ..., like so:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: #<-------------- Now inside the for-loop
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity
Other Remarks
To be more familiar with python code structures and styles, review some of the fundamental syntaxes like Indentation by visiting the style guide # https://www.python.org/dev/peps/pep-0008/
Cheers!

pygame not detecting keypresses

I've been trying to get pygame to detect keypresses so later on I can move a character around on the screen. I'm new to coding so I might just be missing something simple, but I can't figure out what's wrong with the code, should I switch to pygame.key.get_pressed() or something instead? thanks in advance.
running = True
while running:
screen.fill((0,0,0))
# set background
screen.blit(background, (0,0))
player(playerX, playerY)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# detecting key presses
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
print("left")
if event.type == pygame.K_RIGHT:
print("right")
if event.type == pygame.K_UP:
print("up")
if event.type == pygame.KEYUP:
if event.type == pygame.K_LEFT or event.type == pygame.K_RIGHT:
print("stop")
pygame.display.update()
It is a matter of Indentation. You must evaluate the events in the event loop instead of the application loop.
If you want to determine if a certain key is pressed, the you've to verify if the event type is pygame.KEYDOWN (or pygame.KEYUP for button release) and if the .key attribute of the event is equal the key enumerator.
running = True
while running:
screen.fill((0,0,0))
# set background
screen.blit(background, (0,0))
player(playerX, playerY)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
# detecting key presses
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT: #<-- "key" instead of "type"
print("left")
if event.key == pygame.K_RIGHT: #<-- "key" instead of "type"
print("right")
if event.key == pygame.K_UP: #<-- "key" instead of "type"
print("up")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: #<-- "key" instead of "type"
print("stop")
#-->|
# INDENTATION
However, I recommend to use pygame.key.get_pressed() instead of the KEYDOWN event.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
clock = pygame.time.Clock()
velocity = 5
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * velocity
playerY += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * velocity
screen.blit(background, (0,0))
player(playerX, playerY)
pygame.display.update()
You need to indent this part of your code to be in the for loop:
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
print("left")
if event.type == pygame.K_RIGHT:
print("right")
if event.type == pygame.K_UP:
print("up")
if event.type == pygame.KEYUP:
if event.type == pygame.K_LEFT or event.type == pygame.K_RIGHT:
print("stop")
pygame.display.update()
Otherwise, the event will always only be the last event from the pygame.event.get() list.
So basically, from
running = True
while running:
screen.fill((0,0,0))
# set background
screen.blit(background, (0,0))
player(playerX, playerY)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# detecting key presses
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
print("left")
if event.type == pygame.K_RIGHT:
print("right")
if event.type == pygame.K_UP:
print("up")
if event.type == pygame.KEYUP:
if event.type == pygame.K_LEFT or event.type == pygame.K_RIGHT:
print("stop")
pygame.display.update()
to:
running = True
while running:
screen.fill((0,0,0))
# set background
screen.blit(background, (0,0))
player(playerX, playerY)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("left")
if event.key == pygame.K_RIGHT:
print("right")
if event.key == pygame.K_UP:
print("up")
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
print("stop")
pygame.display.update()
(Notice the event.keys I replaced part of your event.types with.)

Why wont the MOD_SHIFT event key work in PYGAME Mac

I'm trying to build a little python program using pygame that detects when the shift key is pressed but it isn't working it isn't printing the debug print that I put in there here is my code
while running:
screen.fill((0, 0, 0))
x, y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
rectangle = "green"
if event.type == pygame.MOUSEBUTTONUP:
rectangle = "red"
if event.type == pygame.KEYDOWN:
if event.key == pygame.KMOD_SHIFT:
modshift = "down"
print("debug shift")
if event.key == pygame.KMOD_CTRL:
modctrl = "down"
if event.type == pygame.KEYUP:
if event.key == pygame.KMOD_SHIFT:
modshift = "up"
Instead of using if event.key == pygame.KMOD_SHIFT: try using:
if event.mod & pygame.KMOD_SHIFT:
The documentation explains it pretty well here: https://www.pygame.org/docs/ref/key.html#key-modifiers-label
The modifier information is contained in the mod attribute of the pygame.KEYDOWN and pygame.KEYUP events. The mod attribute is a bitmask of all the modifier keys that were in a pressed state when the event occurred. The modifier information can be decoded using a bitwise AND (except for KMOD_NONE, which should be compared using equals ==).
Basically, the & operator checks that pygame.KMOD_SHIFT was the button clicked.
Final code would look like:
while running:
screen.fill((0, 0, 0))
x, y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
rectangle = "green"
if event.type == pygame.MOUSEBUTTONUP:
rectangle = "red"
if event.type == pygame.KEYDOWN:
if event.mod & pygame.KMOD_SHIFT:
modshift = "down"
print("debug shift")
if event.mod & pygame.KMOD_CTRL:
modctrl = "down"
if event.type == pygame.KEYUP:
if event.mod & pygame.KMOD_SHIFT:
modshift = "up"

On PyCharm my left key and right key isn't responding

#enable pygame mode
import pygame
pygame.init()
#create screen
screen = pygame.display.set_mode((900,600))
#Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)
#Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500
def player(x, y):
screen.blit(player_icon, (x, y))
#game loop
running = True
while running:
# backround colour RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#If key pressed check wether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("key left pressed")
if event.key == pygame.K_RIGHT:
print("key right pressed")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
print("key stroke has benn released")
#Player change in coordinates
playerX += 0
playerY += 0
player(playerX, playerY)
pygame.display.update()
I have been learning about pygame and game programing using python during this quarantine. I have been doing this by watching a tutorial on youtube. Please don't downgrade me I have tried harder to make my question better last time it was my first question and got 2 downgrades. Thankyou for your time.
It s a matter of Indentation. In your code the pygame.KEYDOWN event is only evaluated in case of event.type == pygame.QUIT. "Move" the pygame.KEYDOWN event handling:
running = True
while running:
# backround colour RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# <--| INDENTATION
#If key pressed check wether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("key left pressed")
if event.key == pygame.K_RIGHT:
print("key right pressed")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
print("key stroke has benn released")

How do you continuously play a note in Pygame?

Python 2.7
Im trying to create a piano-like thing in pygame where when a key is pressed a note plays. My problem is that I can not figure out how to get the note to play forever while the key is held down. I tried to make a while loop but I couldnt figure out how to leave it.
import pygame
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
size = width, height = 800, 400
screen = pygame.display.set_mode((size))
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.KEYUP:
break
elif event.key == pygame.K_i:
pygame.mixer.music.load('file.wav') #A
pygame.mixer.music.play()
elif event.key == pygame.K_o:
pygame.mixer.Sound('file.wav').play() #B
elif event.key == pygame.K_e:
pygame.mixer.Sound('file.wav').play() #C
elif event.key == pygame.K_r:
pygame.mixer.Sound('file.wav').play() #D
elif event.key == pygame.K_t:
pygame.mixer.Sound('file.wav').play() #E
elif event.key == pygame.K_y:
pygame.mixer.Sound('file.wav').play() #F
elif event.key == pygame.K_u:
pygame.mixer.Sound('file.wav').play() #G
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
pygame.mixer.Sound('file.wav').stop()
if keys[pygame.K_DOWN]:
pygame.mixer.Sound('file.wav').play()
While a key is pressed it will continue to play that key but when it isn't pressed anymore it will stop.

Categories

Resources