Determining when Keys Are Pressed

One problem with the drawing application is that there is no way to clear the screen and start over should you make a mistake when drawing. This can be easily rectified using the sensing code block shown in Figure 6.3, which retrieves a true or false, depending on whether a specified key is pressed.

Figure 6.3. This sensing block can be used to detect when the user presses a specified keyboard key.


To see an example of how to work with this code block, let’s modify the previous drawing application by editing the script belonging to the application’s sprite, as shown here.

As you can see, three new code blocks have been added that clear the stage whenever the spacebar is pressed. Figure 6.4 shows an example of the drawing application in operation. Here, the application is used to draw the name Lee on the stage. Next, the spacebar is pressed, clearing the stage, after which an image of a tree has been drawn.

Figure 6.4. This enhanced version of the drawing application can be used to draw and erase.


Tip

In addition to detecting keystrokes using a sensing code block, you can also use the control code block shown in Figure 6.5. The difference between these two code blocks is that the sensing code block can be used within a loop to continuously determine that a specified keyboard key is being pressed. The control block, on the other hand, only executes once when the specified key is initially pressed and is therefore good for initiating an individual action and not for facilitating the repeated execution of an action. You will learn more about this code block later in Chapter 9, “Conditional and Repetitive Logic.”

Figure 6.5. This code block is used to initiate an action whenever a specific keyboard key is pressed.



..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.130.201