Basic Computer Programming (Processing) Computer Programming... · Computer Literacy Basic Computer...
Embed Size (px)
Transcript of Basic Computer Programming (Processing) Computer Programming... · Computer Literacy Basic Computer...

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 1 of 19
Basic Computer Programming (Processing)
Contents
1. Basic Concepts (Page 2)
2. Processing (Page 2)
3. Statements and Comments (Page 6)
4. Variables (Page 7)
5. Setup and Draw (Page 8)
6. Data Types (Page 9)
7. Mouse Function (Page 10)
8. Keyboard Function (Page 12)
9. Conditionals (Page 13)
10. Relational Operators (Page 14)
11. Logical Operators (Page 14)
12. Looping (Page 16)
13. Functions (Page 17)

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 2 of 19
Basic Concepts
A computer program is a sequence of instructions, written to perform a specified task.
Programmers are people who write the programs.
Programming language is a computer language used to create programs. Different
programming languages have their own sets of rules called syntax. A program is wrong if
syntax errors are found.
Source code of a program refers to the human-readable text written with a suitable computer
language. Source code is often transformed into lower-level machine code understood by the
computer.
Executable file contains the machine code and it be executed on a suitable platform. Usually,
execute file has an ‘exe’ file extension.
What is the meaning of ‘open-source’? What is the advantage of it?
Processing
Processing is a programming language initially created to teach computer programming
fundamentals. Processing can be found in https://processing.org/. Download and extract it.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 3 of 19
Open the folder and execute the ‘processing.exe’ program.
Remarks: Alternatively, you can download the program and the source codes of all examples
in http://www.plk83.edu.hk/cy/processing

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 4 of 19
Activity 1
1. Open Processing.
2. Type the following: ellipse (50, 50, 80, 80);
3. Click the RUN button.
What is the output of the program?
____________________________
4. Save the program. Name it as ‘Activity1’. Hence, a new folder is created.
5. Close Processing.
6. Open the ‘Activity1’ folder and open the file
‘Activity1.pde’.
7. Click File Export Application.
8. Choose the Windows platform.
9. Open the folder ‘application.windows32’ inside the
‘Activity1’ folder and find the file ‘Activity1.exe’.
What is the name of source code file? ____________________________
What is the name of the executable file? ____________________________

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 5 of 19
In the above program, ellipse is a function with 4 arguments inside the brackets.
ellipse (a, b, c, d) a: x-coordinate of the ellipse
b: y-coordinate of the ellipse
c: width of the ellipse
d: height of the ellipse
Try to modify the values of the four arguments and observe the output of the program.
Where is the origin of the coordinate system? ____________________________
Activity 2
Study the following functions.
size (w, h) w: width of the display window
h: height of the display window
point (x, y) x: x-coordinate of the point
y: y-coordinate of the
line (x1, y1, x2, y2) x1: x-coordinate of the first point
y1: y-coordinate of the first point
x2: x-coordinate of the second point
y2: y-coordinate of the second point
triangle (x1, y1, x2, y2, x3, y3)
quad (x1, y1, x2, y2, x3, y3, x4, y4)
rect (a, b, c, d) a: x-coordinate of the rectangle
b: y-coordinate of the rectangle
c: width of the rectangle
d: height of the rectangle
Write a program to output the following.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 6 of 19
Activity 3
Visit https://processing.org/reference/ and learn three more functions: background, stroke and
fill.
Design a colourful logo.
Statements and Comments
Statements are the elements that make up programs. The ";" (semi-colon) symbol is used to
end statements.
Comments are used for making notes to help people better understand programs. A comment
begins with two forward slashes ("//").
Example 1
// The size function is a statement that tells the computer how large to make the window.
size (640, 360);
// The background function is a statement that tells the computer
// which color (or gray value) to make the background of the display window
background (204, 153, 0);

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 7 of 19
Variables
Variables are used for storing values. The values of the variables can be changed in the program.
No space is allowed in the variable name.
Example 2
size (400, 400);
line (30, 40, 30, 340); //First stroke
line (30, 190, 130, 190); // Horizontal stroke
line (130, 40, 130, 340); // Last stroke
The coordinates of the upper L.H.S. corner of the letter H are (30, 40), the width is 100 and
the height is 300.
It is tedious to change the position of the letter H in the program as we have to change many
numbers in the program.
In the following program, two variables are used to represent the coordinates of the upper
L.H.S. corner and it is easier to change the position of the letter H.
Example 3
size (400, 400);
int x = 30; // x-coordinate of the upper L.H.S. corner
int y = 40; // y-coordinate of the upper L.H.S. corner
line (x, y, x, y + 300);
line (x, y + 150, x + 100, y + 150);
line (x + 100, y, x + 100, y + 300);
Activity 4
Add two more variables in the last program such that you can easily control the height and the
width of the letter H.
Try to modify the values of the variables to produce the letter H with different sizes and
positions.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 8 of 19
Setup and Draw
The code inside setup () runs once when the program is started.
The code inside the draw () function runs continuously from top to bottom until the program
is stopped.
Example4
int x = 0; // Initial x-coordinate
int y = 0; // Initial y-coordinate
void setup () {
size (400, 300);
background (0, 255, 0); // Green colour background
frameRate (10); // 10 frames per second
}
void draw () {
x = x + 1; // Increase the value of x-coordinate
y = y + 1; // Increase the value of y-coordinate
point (x, y); // Draw a point
}
Activity 5
Design a program to show a point initially at the center of the window. The point become a
circle and the size is increasing.
(Hint: The center of the window is (width / 2, height / 2).)

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 9 of 19
Data Types
Different data types can be used to store different kinds of data.
Data Type Description Example
int Integer. int a = 4;
float A number with decimal place. float b = 5.2;
boolean A Boolean variable has only two
possible values: true or false.
boolean pass = true;
char A single character.
A pair of single quotes is used to
specify the value of the variable.
Example 5
size (200, 100);
char letter = 'A';
String words = "Hello Friends!";
background(0); // Set background to black
textSize (14);
text (letter, 20, 30);
text (words, 20, 70);
String A sequence of characters. ‘S’
must be capitalized.
A pair of double quotes is used to
specify the value of the variable.
Activity 6
Complete the followings.
Variable Data Type
1. Age ____________________
2. Name ____________________
3. Sex ____________________
4. Class ____________________
5. Average_mark ____________________
6. Married ____________________

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 10 of 19
Mouse Functions
The coordinates of the previous mouse pointer are stored in the variables pmouseX and
pmouseY.
The coordinates of the current mouse pointer are stored in the variables mouseX and mouseY.
The mouseClicked() function is called once every time a mouse is clicked.
Example 6
void setup () {
size (400, 400);
}
void draw () {
line (pmouseX, pmouseY, mouseX, mouseY);
}
void mouseClicked () {
background (200);
}
Activity 7
In Example 6, the mouse is working like a pen to draw the line. Modify the program such that
you can toggle the ‘pen up’ and ‘pen down’ status with a mouse click.
(Hint: Declare a variable to represent the pen status.)
Activity 8
Visit https://processing.org/reference/ and learn more mouse functions such as mousePressed,
mouseDragged and mouseButton.
Design a program with the following features.
1. Drag the mouse to draw rectangles with different sizes.
2. Click the right mouse button to clear the drawing.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 11 of 19
Part of the program is given below.
int oldX; // x-coordinate of the upper L.H.S. corner of the rectangle
int oldY; // y-coordinate of the upper L.H.S. corner of the rectangle
void setup () {
size (400, 400);
}
void draw () {
}
void mousePressed () {
if (mouseButton == RIGHT) background (200); // Clear the drawing
oldX = ____________;
oldY = ____________;
}
void mouseDragged () {
rect (___________,___________,___________, ___________);
}
Modify the above program such that a new colour is randomly assigned to a new rectangle.
(Hint: Study the fill and random function on the ‘Reference’ page.)

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 12 of 19
Keyboard Function
The keyPressed() function is called once every time a key is pressed. The key that was pressed
is stored in the key variable. The data type of key is ‘char’.
Example 7
int x = 200; // Initial x-coordinate
int y = 150; // Initial y-coordinate
void setup() {
size (400, 300);
}
void draw() {
// keep draw() here to continue looping while waiting for keys
}
void keyPressed() {
if (key=='6') x = x + 1; // Moving right
if (key=='4') x = x - 1; // Moving left
if (key=='8') y = y - 1; // Moving up
if (key=='2') y = y + 1; // Moving down
point (x, y); // Draw a point
}
Example 8
int x = 200; // Initial x-coordinate
int y = 150; // Initial y-coordinate
void setup() {
size (400, 300);
}
void draw() {
if (key=='6') x = x + 1; // Moving right
if (key=='4') x = x - 1; // Moving left
if (key=='8') y = y - 1; // Moving up
if (key=='2') y = y + 1; // Moving down
point (x, y); // Draw a point
}
Run the two above programs. What is the difference between them?

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 13 of 19
Conditionals
Conditional control structures allow a program to decide to take one action if the condition is
true or to do another action if the condition is false. The conditions are always logical or
relational statements.
Control
Structure
Syntax Description
if if (test) {
statements
}
Allows the program to make a decision about
which code to execute. If the test evaluates to
true, the statements enclosed within the block
are executed and if the test evaluates to false
the statements are not executed.
if..else if (expression) {
statements
} else {
statements
}
Extends the if structure allowing the program to
choose between two blocks of code.
If the expression is true, the first block of
statements is executed. Otherwise, the second
block of statements is executed.
if..else if (expression_1) {
statements_1
} else if (expression_2) {
Statements_2
} else {
Statements_3
}
expression_1 expression_2 Block of
code will be
executed
true any value statements_1
false true statements_2
false statements_3
Activity 9
Modify the program in Example 7 such that you can control the movement of the point in 8
directions using the keys on the NumPad.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 14 of 19
Relational Operators
Operator Meaning
< Less than
> Greater than
== Equality
!= Inequality
<= Less than or equal to
>= Greater than or equal to
Logical Operators
In the following truth tables, there are
two logical expressions P and Q. Logical
expressions can hold two possible values
only: true or false.
&& (and)
P Q P && Q
true true true
true false false
false true false
false false false
! (not)
P ! P
true false
false true
Example 10
Read the example carefully and decide which
logical operator can check whether the marks
are valid (i.e., between 0 and 100 inclusively).
|| (or)
P Q P || Q
true true true
true false true
false true true
false false false

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 15 of 19
Activity 10
Modify the program in Activity 9 such that the point will come back from the opposite side of
the window when it leave the window at one side.
Activity 11
Design a program to display a black square in one of the four quadrants according to the mouse
location as below.
Let’s first write the logic of the program in pseudocode (i.e., English).
Setup:
1. Set up a window of 200 x 200 pixels.
Draw:
1. Draw a white background.
2. Draw horizontal and vertical lines to divide the window in four quadrants.
3. If the mouse is in the top left corner, draw a black square in the top left corner.
4. If the mouse is in the top right corner, draw a black square in the top right corner.
5. If the mouse is in the bottom left corner, draw a black square in the bottom left corner.
6. If the mouse is in the bottom right corner, draw a black square in the bottom right
corner.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 16 of 19
Looping
Looping is a generative process of repeating a set of rules or steps over and over again.
FOR Loop
A for loop can have its own variable just for the purpose of controlling the number of loops.
Example 11
size (200, 200);
for (int i = 40; i <= 160; i=i+20)
line (i, 10, i, 80);
Here are the properties of the variable i in the for loop.
Initial value: 40
The loop will continue if i <= 160
The value of i is increased by 20 in each loop.
Activity 12
Draw 10 concentric circles with different radii.
(Hint: Draw the larger circles first.)
Try to use different colours in the circles.
WHILE Loop
Just as with conditional (if else) structures, a while loop
employs a Boolean test condition. If the test evaluates to true, the instructions enclosed in
curly brackets are executed; if it is false, we continue on to the next line of code.
Syntax: while (Boolean test) {
statements
}
Example 12
int i = 0;
while (i <= 100) {
line (i, 100, i, 100 - i);
i += 2;
}
Remarks: i += 2; is the same as i = i + 2;
Similarly, i++; i+=1; and i = i + 1; are different ways to increase the value of i by one.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 17 of 19
Activity 13
Use a while to draw the following diagram. The length of the longest line is 100 units and the
length of the shortest line is 10 units. In each loop, the length is decreased by 10 units.
Functions
In long programs, there are hundreds, thousands and even more lines of code. Functions are a
means of taking the parts of long program and separating them into modular pieces, making
the code easier to read, as well as to revise.
A function definition (sometimes referred to as a ‘declaration’) has three parts.
1. Return type
2. Function name
3. Parameters
Example 13
void setup () {
println (average (4, 5));
println (average (7, 8));
}
float average (int a, int b) {
return ((a + b) / 2.0);
}
The average function takes two integer parameters (a and b) and returns a float (non-integer)
result.
When calling the average function, two integer arguments should be provided.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 18 of 19
Example 14
Suppose we are going to design a Space Invaders game. Out steps for draw () might look
something like.
1. Draw background
2. Draw spaceship
3. Draw enemy
4. Move spaceship according to user keyboard interaction
5. Move enemy
float shipX = 150;
float shipY = 250;
float EnemyX = 100;
float EnemyY = 50;
void setup () {
size (300, 300);
frameRate (30);
}
void draw () {
background ();
drawShip (shipX,shipY);
drawEnemy (EnemyX, EnemyY);
moveShip ();
moveEnemy ();
}
void background () {
background (0);
stroke (255);
for (int i = 0; i < 10; i++)
point (random (300), random (300));
}
void drawShip (int x, int y) {
stroke (0, 0, 255);
fill (0, 255, 0);
triangle (x, y, x - 20, y + 10, x + 20, y + 10);
ellipse (x, y, 10, 40);
}
void drawEnemy (float x, float y) {
}
void moveShip () {
if (key == CODED) {
if (keyCode == LEFT) shipX--;
if (keyCode == RIGHT) shipX++;
if (keyCode == UP) shipY--;
if (keyCode == DOWN) shipY++;
}
}
void moveEnemy () {
}
Activity 14
Try to complete the above program. The enemy tries to catch the
space ship.

Computer Literacy Basic Computer Programming (Processing)
__________________________________________________________________________________________
Page 19 of 19
Assignment
Title
Ping-pong game
Task
The following picture shows a very old game. Human player can control the movement of one
racket to hit the ball. Another racket is controlled by the computer.
You can enhance the game such as
making the display more beautiful
showing the scores
determining the winner according to some defined rules
more …
Requirements
Submit a zip file to eClass with the following elements.
1. A Word document containing the descriptions and screenshots to show all the features of
the game.
2. The source code of the program.