pygame - Key pressed

26,102

Solution 1

A window needs to be created to receive key presses, the following works.

import pygame
import sys
pygame.init()

pygame.display.set_mode((100, 100))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                print('Forward')
            elif event.key == pygame.K_s:
                print('Backward')

Solution 2

This is what seems to me the most simple and understandable way to do it:

import pygame
pygame.init()
pygame.display.set_mode((300, 300))
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                print('Forward')
            elif event.key == pygame.K_s:
                print('Backward')

Instead of using the sys.exit() method I prefer to just use pygame.quit()

Solution 3

it is no good to ask the gamer to keep hitting w to get the response. If you want to read the "pressed" state. You could consider the followings:

  from pygame import *
    import time
    flag = False # The flag is essential.
    DONE = False
    screen = display.set_mode((500,500))   # 1180, 216
    count=0
    while not DONE:
        event.pump() # process event queue
        keys = key.get_pressed() # It gets the states of all keyboard keys.
        #print("%d"%count,keys)
        count+=1
        if keys[ord('w')]: # And if the key is K_DOWN:
            print("%d w down"%count)
        if keys[ord('s')]: # And if the key is K_DOWN:
            print("%d s down"%count)
        time.sleep(0.1)
Share:
26,102
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I am kinda stuck with a supposed to be simple code to check if the user has pressed "w" or "s".

    Below you can see my code:

    import pygame
    pygame.init()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
                print('Forward')
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                print('Backward')  
    

    Am I forgetting something here?

    Thanks!