473,624 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Detecting key presses

Ok, I'm pretty new to python, so this might be a stupid question. I'm
trying to write a simple text-based pong clone, and I can't figure out
how to read key presses to move the paddles. I just need something that
does the same thing as getch() and kbhit(). I can't use those because
their windows only, and I'm running Linux.

Someone suggested using curses, but that does crazy things with my
output, and leaves the terminal unusable after the program closes.

Jun 18 '06 #1
4 20701
On 2006-06-18 13:20:06, tylertacky write:
Ok, I'm pretty new to python, so this might be a stupid question. I'm
trying to write a simple text-based pong clone, and I can't figure out
how to read key presses to move the paddles. I just need something that
does the same thing as getch() and kbhit(). I can't use those because
their windows only, and I'm running Linux.

Someone suggested using curses, but that does crazy things with my
output, and leaves the terminal unusable after the program closes.

--
http://mail.python.org/mailman/listinfo/python-list


The python.org site has a faq about getting keystroke.
It uses termios and fcntl modules.
Here's the link:
http://www.python.org/doc/faq/librar...ress-at-a-time

Hope it can help you!
-----
Fan Zhang

Jun 18 '06 #2
ty********@gmai l.com schrieb:
Ok, I'm pretty new to python, so this might be a stupid question. I'm
trying to write a simple text-based pong clone, and I can't figure out
how to read key presses to move the paddles. I just need something that
does the same thing as getch() and kbhit(). I can't use those because
their windows only, and I'm running Linux.

Someone suggested using curses, but that does crazy things with my
output, and leaves the terminal unusable after the program closes.


Maybe using pygame for a graphical version is appealing to you -
additionally, the event-sytem of it will do what you ask for.

Diez
Jun 18 '06 #3
Not a stupid question at all - its something I was looking for, and was
(and still am) surprised not to find a cross platform implementation.
It must be possible - for a short while I dabbled with yabasic and
there the same source code would recognise a keypress in both Windows
and Linux.

My solution was:-

# Await key and return code - dos only
def _keycode_msvcrt (self):
#Loop till key pressed
while 1:
if msvcrt.kbhit():
k=ord(msvcrt.ge tch())
if k==0 or k==224: #Special keys
k=1000+ord(msvc rt.getch()) #return 1000+ 2nd code
pass
break
pass
pass
return k

# Await key and return code - linux only
def _keycode_linux2 (self):
# Loop till key pressed
# Set up keycode list
a=[0,0,0,0,0,0]

# Press a key and populate list
try:
os.system('stty -icanon')
os.system('stty -echo')
a[0]=ord(sys.stdin. read(1))
if a[0]==27:
a[1]=ord(sys.stdin. read(1))
if a[1]==91:
a[2]=ord(sys.stdin. read(1))
if (a[2]>=49 and a[2]<=54) or a[2]==91:
a[3]=ord(sys.stdin. read(1))
if a[3]>=48 and a[3]<=57:
a[4]=ord(sys.stdin. read(1))
finally:
os.system('stty echo')
os.system('stty icanon')

# Decode keypress
if a==[ 10, 0, 0, 0, 0, 0]: k= 13 # Enter
elif a==[ 27, 27, 0, 0, 0, 0]: k= 27 # Esc (double
press)
elif a==[ 27, 91, 91, 65, 0, 0]: k=1059 # F1
elif a==[ 27, 91, 91, 66, 0, 0]: k=1060 # F2
elif a==[ 27, 91, 91, 67, 0, 0]: k=1061 # F3
elif a==[ 27, 91, 91, 68, 0, 0]: k=1062 # F4
elif a==[ 27, 91, 91, 69, 0, 0]: k=1063 # F5
elif a==[ 27, 91, 49, 55, 126, 0]: k=1064 # F6
elif a==[ 27, 91, 49, 56, 126, 0]: k=1065 # F7
elif a==[ 27, 91, 49, 57, 126, 0]: k=1066 # F8
elif a==[ 27, 91, 50, 48, 126, 0]: k=1067 # F9
elif a==[ 27, 91, 50, 49, 126, 0]: k=1068 # F10
elif a==[ 27, 91, 50, 51, 126, 0]: k=1133 # F11
elif a==[ 27, 91, 50, 52, 126, 0]: k=1134 # F12
elif a==[ 27, 91, 50, 126, 0, 0]: k=1082 # Ins
elif a==[ 27, 91, 51, 126, 0, 0]: k=1083 # Del
elif a==[ 27, 91, 49, 126, 0, 0]: k=1071 # Home
elif a==[ 27, 91, 52, 126, 0, 0]: k=1079 # End
elif a==[ 27, 91, 53, 126, 0, 0]: k=1073 # Pg Up
elif a==[ 27, 91, 54, 126, 0, 0]: k=1081 # Pg Dn
elif a==[ 27, 91, 65, 0, 0, 0]: k=1072 # Up
elif a==[ 27, 91, 66, 0, 0, 0]: k=1080 # Down
elif a==[ 27, 91, 68, 0, 0, 0]: k=1075 # Left
elif a==[ 27, 91, 67, 0, 0, 0]: k=1077 # Right
elif a==[127, 0, 0, 0, 0, 0]: k= 8 # Backspace
else: k=a[0] # Ascii code

# Done
return k
# Return key code
def key(self,case=' NONE'):

# Get OS name and call platform specific function
a=sys.platform
if a=='linux2': #Linux (works on Fedora
Core 1 and 3)
k=self._keycode _linux2()
elif a=='win32': #windows
k=self._keycode _msvcrt()
else: #unknown
k=ord(raw_input ())

# Adjust case
if case=='UPPER':
if k>=97 and k<=122:
k=k-32
if case=='LOWER':
if k>=65 and k<=90:
k=k+32

# Done
return k

A bit clumsy, I know (for example it needs a a double press to
recognise the escape key), and I'm not sure I understand why it works,
but for me it was a passable solution.

Peter

Jun 19 '06 #4
Someone suggested using curses, but that does crazy things with my
output, and leaves the terminal unusable after the program closes.


It's very good suggestion but you should use also initscr
and endwin functions.

Regards,
Rob

Jun 19 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
18310
by: Halldór Ísak Gylfason | last post by:
In my application I have an iframe that is empty (and not visible) initially, however when a user presses a button a form is programmatically submitted and the target is set to the IFrame. I want to detect when the frame has been loaded with the result of the form submit. Of course I have tried some event handlers like onload, onactivate, onreadystatechange, but they do not work in this example. They only seem to work, when the "SRC"...
3
14785
by: Dag Sunde | last post by:
Is there a way to detect if the reason an onUnload() handler was called originated from the user explicitly refreshed the page(s)? Ie. pressed "Ctrl-R", "F5" or klicked the refresh button in the toolbar or the context menu? I'm aware that I can not stop a refresh, but the reason I want to know is that I have a hidden frame in an intranet application. This hidden frame is present at all times after
2
5035
by: MackS | last post by:
Hello I am writing a small app to learn how to use the curses module. I would like to know how I can get "composite" key presses, eg, Control+Q. Currently I am looking at the following code snippet: import curses.wrapper def main(stdscr):
1
1239
by: Simon Harvey | last post by:
I'm having a problem with a textbox I'm using. On all the other pages i have, if the user presses the enter key the form submits and moves on to the next page. However with this page if the user presses enter, he/she is directed to the index page of the site - None of the buttons on the page even do that so I havent a clue whats going on! Does anyone have any thoughts as to why this might be happening and any ways to potentially...
1
1211
by: thechaosengine | last post by:
Hi all, I have a master page for my site which contains amongst other things, a text box and a button for perfroming a quick search. This appears on every page on the site. The problem is, when looking at a page with an additional form to be filled in, whenever the user presses return to submit the page, its the quick search button that is doing the submit. It never actually gets far though because
5
6502
by: kh | last post by:
My app filters windows messages because of some custom window functionality I have implemented. Does my window receive a message when the user selects Alt-Tab? If so which message? Many thanks kh
3
7240
by: somaskarthic | last post by:
Hi I am trying to use Javascript in order to detect when a user presses the little 'X' at the top right hand corner of the window or uses File..Close, in order to process some code before hand. If unload event is used in body tag , then each and every time whenever the form unloads the javascript function would fire. But i want to fire that function only when the close button ( X ) in the top right corner is pressed. Can anyone help me...
1
2340
by: Frank Rizzo | last post by:
I'd like to detect a condition when a user presses a predefined keyboard combination. For instance, left shift + right control + 5 on the number pad. I've tried the KeyDown event on the form. But I can't determine which shift (or control) key was pressed (right or left). I've tried e.KeyCode, e.KeyData, e.Modifiers. Am I missing something really basic? Thanks
4
4850
by: almurph | last post by:
Hi everyone, I'm a newbie to javascript. I have written some code to detect when a user presses the down-arrow, up-arrow and enter button. Essentially the user can arrow down or up through a list and the textbox is populated with the option when the user presses the enter button. This is for a VB.NET Web form type project. The problem is that when I press the enter button the entire form get
0
8233
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8170
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8675
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8619
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6108
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.