Keyboard input

From TRCCompSci - AQA Computer Science
Revision as of 07:27, 6 July 2018 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Within the game loop of your code, we can firstly get the status of the keyboard and store it in a variable called user_input. We can then check this for certain keys:

user_input = pygame.key.get_pressed()
    
if(user_input[pygame.K_UP]):
    Y=Y-1
elif(user_input[pygame.K_DOWN]):
    Y=Y+1
if(user_input[pygame.K_LEFT]):
    X=X-1
elif(user_input[pygame.K_RIGHT]):
    X=X+1

If these variables are used to draw something to the screen, then the object will move around the screen. The benefit of using this method is that if the player continues to hold a key the key will continue to be registered by get_pressed(). However the next method relies on events, and the event will only register on KEYDOWN (press) or KEYUP (release) you will need to have extra logic to determine if it is been held.

The alternative way of handling input is within the pygame.events:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); #sys.exit() if sys is imported
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                X+X-1
            elif event.key == pygame.K_RIGHT:
                X=X+1
            if event.key == pygame.K_UP:
                Y=Y-1
            elif event.key == pygame.K_DOWN:
                Y=Y+1

However to allow the player to continue to hold a key you will need to create some boolean variables and set these on KEYDOWN or KEYUP:

LEFTHELD = False
RIGHTHELD = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); #sys.exit() if sys is imported
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                LEFTHELD = True
            elif event.key == pygame.K_RIGHT:
                RIGHTHELD = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                LEFTHELD = False
            elif event.key == pygame.K_RIGHT:
                RIGHTHELD = True

     if LEFTHELD:
         X = X - 1
     if RIGHTHELD:
         X = X + 1