Learn to Code in 30 Days: with MiniScript and Mini Micro by Strout Joe

Learn to Code in 30 Days: with MiniScript and Mini Micro by Strout Joe

Author:Strout, Joe [Strout, Joe]
Language: eng
Format: epub
Publisher: MiniScript Press
Published: 2021-09-23T16:00:00+00:00


* * *

1

print "Press any key to stop the count."

2

print "See if you can stop on exactly 50! Get ready..."

3

wait

4

print "GO!"

5

for i in range(1, 100)

6

if key.available then break

7

print i

8

wait 0.05

9

end for

10

key.clear

11

diff = abs(i - 50)

12

print "You stopped " + diff + " away from 50."

13

if diff < 5 then print "Amazing!"

* * *

Reaction test.

Save this program as “reactionTest”, then try it a few times. Notice how we’re checking key.available within the loop, and when one is available (i.e. the user has pressed a key), we break out of the loop. Then we use key.clear to clear out the keyboard buffer. In fact, try taking that out, and see what happens!

The second way to detect key presses without waiting for them is to use key.pressed . This function is quite different from the other key functions we’ve looked at so far. The key.available , key.get , and key.clear functions all deal with the keyboard buffer , the set of printable characters (plus a few editing characters as discovered before) that the user has typed. These can include modified keys like capital letters, $, or π, but they don’t include the modifier keys themselves. Also, when you hold a printable key down, it will be entered into the keyboard buffer multiple times, following the same key-repeat behavior you see when typing. Basically, despite being in the “key” module, what these functions actually report is keyboard input , one character at a time.

The key.pressed function is different. It reports on the status (pressed or not pressed) of individual, physical keys on the keyboard. That includes the left and right shift keys, the alt keys, the function keys, and so on. It also includes the printable keys like letters and numbers, but not the shifted version of those; to key.pressed , shift-2 is just two keys being pressed, not the at-sign that key.get would report.

To illustrate, here’s a program that counts up only while the left Shift key is held.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.