Posts: 18
Joined: Sat Apr 13, 2013 7:00 pm

Keyboard Scanning

Sat Jun 29, 2013 1:15 pm

Hello everybody.
I have typed in 'Bat and Ball' from the first MagPi and it works well. As a programming exercise which I know will be useful to me in the future, I decided to convert it to keyboard control. So far I have failed. All the methods I have come across so far seem to be incredibly over-involved and very tedious; some of them even rely upon emptying and then restoring an event buffer! The worst effect is the amount of time some of these methods must take.

What I want is something similar to the commands that are available in BBC BASIC, so GET, GET$, INKEY, and INKEY$ would be good starting points. But the one I really want for gaming is INKEY with a negative argument, e.g. INKEY(-66), see Archimedes BBC BASIC GUIDE page 63, sub-heading 'Scanning the keyboard', and the old BBC USER GUIDE page 273.

I don't want anything more complicated than that. Having been used to such an obvious solution to something which should not really be a problem anyway since the early 80's I don't intend to go back to anything less!

I will only be happy when I can control Bat and Ball using the Z and X keys by commenting-out the mouse control part of it and adding no more than a few extra lines of code. And none of those extra lines must start with the word 'import', ok?

User avatar
Posts: 2591
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Keyboard Scanning

Tue Jul 02, 2013 11:04 am

In the bad old days program designers tried to include all the functionality that they thought users would ever need. Subsequently it was realised that a much better approach was to have less in the core and 'import' things as and when they were needed.

User avatar
Forum Moderator
Forum Moderator
Posts: 1665
Joined: Fri Oct 14, 2011 8:06 pm
Location: The Netherlands
Contact: Twitter

Re: Keyboard Scanning

Tue Jul 02, 2013 11:47 am

Pygame is always a good system for this;

Code: Select all

from pygame.locals import *

pygame.display.set_caption("My Game")
surface = pygame.display.set_mode((900, 200), 0, 32)

While True:
	e = pygame.event.poll()
	if e.type == JOYAXISMOTION:
		print e
	elif e.type == JOYBUTTONDOWN:
		print e
	elif e.type == KEYDOWN:
		print e
	elif e.type == KEYUP:
		print e
	elif e.type == QUIT:
		print e
		print e
More info here;

You can detect when a keydown event occurs, set a flag which is to start moving the bat in that direction and unset the flag when the corresponding keyup event occurs.

Return to “Python”