Working with the Keyboard

Direct via the Command line.

Type or paste these two lines of code into the command line.

keyboardon [print keyboardvalue]
setfocus [MSWLogo screen]


This will now print the numerical value of most of the keys that you press. Note the values of the keys that you want to use to control a game.

To turn the keyboard off type this:

keyboardoff

A Keyboard Reading Procedure

This procedure returns the value of the last key pressed.

to keyread
keyboardon [make "keyval keyboardvalue]
setfocus [MSWLogo screen]
output :keyval
keyboardoff
setfocus [MSWLogo commander]
end

Test it with this command line code:

make "keyval 0 repeat 30 [print keyread wait 60]

Procedure to move a square across the screen.

to movesq
make "xInd 0
make "retval 0
do.until [
make "retval keyread
if :retval>0 [
if :retval=97 [
make "xInd :xInd-1 ]
if :retval=115 [
make "xInd :xInd+1 ]]
if :xInd>5 [make "xInd 5]
if :xInd<-5 [make "xInd -5]
cs
pu setxy :xInd*50 0 pd
repeat 4 [fd 50 rt 90]
make "retval 0
wait 60
][:retval=27]
end

  1. Set up a variable xInd for the x Index.
  2. Set up a variable retval for the returned keyboard value.
  3. Start a do.until loop which keeps going until the esc key is pressed.
  4. You must make sure that do.until loops have a possible exit condition!
  5. Find out which key was pressed last.
  6. If the key was a, value 97, then subtract 1 from xInd.
  7. If the key was s, value 115, then add 1 to xInd.
  8. All other keys stop the square moving.
  9. Make sure that the square doesn't keep going off the edge of the board.
  10. Lift the pen and move the turtle to the correct position.
  11. Put the pen down and draw a square.
  12. Wait 1 second.
  13. Repeat the loop.

Last updated 23rd February 2010