Capturing keystrokes for a game (python)

Does anyone know how to record keystrokes for a game (i.e. use the keyboard to navigate a simple ascii based game where 8 = up, 2 = down, 4 on the left, etc ... and when clicking on no return required, single keystroke is target.)? I found this code, which looks like a good idea, but is over my head. Adding comments or sending me an article on the subject, etc. It would be a great help. I know a lot of people are asking this question. Thank you in advance?

        from msvcrt import kbhit
    except ImportError:
        import termios, fcntl, sys, os
        def kbhit():
            fd = sys.stdin.fileno()
            oldterm = termios.tcgetattr(fd)
            newattr = termios.tcgetattr(fd)
            newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
            termios.tcsetattr(fd, termios.TCSANOW, newattr)
            oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
                while True:
                        c =
                        return True
                    except IOError:
                        return False
                termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
                fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)



source to share

2 answers

Pygame is a good place to start, the documentation is really good. This is how you can get the keyboard output:

import pygame    
screen = pygame.display.set_mode((100, 100))
while 1:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key <= 256:
            print event.key, chr(event.key)


You have to initialize pygame and create an active window for this. I don't think there is any way to avoid hitting the "return" key without doing something along those lines.

Building something in Pygame is actually a pretty good way to get started learning programming as there are tons of examples on the site.



Okay, if you want to understand how to control this directly, start with a good study of the Linux (or OS X) man pages for termios

, fcntl

and stty

. That's a lot, but you'll see what all these flags are for.

Typically your keyboard input is line buffered: the terminal driver builds it up until you hit return. The flag ~termios.ICANON

is the one that is responsible for turning off line buffering, so you can immediately see what the user is typing.

On the other hand, if you want your program to only respond when the user presses a key, you do NOT want to os.O_NONBLOCK

: this means that your program will not block when reading from the keyboard, but your reads will return an empty string. This is suitable for live action games where everything happens regardless of whether the user is responsive.



All Articles