简体   繁体   中英

Expected output when printing keydown events in pygame

I am following the book "Python Crash Course" by Eric Matthes and am working on exercise 12-4 "Keys". The purpose of this exercise is to test what the print output would be for a blank pygame screen that prints every keydown event. I am trying to make sure that my output is correct and figure out what the output means.

After I execute the file and the blank screen pops up, I enter a variety of keys (letters, numbers, arrows etc.). On the terminal shell, a series of numbers being printed out. For example, if I enter "g", "p", the up arrow and "2", the following numbers get printed out: 103 112 273 50 Is this correct or should I have been seeing something else? What does the output mean? Does each key have a number associated with it?

Here is the code I am using:

import sys

import pygame

def run_game():
    #Initialize game and create a screen object.
    pygame.init()
    screen = pygame.display.set_mode((1200,800))
    pygame.display.set_caption("Keys")
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                print(event.key)
        pygame.display.flip()

run_game()

The short and simple answer is yes; you're seeing the keycode of each key.

Pygame is based on SDL, so to see a list of all keycodes take a look at the SDL docs ( SDLKeycodeLookup ).

The longer is answer is: it's a little more compliated, since there's also the scancode ( SDL_Scancode ), which is platform-specific, but you usually don't have to worry about that.

A more interresting thing to know is that the pygame.KEYDOWN event has a unicode attribute that represents a single character string that is the fully translated character entered.

Yes, each key on your keyboard has a number.

You can see some of these number on this ascii table . (You're apparently printing the decimal code).

You can see a better response if you don't use ".key" in your print command.

For example, pressing "enter" in your code, you see: "13"

Using just print(event) , you see:

<Event(768-KeyDown {'unicode': '', 'key': 13, 'mod': 4096, 'scancode': 40, 'window': None})>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM