Basic Computer Programming (Processing)

Similar documents
[ the academy_of_code] Senior Beginners

1 Getting started with Processing

CISC 1600, Lab 2.2: Interactivity in Processing

CISC 1600, Lab 3.2: Interactivity in Processing

Pick a number. Conditionals. Boolean Logic Relational Expressions Logical Operators Numerical Representation Binary. CS Conditionals 1

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

A B C D CS105 03a Interaction

Computer Graphics. Interaction

Exploring Processing

1 Getting started with Processing

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Watch the following for more announcements

What can we do with Processing? Let s check. Natural Language and Dialogue Systems Lab Guest Image. Remember how colors work.

Conditional Events. Mouse events and Operators. Dr. Siobhán Drohan Mairead Meagher. Produced by:

We will start our journey into Processing with creating static images using commands available in Processing:

Interaction Design A.A. 2017/2018

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

The way I feel about music is that there is no right and wrong. Only true and false. Fiona Apple. true false false

Basic Input and Output

Introduction to Processing. Sally Kong

CS110 Introduction to Computing Fall 2016 Practice Exam 1 -- Solutions

Interaction Design A.A. 2017/2018

CISC 1600 Lecture 2.2 Interactivity&animation in Processing

CISC 1600 Lecture 3.1 Introduction to Processing

CST112 Variables Page 1

Processing Assignment Write- Ups

CISC 1600, Lab 3.1: Processing

Interaction Design A.A. 2017/2018

Basic Input and Output

CISC 1600, Lab 2.1: Processing

Basic Input and Output

Class #1. introduction, functions, variables, conditionals

Bits and Bytes. How do computers compute?

CS110 Introduction to Computing Fall 2016 Practice Exam 1

What is a variable? a named location in the computer s memory. mousex mousey. width height. fontcolor. username

Recall that creating or declaring a variable can be done as follows:

An Introduction to Processing

Kimberly Nguyen Professor Oliehoek Introduction to Programming 8 September 2013

What is a variable? A named locajon in the computer s memory. A variable stores values

mith College Computer Science CSC103 How Computers Work Week 7 Fall 2017 Dominique Thiébaut

Basic Input and Output

if / if else statements

Introduction to Processing

mith College Computer Science CSC103 How Computers Work Week 6 Fall 2017 Dominique Thiébaut

CSE120 Wi18 Final Review

Functions. Functions. nofill(); point(20, 30); float angle = map(i, 0, 10, -2, 2); parameters return values

CISC 1600 Lecture 2.2 Interactivity&animation in Processing

The Processing language

Lesson Two. Everything You Need to Know. 4 Variables 5 Conditionals 6 Loops

COMP Summer 2015 (A01) Jim (James) Young jimyoung.ca

Question 1 (10 points) Write the correct answer in each of the following: a) Write a Processing command to create a canvas of 400x300 pixels:

CMPT-166: Sample Midterm

GRAPHICS & INTERACTIVE PROGRAMMING. Lecture 1 Introduction to Processing

Khan Academy JavaScript Study Guide

5.1. Examples: Going beyond Sequence

Variables One More (but not the last) Time with feeling

Miscellaneous Stuff That Might Be Important.

Repetition is the reality and the seriousness of life. Soren Kierkegaard

CS 106 Winter Lab 03: Input and Output

void mouseclicked() { // Called when the mouse is pressed and released // at the same mouse position }

University of Cincinnati. P5.JS: Getting Started. p5.js

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

GRAPHICS PROGRAMMING. LAB #3 Starting a Simple Vector Animation

1. Complete these exercises to practice creating user functions in small sketches.

This assignment was revised from the original PDF released to revise/add Parts D and E.

INTRODUCTION TO PROCESSING. Alark Joshi, Amit Jain, Jyh-haw Yeh and Tim Andersen

CPSC Fall L01 Final Exam

Computer and Programming: Lab 1

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Name CMPS 5J Final March 17, 2010 This is a closed notes, closed book exam. Each problem is worth 1 point unless indicated otherwise.

Old 257 Exam #2s for Practice

Module 05 User Interfaces. CS 106 Winter 2018

COMP Summer 2015 (A01) Jim (James) Young jimyoung.ca

Variables and Control Structures. CS 110 Eric Eaton

CS 106 Winter Lab 05: User Interfaces

Final Exam Winter 2013

Module 01 Processing Recap

BASIC ELEMENTS OF A COMPUTER PROGRAM

Module 01 Processing Recap. CS 106 Winter 2018

All program statements you write should be syntactically correct. Partial credit is not guaranteed with incorrect use of syntax.

Sten-SLATE ESP. Graphical Interface

ASSIGNMENT 2. COMP-202A, Fall 2013, All Sections. Due: October 20 th, 2013 (23:59)

Design Programming DECO2011

Notes from the Boards Set BN19 Page

THE JAVASCRIPT ARTIST 15/10/2016

Connecting Arduino to Processing

Solution Notes. COMP 151: Terms Test

(Inter)Ac*ve Scripts. Sta*c Program Structure 1/26/15. Crea+ve Coding & Genera+ve Art in Processing 2 Ira Greenberg, Dianna Xu, Deepak Kumar

SFPL Reference Manual

Animations involving numbers

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Processing & Arduino in Tandem. Creating Your Own Digital Art Tools

AN INTRODUCTION TO SCRATCH (2) PROGRAMMING

Computer Programming : C++

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2

CST112--Functions Page 1

Mirage. Language Reference Manual. Image drawn using Mirage 1.1. Columbia University COMS W4115 Programming Languages and Translators Fall 2006

Your First Windows Form

In this chapter: What is an array? Declaring an array. Initialization. Array operations using the for loop with an array. Arrays of objects.

CS 251 Intermediate Programming Java Basics

Transcription:

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) Page 1 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. Page 2 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 Page 3 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? Page 4 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. Page 5 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); Page 6 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); line (30, 190, 130, 190); line (130, 40, 130, 340); //First stroke // Horizontal stroke // 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. Page 7 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); framerate (10); // Green colour background // 10 frames per second void draw () { x = x + 1; y = y + 1; point (x, y); // Increase the value of x-coordinate // Increase the value of y-coordinate // 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).) Page 8 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 boolean pass = true; possible values: true or false. char String A single character. A pair of single quotes is used to specify the value of the variable. A sequence of characters. S must be capitalized. A pair of double 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); Activity 6 Complete the followings. Variable Data Type 1. Age 2. Name 3. Sex 4. Class 5. Average_mark 6. Married Page 9 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. Page 10 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.) Page 11 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? Page 12 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 Syntax Structure if if (test) { statements Description 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 if..else if (expression_1) { statements_1 else if (expression_2) { Statements_2 else { Statements_3 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. 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. Page 13 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 (or) P Q P Q true true true true false true false true true false false false! (not) P true false! P 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). Page 14 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. Page 15 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. Page 16 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. Page 17 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. Page 18 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. Page 19 of 19