ICS2O_0405_keyBoardInput

In graphics/GUI programming, you often want to have objects on the screen react to the user pressing a key on the keyboard. For example, you may want the object to move up when the up arrow is pressed, down when the down arrow is pressed, etc.

The first challenge for a program is just to detect when a particular key has been pressed by the user. The Input.getch(char :string(1)) command will retrieve a key that has been depressed. Declare char as type string(1) but only include your variable name in the call to getch. (That's unusual, I'm not sure why this is the case.)

If char is a regular key that is in the alphabet then you can just use an if statement and compare char to a letter like 'a' or 'x'. OTOH, if char is supposed to be something non-alphabetic like the down arrow then you need to compare char to the ordinal value for the down arrow key. [Every key on the keyboard has an ordinal value - a number - associated with it and you can use this.] if ord(char) = 200 then %up arrow key put "Up arrow key pressed!" end if

Here are for the keyboard.

The next challenge is to connect the up arrow key to the behaviour of the object. When the up arrow key is pressed, you want the object to move upwards.

Suppose we have a circle: Draw.FillOval(x_coord, y_coord, x_radius, y_radius, colour : int)

We want the value of its y-coordinate to increase when the up arrow is pressed (so that it will move upwards) so: if ord(char) = 200 then %up arrow key y_coord += 50 % increase the y_coord by 50 pixels end if %and redraw the oval... Draw.FillOval(x_coord, y_coord, x_radius, y_radius, colour)

I've put all this together in