windows - Python method for reading keypress? -
i'm new python, , made game , menu in python. question is, using (raw_)input() requires me press enter after every keypress, i'd make pressing downarrow instantly select next menuitem, or move down in game. @ moment, requires me type "down" , hit enter. did quite alot of research, prefer not download huge modules (fe. pygame) achieve single keydown() method. there easier ways, couldn't find?
edit: found out msvcrt.getch()
trick. it's not keydown(), works. however, i'm not sure how use either, seems quite weird, here? got @ momemt:
from msvcrt import getch while true: key = getch() print(key)
however, keeps giving me these nonsense bytes, example, downarrow this:
b'\xe0' b'p'
and have no idea how use them, i've tried compare chr() , use ord() can't comparisons. i'm trying this:
from msvcrt import getch while true: key = getch() if key == escape: break elif key == downarrow: movedown() elif key == 'a': ...
and on... help?
figured out testing stuff myself. couldn't find topics tho, i'll leave solution here. might not only, or best solution, works purposes (within getch's limits), , better nothing.
note: proper keydown()
recognize keys , actual key presses, still valued.
solution: using ord()
-function first turn getch()
integer (i guess they're virtual key codes, not sure) works fine, , comparing result actual number representing wanted key. also, if needed to, add chr()
around number returned, convert character. however, i'm using down arrow, esc, etc. converting character stupid. here's final code:
from msvcrt import getch while true: key = ord(getch()) if key == 27: #esc break elif key == 13: #enter select() elif key == 224: #special keys (arrows, f keys, ins, del, etc.) key = ord(getch()) if key == 80: #down arrow movedown() elif key == 72: #up arrow moveup()
also if else needs to, can find out key codes google, or using python , pressing the key:
from msvcrt import getch while true: print(ord(getch()))
Comments
Post a Comment