Making Decision

Valuating Boolean Expressions

have previous knowledge. Therefore, you can follow this step-by-step guide. If not, we recommend we try first our previous posts:

Coding Lessons for kids: A good place to start

Basic coding for kids: coding in scratch

Easy Scratch Project: Let’s do it

Then, let’s move on and learn new programming concepts.

We set two variables, x, and y, as follows: x = 5, and y = 10. The table below below below shows some examples that use Scratch’s relational blocks. These examples reveal several small prints about relational operators. First, we will match individual variables (such as x, y) and complete expressions (such as two * x and x + 6). Second, a comparison result is usually true or false (that is, a Boolean value). Third, the x = y block doesn’t mean “Set x adequate to y.” Instead, it asks, “Is x up to y?”

So when the statement set z to (x = y) is executed, the worth of x remains 5.

Relational operators in scratch3.0

Comparing Letters and Strings

Let’s consider a game during which the player tries to guess a one-letter secret code between A and Z. The sport reads the player’s guess, compares it with the key code, and instructs the player to refine his guess based on the alphabetical order of letters. If the key letter were G, for example, the player entered a B. The sport should say something like “After B” to inform the player that the key code comes after the letter B in the alphabet. How can you compare the proper letter with the player’s input to choose what message to display?

Fortunately, the relational operators in Scratch also can compare letters. As illustrated in the following figure, Scratch compares letters supported by their alphabetical order. Since the letter A comes before the letter B within the alphabet, the expression A < B returns true. However, it’s vital to notice that these comparisons aren’t case sensitive; majuscule A is the same as the small letter a. Thus, the expression A = an also returns true.

Operators in Scratch

figure: Using relational operators to check letters

Knowing this information, you’ll be able to test the player’s guess using the following set of conditionals:

IF (answer = secret code), then say Correct
 OR IF (answer > secretCode), then say Before <answer>
Or IF (answer < secretCode), then say After <answer>

I’ll teach you ways to implement conditionals in Scratch. But let’s explore relational operators first.

What if the key code contains over one letter? as an example, the player might guess the name of an animal. Are you still using Scratch’s relational operators to try to make a comparison? Luckily, the short answer is yes:

You can use Scratch’s relational operators to match strings. But how does Scratch process a comparison like an elephant > or mouse? The examples in the following figure illustrate the results of comparing strings.

Relational operators Relational Operators in Scratch

1                                                                                                          2

Relational operator in scratch3.0 Relational Operators in Scratch3.0

3                                                                                                                4

  • Scratch compares strings irrespective of their case. So, for example, “Scratch is fun” and “SCRATCH IS FUN”  are considered equal.
  • Scratch counts white spaces in its comparison. So, for example, the string “Scratch is fun,” which starts and ends with a single space, is not the same as the “Scratch is fun” 3.
  • When comparing the strings “ABC” and “ABD,” as in 4, Scratch first considers the first character in the two strings. Then, since they are the same (the letter A in this case), Scratch examines the second character in both strings then, as this character is also the same in the two strings. If the letter C is less than the letter D (that is, C comes before D in the alphabet), the first string is less than the second string.

Knowing this, it shouldn’t surprise you when the expression elephant >mouse evaluates to false, although actual elephants are much larger than mice. In keeping with Scratch’s string comparison rules, the string “elephant” is less than the string “mouse” because the letter e (the first letter in elephant) comes before the letter m (the first letter in mouse) within the alphabet.

Comparing and sorting strings supported by the alphabetical order of their characters is employed in many real-life situations, including ordering directory listings, books on bookshelves, words in dictionaries, and so on. For example, the word elephant comes before the word mouse within the dictionary, and string comparison in Scratch gives a solution that supports this order.

Now that you understarelational operators are and how Scratch uses them to match numbers and strings, it’s time to find out about conditional blocks.

Decision Structures

Scratch’s Control palette contains two blocks that allow you to create decisions and control actions in your programs: the if block and, therefore, theif,/else block. Using these blocks, you’ll ask a matter and take a course of action to support the solutioDuring this section, we’ll’ll discuss these two blocks in detion, discuss flags, and learn to check multiple conditions with nested if blocks. I’ll then introduce menu-driven applications and explain how nestif blocks can aid in their implementation.

The if Block

The if block could be a decision structure thallows youity to specify whether a group of commands should (or should not) be executed supported by the ttest condition results. The design of the if block and its corresponding flowchart are shown in the following figure.

IF Block inScratch3.0

The diamond shape represents a call block that provides a yes/no (or true/false) answer to an issue in the following figure. If the test condition within the header of the if block is true, the program executes the commands listed inside the body before moving on to the command that follows the if block (Command M within the following figure). If the test condition is fake, the program skips those commands and moves to Command M.

To see the if block in action, create the script shown in the following figure and run it. The script runs a forever loop that moves a sprite around the Stage, changes its color, and makes it bounce off the sides of the Stage.

If Statement in Scratch3.0 

The forever loop in our script contains an if block that checks the sprite’s x-position after every move command. If the x-position more significantger than zero, the sprite should change its color. After you run this script, you’ll notice that the sprite changes its color only it’s taking possession of the right 1/2 of the StagThishis is often because the “change color effect by 25 “block is executed only the x position > 0 conditions is true.the if block in scratch3.0

Using Variables as Flags

You are simply developing an area adventure gathat aims is to destroy a fleet of attacking warships. Tcaptain, the playerain, maneuvers a starship with the arrow keys on the keyboard and fires missiles by pressing the spacebar. If the player’s starship gets hit by enemy fire a certain number of times, the ship loses its ability to attack. At now, pressing the spacebar mustn’t fifurther missiles to any extentles, and therefore the captain has to adopt a defense strategy to avoid takint further hitWhenhen the spacebar is pressed, your program must check the state of the starship’s attack system to make a decision whether or not the player can fire.

Checks of this nature are normally performed using flags, which are variables you employ to point to whether or not an occasion of interest has happened. you’ll use any two values to explain the event’s status, but it’s common practice to use 0 (or false) to point that the event hasn’t occurred and 1 (or true) to point that it’s.

In your space shooter game, you’ll use a flag named can fire to point the state of the starship. a worth of 1 implies that the starship can fire missiles, and a price of 0 implies that it can’t. Based on this, your spacebar event handler may be coded as shown in the following figure. At the beginning of the sport, you’d initialize the value of the canFire flag to 1 to point that the starship is capable of firing missiles. When the starship gets hit by a particular amount of enemy fire, you’d set the canFire flag to 0 to point that the attack system has become dysfunctional; at that time, pressing the spacebar won’t fire from now on missiles.

Although you’ll be able to name your flags anything you wish, I like to recommend using names that reflect their true/false nature. The table below below below shows some examples of flags you may use within the space shooter game.

set variable value instruction

Now that you just understand how to use the if block and flags. Let’s discuss another conditional block, one which will allow you to execute one block of code when a particular condition is true. And another if that condition is fake.

The if/else Block

Imagine that you just are creating a game to show basic math to elementary students. The sport presents an additional problem and so asks the coed to enter a solution. The coed should receive one point for an accurate answer and lose one point for an incorrect answer. you’ll perform this task using two if statements:

If the answer is correct, add one point to score

If the answer is incorrect, subtract one point from the score

You could also simplify this logic—and make the code more efficient— by combining the two if statements into one if/else statement as follows:

Nested if and if/else blocks

you wish to check over one condition before taking an action. You can nest multiple if (or if/else) blocks inside one another to perform the required test. Consider for instance the script shown in the following figure, which determines whether a student should receive a scholarship. To qualify, the student must have: (1) a grade average (GPA) more than 3.8 and (2) a grade above 92 percent in math.

 

nested if else blockif else condition

First, the expression GPA > 3.8 is tested. If this expression is fake, we don’t just check the opposite condition because the scholar doesn’t meet the scholarship criteria. If the expression GPA > 3.8 is true, however, we need to test the second condition. this can be through with the nested if/else block,

which tests the condition mathScore > 92. If this second condition is additionally true, the coed gets the scholarship. Otherwise, the scholar doesn’t qualify, and an appropriate message explaining the rationale is displayed.

Menu-Driven Programs

Next, we’ll explore a typical use of nested if blocks. specifically. You’ll learn how to put in writing programs that present the user with choices and act on the user’s selection.

When you come out with some programs, they display an inventory (or menu) of available options and expect you to form a variety. Sometimes, you’ll interact with these programs by entering a variety that corresponds to your required option. Such programs may use a sequence of nested if/else blocks to determine the user’s selection and act appropriately. To determine how nested if/else blocks work, we’ll discuss an application. As shown in the following figure, that calculates the world of various geometric shapes.

menu driven programs

The program for this application contains the Stage’s background image. Which shows the available options (the numbers 1, 2, or 3), and the Tutor sprite. Which asks the user for a choice, performs the calculation, and displays the result. The most script, shown in the following figure, starts when the green flag icon is clicked.

menu driven programs

 

After asking the user to enter a choice, the Tutor sprite waits for the user’s input and uses three if/else blocks to process it. If the user entered a valid choice (that is, 1, 2, or 3). The script calls the acceptable below procedure to calculate the world of the indicated shape. Otherwise, the script invokes the say command to tell the user that the selection entered is invalid. The procedures for calculating the areas of the three shapes are shown

in the Following figure below.

 

block making

Each procedure asks the user to enter the size for its corresponding shape. Calculate the area and display the result. for instance. The Rectangle procedure asks the user to enter the length and width of the rectangle. And saves the answers within the length and width variables, respectively. It then computes the world by multiplying the length by the width and displays the solution. The opposite two procedures work similarly.

Logical Operators

In the previous section, you learned the way to use nested if and if/else blocks to test multiple conditions. But you’ll also try this with logical operators. Using logical operators, you’ll be able to combine two or more relational expressions to provide one true/false result. for instance, the logical expression (x > 5) and (x < 10) is created from two logical expressions (x > 5 and x < 10) that are combined using the logical opera,tor and. we will think of x > 5 and x < 10 because of the two operands of the operator; the results of this operator are true given that both operands are true. The table below lists the three logical operators available in Scratch with a quick explanation of their meaning.

logical operators in scratch

Now that you’ve seen a quick overview of every operator. Let’s explore how they add more detail, one at a time.

The and Operator

The And-Operator takes two expressions as parameters. If both expressions are true, the operator returns true; otherwise, it returns false. The truth table belor and, which lists the output of the operator for all possible combinations of inputs. It is shown in the table below.

and logical operator

As an example of using the and opera, let’st’s say we’re creating a game in which the player gets 200 bonus points when the score reaches 100 within the first level. The sport level is tracked by a variable named level. And also, the score is tracked employing a variabcalledmed score. The following figure shows how these conditions are tested using nestif blocks u or with the operator v.

and operator

2.and operator in scratch

In both cases, the bonus points are added only both conditions are true. As you’ll see, the And-Operator provides a more concise way of performing the identical test. The command(s) inside the if block are in the following figure. We are going to be executed providing level equals 1 and score equals 100. If either condition is fake, the complete test evaluates to false, and therefore the change score by 200 blocks won’t be executed.

The Or Operator

The Or-operator also takes two expressions as parameters. If either expression is true, the or operator returns true. It returns false only the 2 expressions are both false. the reality table below for the or operator is given in the table below below below.

Or operator

To demonstrate the utility of the or operator. Let’s assume that players of a certain game have a limited time to succeed in the following level. They also start with a given amount of energy that depletes as they navigate the present level. The game ends if the player fails to succeed in the following level within the allowable time. Or if the player depletes all the allotted energy before reaching the next level. The remaining time is tracked by a variable named timeLeft, and the player’s current energy is tracked by a variable named energyLevel. The following figure shows how the sport end condition may be tested using nested

if/else blocks 1 and therefore the or operator 2…

or operator

or operator in scratch

Note again that the operator provides a more concise thanks to testing multiple conditions. The command(s) inside the if block in the Following figure will be executed if timeLeft or energyLevel is 0. If both of those conditions are false, the complete test evaluates to false, and the gameOver flag will
not be set to 1.

The not operator

The not operator takes only one expression as input. The operator’s results are true if the expression is fake and false if the expression is true. The truth table below for this operator is given in the table below.

not operator

Going back to our hypothetical game from earlier, let’s say the player
can’t attain the following level if the score isn’t quite 100 points. This
would be an honest place to use the not operator, as shown in the following figure.
You can read this code block as, “If the score isn’t greater than 100, do the
command(s) inside the if block.”

not operator in scratch

In effect, if the value of the variable score variable is 100 or lower, the test expression evaluates to true, and the say command will execute. Note that the expression not (score > 100) resembles (score ≤ 100).

We have explored several Scratch concepts during this chapter thus far, including comparisons, conditional statements, and logical operators. Let’s use that knowledge to form some fun and useful applications.

You can find exciting projects on the official Scratch site.

 


Posted

in

, ,

by

Tags: