Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

python - How do you use msvcrt.getch to extract and use input?

I need to create a program/game in python where the user quickly enters 2 keys such as the z or x keys and this makes their character move forward everytime they press it in the right order. I've done a lot of research and decided that I should use msvcrt.getch() to recieve the input, but whenever I try it, it stores the input as a byte which I cannot use, I am relatively new to programming and could use some help explaining the function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to decode the returned value to a str object:

msvcrt.getch().decode('ASCII')

would interpret the byte as a ASCII codepoint, for example. You may need to use a different encoding depending on the keyboard layout and locale, but the msvcrt.getch() API specifically only deals with ASCII characters according to the documentation:

The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible.

You probably want to use msvcrt.getwch() instead to get Unicode values directly; the method supports more than just ASCII codepoints as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...