Keyboard Commands in PyGame

Question:

I have made a test code to try and solve this problem. I cannot figure it out. The test code takes in keyboard commands 1,2,3 into pygame and prints out whichever key was pressed into the console. I wrote the code with classes and stuff because it will later go into a larger code. My desire is to instead of pressing down on a key and having it print, to load a list of keyboard commands into the program. Then, press enter, and have pygame intake each keyboard command.

Current code, press 1 and ‘pressed key 1’ will be printed to console:

import pygame
from pygame.locals import *

class Test():
    def __init__(self):
        pass
    def mainloop(self): #here is where keys are selected

        rot_slice_map = {K_1: 'pressed key 1', K_2: 'pressed key 2', K_3: 'pressed key 3'}

        while True:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == KEYDOWN:
                    if event.key in rot_slice_map:
                        print(rot_slice_map[event.key])

def main():

    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    New = Test()
    New.mainloop()

if __name__ == '__main__':
    main()
    pygame.quit()
    quit()

Desired code:

take in a list of keyboard commands in the form of [K_1,K_2,K_3], press enter, and have the console print ‘pressed key 1’, ‘pressed key 2’, and each print in the console should be individual, like you are having the code press the keys for you.

Asked By: BH10001

||

Answers:

Here is an example that draws what you type on the screen, pressing Enter will clear the line. Pressing Esc will simulate typing the sample string.

import string
import pygame

# create list of events to push into the queue
sim_events = []
sample = "ABCDEFGH12345678987654321"
for c in sample:
    key_down = pygame.event.Event(pygame.KEYDOWN, {"unicode": c, "key": ord(c)})
    key_up = pygame.event.Event(pygame.KEYUP, {"unicode": c, "key": ord(c)})
    sim_events.append(key_down)
    sim_events.append(key_up)

pygame.init()
screen = pygame.display.set_mode((800, 400))
buffer = ""
font = pygame.font.SysFont(None, 66)
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            print(f"Key {pygame.key.name(event.key)} pressed")
            # filter printable digits
            if event.unicode and event.unicode in string.printable:
                buffer += event.unicode
            if event.key == pygame.K_RETURN:
                buffer = ""
            elif event.key == pygame.K_ESCAPE:
                for evt in sim_events:
                    pygame.event.post(evt)
    ## clear the screen
    screen.fill("black")
    ## render the text
    text = font.render(buffer, True, "white", "black")
    text_rect = text.get_rect()
    text_rect.center = screen.get_rect().center
    ## draw the text
    screen.blit(text, text_rect)
    ## update the display
    pygame.display.update()
    ## Limit FPS
    clock.tick(60)
pygame.quit()

The name of the key pressed is also printed to the console.

Answered By: import random
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.