[Tutor] Tutor Digest, Vol 195, Issue 23

Alan Gauld alan.gauld at yahoo.co.uk
Sat May 16 04:47:09 EDT 2020


On 16/05/2020 02:05, Boi0 wrote:
> I'm working on a text-based RPG, I am on a Windows, and I want the
> inventory to open (by pressing i) without pressing enter.

OK, Thanks. They simplest way to read keystrokes in Windows is using the
msvcrt module which includes the getch() function. But it is quite
tricky to use since it literally just reads the keyboard at the point
you call it. So you usually have to create a while loop to wait for a
keypress. One way to do that is to create a background thread that
monitors for keystrokes and then sets a flag somewhere that the main
program can check intermittently. (I don't know if you are familiar with
threads, they can be quite tricky, but this usage is one of the simplest
provided you ensure only the thread ever writes to the flag and only the
main program reads it.)

Another option which is probably better for your case but will require a
major redesign of your code is to use the curses library. Unfortunately
curses does not ship with Windows Python so you need to install the
windows version from PyPi.
https://pypi.org/project/windows-curses/

But curses provides three things you can use - a getch() function which
blocks until a key is pressed (and that includes mouse clicks!) and the
ability to create small subwindows on your text terminal. Into these you
can insert text - like your inventory or a menu, say. Also it lets you
control colour and style(bold etc) of text. Again the learning curve is
relatively steep and you have to use curses for your whole program you
can't mix n match with normal print/input etc.

You can see both approaches at work in the event-driven programming
topic of my tutorial(see .sig below)

Finally there are another couple of modules for terminal keyboard
handling in Windows, but they are very similar to the above
approaches. Fred Lundh's Console module:
http://effbot.org/zone/console-index.htm

and the ANSI library for drawing boxes and setting colors:
https://pypi.org/project/easy-ansi/
You still need msvcrt for input  but its easier than curses
for drawing boxes(aka windows) etc.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list