All post of ElecFreaksProgram

Interesting Programming Guidance for Designer–Program Process Control–Condition Statement (Part One)

By November 14, 2017 No Comments
fp

In the last chapter Interesting Programing Guidance for Designer–Program Process Control- Loop Statement, we have referred to loop statement which can make a certain section of code executed repeatedly. If we use a line to analog the program execution process, it is just like the knot area. And the latter condition statement we are going to talk about will allow the program to develop multiple branches, which forms appearance same with tree root shape.

In this chapter, we will mainly show you the characteristics of if condition statement while attaching several knowledge points. You will learn to know how to use logical operators, relational operators as well as KeyPressed event.

Before we start, let me show you some relative data types and their relationships as well as some basic knowledge about logical operators.

 

Data Type Boolean, Char, String

 

表1

The previously referred int, float can store data. But appearantly, it is still not enough to use. For example, if we want to access some Chinese or English characters, we have to use char and String.

Code Example (6-1):

void setup(){

char a = 'x';

String b = "words";

println(a);

println(b);

}

 

Result in the console:


According to the example above, char is a kind of data types which is used to access a single character. When we assign a value to it, the character must carry a single quote mark to differentiate it from the name of variable. While assigning value to String type, the character has to use a double quote mark. It can access more character information than char. Suppose if we want to store information like addresses, conversations, names and so on, we can consider to use String.

Now that String can store more information than char, then can we assign the char value to String? Of course, we can on condition that we write a type conversion function, or the program will go wrong.

Code Example(6-2):

void setup(){

char a = 'x';

String b = str(a);

println(a);

println(b);

}

Result in the console:


Here, the str() is the so-called type conversion function. It can convert char type into String type.

 

Connect String

 

There is a special usage for String type. With the sign of “+”, we can connect two strings together.

Code Example (6-3):

void setup(){

String a = "words1";

String b = "words2";

String c = a + b;

println(c);

}

Result in the console:


When we want to assemble multiple text information together, we might consider “+” sign.

 

Boolean Type

 

In the following, there’s another data type, boolean. It can access very little things except two values: true and false. It is just like to cast a coin of no thickness , either front side or back side. Either true or false, no neutral status exists. Boolean type will be closely combined with the latter referred if statement. According to the value of true or false, it can judge whether to execute some statements. Let’s take a look at an example about boolean.

Code Example(6-4):

void setup(){

boolean a = true;

boolean b = false;

println(a);

println(b);

}


In the console of Processing, it will output the correspinding boolean values of variable a and b. Certainly, except for using true and false to stand for true value and false value, we can also use numbers to assign values in the program.

Code Example(6-5):

void setup(){

boolean a = boolean(1);

boolean b = boolean(0);

boolean c = boolean(3);

println(a);

println(b);

println(c);

}

Result in the console:


boolean() is a type conversion function. All “non-zero” shaping data will be converted into true value. When the number is 0, it will convert to false value. In function boolean(), you can’t write decimals. If you write boolean(3.2), then the program will report wrong.

 

Logical Operator & Relational Operator

 

In the program, we can not only do calculation of plus, minus, multiply and divide, but also some unexpected calculations.

 

Relational Operator

The final returned results of plus, minus, multiply and divide operators are values. While in relational operators, the returned results are boolean values.

表2

Code Example(6-6):

void setup(){

int a = 1;

int b = 2;

println(a == b);

println(a != b);

println(a > b);

}

Result in the console:


Rlational operator by its name is used to compare the relationship of the left and right side. It is easy to understand. When condition is workable, it returns to true value; when it is not workable, then returns to false value. Of all these, the only one thing we have to pay attention to is the writing of “==“. We must write two equal signs so that it can be called a relational operator. If we write one equal sign only, it becomes the “” symbol of assign value.

 

Logical Operator

 

Next, we come to introduce logical operator. Same to the above relational operator, its returned results are boolean values too. And it has three types: and, or, not.

表3

When using operator &&, only if the both sides of the expression is truth, the returned result can be true value. When one side is false or both sides are false, then it will return to false value.

The function of operator ! is negation. You have to write it directly before the expression without compare the left and right side. If the original expression is truth, it will return to the result of false after being used. If the original expression is false, then it will reture to the result of true.

Code Example(6-7):

void setup(){

println(true && true);

println(true && false);

println(false && false);

println(true || true);

println(true || false);

println(false || false);

println(!true);

println(!false);

}

Result in the console:


 

If Condition Statement

 

The above conceptions are quite abstract. It seems very difficult to think out the actual functions of relational operators and logical operators. Actually, only when we place it under the context of graphic design, all will be very intuitive. Finally, we come to the main role of this chapter. That is if statement.

Below is the invoke format of if statement:

if(expression){

}

Before we learned if statement, all sentances in program will be executed without choose. While after we used if statements, before execution, it will judge the value of expression. When the boolean value of expression is true, the code within brace will be executed, or it will jump out of the step.

Code Example (6-8):

void setup(){

if(true){

println(1);

}

if(3 > 2){

println(2);

}

if(false){

println(3);

}

if(3 < 2){

println(4);

}

}

Result in the console:


You can see which statements are real executed through the above output values. They are closely related to boolean values of the expressions.

 

Use If Statement to Control Graphic Display and Hide

 

Now we don’t have to see the black console any more. Just try to realize some simple graphic effects with if statement.

Code Example(6-9):

void setup(){

size(700,700);

}

void draw(){

background(32,48,65);

if(mouseX > width/2){

fill(3,240,175);

noStroke();

ellipse(width/2,height/2,200,200);

}

}

Write mouse position judgement in if statement, it will affect the execution of the following statements so that to achieve the effect of controlling graphic display or hide.

1

If Statement Extention: – else and else if

 

When the conditions are met in if statement, it will operate the code in brace. The condition of the above expression is mouseX > width/2. So when we move mouse to the right side of sreen, it will display a circle. If we want another pattern appeared when we move mouse to the left screen, then what shall we do? Shall we write an extra if statement?

You don’t have to do this. If two conditions have the relationship of “not”, thenuse else directly will be more convenient.

Invoke Format:

if(condition){

   Statement 1;

}else{

   Statement 2;

}

When conditions are met, then execute statement 1. If not met, then execute statement 2.

Code Example (6-10):

void setup() {

size(700, 700);

}

void draw() {

background(32, 48, 65);

noStroke();

if (mouseX > width/2) {

fill(3, 240, 175);

ellipse(width/2, height/2, 200, 200);

} else {

rectMode(CENTER);

fill(204, 3, 204);

rect(width/2, height/2, 200, 200);

}

}

2It is much simpler to write like this. Besides, there is another usage of if statement. That is else if. When we have more conditions to judge, we can consider it.

Invoke Format:

if(condition 1){

   Statement 1;

}else if(condition 2){

   Statement 2;

}


else if(condition n){

  Statement n;

}else{

   Statement n+1;

}

The statement of else if can be continuously superposed. Its execution sequence is still from the top to the bottom. Start from the judgement of statement 1, if condition 1 is met, then execute statement 1 and skip the following statements without execution. When condition 1 is not met, then it will detect condition 2 in else if. If condition 2 is met, then execute statement 2. Or it will repeatedly circulate until condition 2 is executed. In the last, if all conditions are not met, it will execute statements in else.

Certainly, the final else is not a must to add. If you do not write else and all conditionsare not met after execution, then all statements in if will not operate.

Code Example (6-11):

void setup() {

size(700, 700);

}

void draw() {

background(32, 48, 65);

noStroke();

if (mouseX < width/3) {

fill(3, 240, 175);

ellipse(width/2, height/2, 200, 200);

} else if (mouseX < width/3 * 2) {

rectMode(CENTER);

fill(204, 3, 204);

rect(width/2, height/2, 200, 200);

} else {

fill(3, 165, 204);

triangle(250, 450, 450, 450, 350, 250);

}

}

3This example is similar to divide the screen into 3 parts: left, middle, right. Different mouse coordinates will display different patterns.

 

If Statement Nest

 

If statemenet can be nested. Therefore, we can assemble it to create more complicated situations.

Code Example (6-12):

void setup() {

size(700, 700);

noStroke();

}

void draw() {

if (mouseX > width/2) {

background(235, 16, 0);

if (mouseY > height/2) {

fill(32, 48, 65);

rectMode(CENTER);

rect(width/2, height/2, 200, 400);

} else {

fill(255);

rectMode(CENTER);

rect(width/2, height/2, 400, 200);

}

} else {

background(48, 180, 89);

if (mouseY > height/2) {

fill(32, 48, 65);

ellipse(width/2, height/2, 200, 400);

} else {

fill(255);

ellipse(width/2, height/2, 400, 200);

}

}

}

4Because of we have written different background colors separately into the two branches of if else in the first layer, the mouse position change will directly influence background color. In the latter two branches, we separately write an if else statement again. Through multiple groups of situations, it is equivalent to divide the program into 4 sections or 4 status.

 

If Statement and Modulo Operation

 

Here we are going to introduce a clever usage to you. It has high frequency of usage in for loop. In the past, we always use “i” value in for loop to influence partial parameters of graphic elements. For example, to draw a row of circles, we have to use “i” value to get the coordinate of position. Except for this, actually we can make some judgement for the value “i” like to do modulo operation( equals to get the remainder). According to the different remainders, it will group a large number of elements combining with if statement. In the following example, when “i” is even number, the element fill color is white; when it is odd number, the fill color is black.

Code Example (6-13):

void setup() {

size(700, 700);

noStroke();

}

void draw() {

background(132, 197, 100);

int num = 10;

float w = mouseX / 10;

for (int i = 0; i < num; i++) {

if (i % 2 == 0) {

fill(255);

} else {

fill(0);

}

rectMode(CENTER);

rect(width/(float)num * (i + 0.5), height/2, w, 600);

}

}

5

 

KeyPressed Event

 

Now I believe you may have understand the characteristics of if statement. But if we want to make it become more funny, we have to use some programming conceptions introduced in the following. Next, what we are going to introduce is keyPressed event.

The previous program interactions are basically depend on mouse coordinate mouseX, mouseY to realize. Although it is very flexible, the limit is obvious. When we want to make choice through the mouse position, we have to write lots of if statements. It is the wisest method to use keyboard to do interaction under the condition that we haven’t mastered how to write a button controller. keyPressed is event relative to keyboard. Same with setup and draw, you have to define it beforehand. You only have to write its structure into the brace, then you can invoke it directly.

Invoke Format:

void keyPressed(){

}


keyPressed can be presently considered as in the same level of setup and draw. It is excluded from setup and draw. When you press down the keys on the keyboard, statements in keyPressed will be executed.

Let’s look at the example below and try to understand the influence of KeyPressed towards the program process.

 

keyPressed Execution Process

 

Code Example(6-14):

void setup(){

println(frameCount + ":setup");

}

void draw(){

println(frameCount + ":draw");

}

void keyPressed(){

println(frameCount + ":keyPressed");

}

Code Explain:

After the program operated, remember to press some keys on keyboard

randomly. Then close the program and watch out the result in the console. Here we mainly observe the execution sequence of each structure, among which frameCount can obtain the current operated frames.


Roll down the console, look for strings with character of “keyPressed”. Its output position depends on your key press time. In this example, it shows when program runs to 90 frames, it leads to key press event.

Through the observation of frameCount, it is not difficult to find that keyPressed event is executed behind draw .

The sign “” here stands for connect two strings in the front and back. Although frameCount int the front is shaping data, it will output links after being defaulted to convert into string type in P5.

 

keyPressed Obtain Key Press Value

 

keyPressed can not only judge when you press, but also get to know which key is pressed through obtaining the value of key.

Code Example(6-15):

void keyPressed() {

if (key == '1') {

println( 1 );

}

if (key == '2') {

println( 2 );

}

if (key == '3') {

println( 3 );

}

if (key == 'a') {

println( 'a' );

}

if (key == 's') {

println( 's' );

}

if (key == 'd') {

println( 'd' );

}

}

In the above example, we have added key press detection for number keys 1, 2 , 3 and alphabet keys a, s, d. When you pressed these keys, it will output the relative characters in the console. Key is defined by the system. It can obtain the key value you pressed automatically. So, if you want to know whether key is a certain value, the judgement condition shall be written into if(key == a certain value). If you want to detect number keys or alphabet keys, you only have to add single quote marks on the base of numbers or alphabets.

 

Use keyPressed to Control Graphic

 

Previously, we have realized the graphic hide and display effect through changing the position of mouse. Now we can try it with keyPressed.

Code Example (6-16):

boolean show;

void setup() {

size(700, 700);

}

void draw() {

background(32, 48, 65);

if (show) {

fill(3, 240, 175);

noStroke();

ellipse(width/2, height/2, 200, 200);

}

}

void keyPressed() {

if (key == '1') {

show = true;

}

if (key == '2') {

show = false;

}

}

6

 

Drawing functions can not be written into keyPressed. You have to create a boolean variable as a media. keyPressed will influence the value of boolean variable firstly. Then the if statement in function draw will decide to display or hide according to this value.

Introductions about the usage of keyPressed come to a stop here. Later, we will have more chapters for your to explore various events deeply.

 

Condition Control Statement Switch

 

The condition control statements do not have if statement only. There is a brother for if statement. That is switch.

Writing Format:

 

switch(expression) {

 case constant expression 1:

   Statement 1;

   break;

 case constant expression 2:

   Statement 2;

   break;

 ….

 case constant expression n:

   Statement n;

   break;

 }

Behind switch, we have to write an expression. The latter sentence of case is the possible conditions for the expression value. When this value meets the condition, the relative statement will execute.

Case statement can have multiple superposition. And it must follow a constant behind.

We have to add break in the end of each case. This is a custom practice. It is used for jumping out of this sentence.

If we do not add break, then the case statement after break will execute directly.

Switch and if are very similar. Then when shall we use switch and when shall we use if, we can refer to the above example (6-15) and get familiar with the usage of switch.

Code Example (6-16):

void keyPressed() {

switch(key) {

case '1':

println(1);

break;

case '2':

println(2);

break;

case '3':

println(3);

break;

case 'a':

println('a');

break;

case 's':

println('s');

break;

case 'd':

println('d');

break;

}

}

It is more intuitive to use switch statement to judge key value than use if statement.

When there are multiple branches needed to be dealt with by the program and the values need to be judged are constants, then you can consider using switch.

The case in switch statement requires to be a constant. It is usually not operate logical judgement. If the judgement condition of the internal layer is like “x > 5”, then you can’t use switch but consider using if statement.

 

The Extention of Switch

 

Switch is similar to if. When the previous conditions are not met for the else in if, it will excute the statements within. Correspond to switch, it is default. It is often placed in the last.

Writting Format:

switch(expression) {

 case constant expression 1:

   Statement 1;

   break;

 case constant expression 2:

    Statement 2;

   break;

 ….

 case constant expression n:

    Statement n;

   break;

 default:

       Statement n+1;

 }

Behind default, you don’t have to add break statements.

 

End

 

The introduction of condition control statement comes to an end here. In the next chapter, we will tell you methods about carrying words and pictures. Combine these knowledge with if statement, you can create a text venture game from scratch!

This article comes from designer Wenzy.

 

Relative Readings:

 

Interesting Programming Guidance for Designer——Processing Initial Touch

Interesting Programming Guidance for Designer——Create Your First Processing Program

Interesting Programming Guidance for Designer–Get Your Picture Running(Part One)

Interesting Programming Guidance for Designer–Get Your Picture Running(Part Two)

Interesting Programing Guidance for Designer–Program Process Control- Loop Statement

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)
song

Author song

More posts by song

Leave a Reply