Skip to content
← Back to Community
ASCII Lunar Lander Game
Profile icon
nkibre

reproducing a game I wrote 35 years ago (in MS Basic on an Osborne I) in Python.

uses a very simple way of catching unbuffered keyboard input for game controls

Voters
Profile icon
DungeonMaster00
Profile icon
leo-ironkey
Profile icon
nkibre
Comments
hotnewtop
Profile icon
leo-ironkey

Very cool!

Profile icon
PythonAnaconda

How'd you make it immediately detect key presses?? I've been trying to do that for a while now, but I can't figure out how to!

Profile icon
nkibre

Hi @PythonAnaconda yeah that took me a while to figure out! Well, to make a python script immediately react to keypresses (instead of waiting for a newline) was this bit that I put in the main func:

# set stdin to unbuffered so we can get keystrokes immediately old_settings = termios.tcgetattr(sys.stdin.fileno()) tty.setraw(sys.stdin.fileno())

Btw, this works in the Repl.It environment, and in Unix/Linux environments like the WSL terminal, but I kind of remember that you have to do something slightly different to run in a native DOs/Windows/Powershell environment. At some point I stopped caring about that (even though, or maybe because, my day job is at M$!).

Anyway, if you use those two lines or equivalent, your program will react to individual keys, instead of waiting for the user to hit enter. But, if you just do that, it will still just sit there waiting for keys, and do nothing meantime, which isn't how a video game should work. So that's why I made the program fork into two threads. One thread just waits for keystrokes, and the other thread runs the rest of the game. The listener thread communicates keystrokes to the main thread via a global variable. I'm sure there are more sophisticated ways to do that but this works.