You'rYour problem is nothing related to Pygame. It's It's about Python.
It mean'smeans when you press a key , an event is sent to this function., which it's type is : pygame.KEYDOWN
. And when Youyou release that key, another event is being sent :
pygame.KEYUP.
Note that when Youyou are Holdingholding a specific key, Nono event is being sent to pygame.event.get().
So, basically, all Youyou need to do is to track down held-down keys using pygame.KEYDOWN and pygame.KEYUP.
Method 1 , Creating a medium List:
Method 1: creating a medium list
InWith this method, whenever a key is pressed You, you append it to a Listlist. And whenever YouWhenever you release that key , Youyou remove it from the list. AndThen, all Youyou need to do is to check that Listlist in you'ryour game loop.
Use this if Youyou want to track down many held keys.
heldKeys=[]
def getEvents():
global heldKeys
for i in pg.event.get():
if i.event==pygame.KEYDOWN:#Track down key presses here
if i.key==pygame.K_DOWN:
heldKeys.append('Down')
elif i.event==pygame.KEYUP:#Track down key releases here
if i.key==pygame.K_DOWN:
heldKeys.remove('Down')
def checkHeldKeys():#use this in you'r game loop to move you'r character
global heroY;
for i in heldKeys:
if 'Down' in heldKeys:
heroY+=10;
Method 2 , Creating a medium boolean variable:
Method 2: creating a medium boolean variable
In here, all You need is a boolean.
Whenever the pygame.KEYDOWN signal is sent , set this boolean to True:
whenever the pygame.KEYUP signal is sent , set this boolean to False
- Whenever the
pygame.KEYDOWNsignal is sent, set this boolean toTrue. - whenever the
pygame.KEYUPsignal is sent, set this boolean toFalse.
Use this method Onlyonly if Youyou need to check 1 or 2 held keys.
isMoving=False
def getEvents():
global heldKeys
for i in pg.event.get():
if i.event==pygame.KEYDOWN:#Track down key presses here
if i.key==pygame.K_DOWN:
isMoving=True
elif i.event==pygame.KEYUP:#Track down key releases here
if i.key==pygame.K_DOWN:
isMoving=False
def checkIsMoving():#use this in you'r game loop to move you'r character
global heroY;
if isMoving==True:
heroY+=10
```