Generating a Random Number

Some applications, such as computer games, require an element of randomness or chance. For example, a game that needs to simulate the rolling of dice needs to be able to create a pair of random numbers in the range of 1 to 6. Scratch provides the capability through the code block shown in Figure 8.3.

Figure 8.3. By default, this code block is configured to generate a number in the range of 1 to 10.


This code block provides a means of generating random integer (whole) numbers using any specified range of numbers. The default range is 1 to 10, but you may change the input fields to suit your needs. If needed, you can generate negative numbers. In addition to hard coding a numeric range into the control, you can substitute variable blocks by dragging and dropping them into either or both of this code block’s input fields.

To develop an understanding of how this code block works, look at the following example:

Here, a script has been created that begins by assigning a variable named Count a starting value of 0. Next, the variable’s value is changed by assigning it a randomly selected value in the range of 1 to 5. A loop is then set up to repeat the execution of two embedded code blocks. The loop is designed to repeat a specified number of times and is set up by default to execute 10 times. However, by dragging and dropping an instance of the Count variable block into the loop’s input field, the number of times that the loop executes is randomly determined, depending on the randomly assigned value of Count.

Note

Each time the loop executes, it plays an audio file that sounds like a cat meowing. In order to give the audio file time to finish playing, a control block was added to pause script execution for one second. To see this script in action, create a new Scratch application and add the script to the default Cat sprite.


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

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