IAT 800 Lec 3 - sfu.ca

IAT 800 Lec 3 - sfu.ca

IAT 265 Lecture 2: Java Loops, Arrays Processing setup, draw, mouse Shapes Transformations, Push/Pop Suggestions on learning to program g Spend a lot of time fiddling around with code Programming is something you have to learn by doing it g Get help from other people I expect those who already know some

programming to help others Figure things out in groups g Ask me questions in class Jan 9, 2018 IAT 265 2 setup() Syntax void setup() is a predefined Processing method that you define setup() is called once when a sketch first starts executing Semantics

g Place any startup code in setup(), eg. Setting the size Setting the background color Initializing variables Jan 9, 2018 IAT 265 Design 3 draw() draw() is a predefined Processing method that you define draw() is called repeatedly by the Processing system g

Put code in draw() when you need to constantly update the display (for example, animating an object) Jan 9, 2018 IAT 265 4 Example of setup() and draw() int x; int y; void setup() { size(400, 400); background(0); x = 0; y = height/2; } void draw() { background(0);

ellipse(x, y, 20, 20); x = x + 1; if (x > width) x = 0; } Jan 9, 2018 IAT 265 5 setup() and draw() are examples of callbacks g A callback function is defined by the programmer The callback gets called in response to some internal event You usually dont call callback functions directly with your own code. setup() and draw() are predefined within

Processing as to-be-called-if-defined Jan 9, 2018 IAT 265 6 Callbacks g A Callback is an example of the Observer Pattern more later! Jan 9, 2018 IAT 265 7 Controlling draw() g

frameRate() can be used to set the number of times per second that draw() is called frameRate(30) says to call draw() 30 times a second (if the computer is capable) g delay() delays execution for a certain number of milliseconds delay(250) delays for 250 milliseconds (1/4 of a sec.) You can use delay() or frameRate() to determine how fast you want draw() to be called frameRate() is probably easier g noLoop() tells the system to stop calling draw() If you want to, for example, turn off animation g loop() tells the system to start calling draw() again Use noLoop() and loop() together to turn repeated drawing on and off

Jan 9, 2018 IAT 265 8 Mouse variables g mouseX and mouseY variables that automatically contain the current mouse location pmouseX and pmouseY hold the previous location g mousePressed boolean variable that is true if a mouse button is down mouseButton value is LEFT, RIGHT or CENTER depending on which button is held down

Jan 9, 2018 IAT 265 9 Mouse callback methods g There are several built-in methods you can fill in to respond to mouse events mousePressed() mouseMoved() mouseReleased() mouseDragged() Example: void mousePressed() { if( mouseButton == LEFT ){

println( Left Mouse Button was pressed ); loop(); // activate drawing again } } Jan 9, 2018 IAT 265 10 If if statements introduce conditional execution if ( ) { // do this code } have one of two values: true or false Jan 9, 2018 IAT 265

11 Example boolean drawRect = true; boolean drawAnX = true; if (drawRect) { fill( 0, 200, 0 ); // fill with green rect( 30, 30, 40, 40 ); } if (drawAnX) { line( 0, 0, 100, 100 ); line( 100, 0, 0, 100 ); } Try changing the values of drawRect and drawAnX Jan 9, 2018 IAT 265

12 Example if / else boolean drawRect = true; boolean drawAnX = true; if (drawRect) { fill( 0, 200, 0 ); // fill with green rect( 30, 30, 40, 40 ); } else { fill( 0, 200, 220 ); // fill with cyan ellipse( 30, 30, 40, 40); } if (drawAnX) { line( 0, 0, 100, 100 );

line( 100, 0, 0, 100 ); } Jan 9, 2018 IAT 265 13 Nested if boolean drawRect = true; boolean drawEllipse = true, drawTriangle = true ; if (drawRect) { fill( 0, 200, 0 ); // fill with green rect( 30, 30, 40, 40 ); } else if( drawEllipse )

{ fill( 0, 200, 220 ); // fill with cyan ellipse( 30, 30, 40, 40); } else if( drawTriangle ) { triangle( 30, 30, 30, 80, 80, 30 ); } Jan 9, 2018 IAT 265 14

Loops g Sometimes you want to execute code multiple times E.g. draw() is being called in a loop g Java provides a number of looping mechanisms g They all test some boolean expression (just like an if statement does) and continue to execute code while the expression is true Jan 9, 2018 IAT 265

15 while loops while( ) { } g Repeatedly executes the code body while the boolean expression is true Jan 9, 2018 IAT 265 16 for loops for( ;

expression> ; { ) to execute each time in loop> } First executes the initialization statement g Then tests the boolean expression if true, executes the code once g Then repeats the following: execute final statement, test boolean expression execute true Jan 9, 2018

IAT 265 code if 17 Converting for to while Seeing how for loops can be converted to while loops helps you understand for for( ; ; ) { g } // is the same as

stmt> ; while( ) { ; } Jan 9, 2018 IAT 265 18 Get out of a loop for good behavior while( ) {

if( ) { break ; } } Jan 9, 2018 IAT 265 19 Reading time in Processing int hour() returns the hour (0 23) int minute() returns the minutes (0 59) int second() returns the seconds (0 59) int day()

returns the day of the month (1 -31) int month() returns the month (1 12) int year() returns the four digit year (e.g. 2004) float milliseconds() returns number of millis since start of app Jan 9, 2018 IAT 265 20 draw() has nothing to do with time g g

g The value returned by second() or milliseconds() has nothing to do with how often draw() is called In draw() you draw frames you dont know how often it will be called Put a println in loop to see how often it gets called long lastTimeLoopWasCalled = 0; void draw() { long milliseconds = millis(); println(milliseconds - lastTimeLoopWasCalled); lastTimeLoopWasCalled = milliseconds ; } Jan 9, 2018 IAT 265 21

Arrays g g An array is a contiguous collection of data items of one type Allows you to structure data Accessed by index number Jan 9, 2018 IAT 265 22 Effect of creating an int variable Code Effect Name: anInt, Type: int

// Single int int anInt; Name: anInt, Type: int // Put a value in the int 3 anInt = 3; Name: anInt, Type: int hello // Type error! Cant shove hello into an int anInt = hello; Jan 9, 2018 IAT 265

23 Creating an array of ints Code Effect Name: intArray, Type: int[] // declare int array int[] intArray; // initialize int array 0 1 2 3 4

0 0 0 0 0 each element has type int intArray = new int[5]; 0 1 2 3

4 3 0 0 0 0 0 1 2 3 4

3 0 5 0 0 // set first element intArray[0] = 3; // set third element intArray[2] = 5; Jan 9, 2018 IAT 265 24

Next g g g g Arrays Building Complex Shapes Translation and Rotation Pushing and Popping Jan 9, 2018 IAT 265 Building Special Shapes g g The beginShape() and endShape() functions allow us to draw irregular

shapes from any number of points we define. Many types of Shape: POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN, QUADS, QUAD_STRIP, POLYGON POLYGON will be the most useful. Jan 9, 2018 IAT 265 Building Polygons g beginShape( POLYGON ); Tells the program to start the polygon. g

vertex(x, y); Make as many calls to this as you have vertices in your polygon. g endShape( CLOSE ); Finishes the shape, connecting the last vertex to the first vertex to close the polygon, then colors it with the current fill() color. Jan 9, 2018 IAT 265 Building Polygons beginShape(); vertex(10, 50); (starts a new polygon, and begins at point (10, 50).)

Jan 9, 2018 IAT 265 Building Polygons vertex(20, vertex(30, vertex(80, vertex(40, 10); 40); 60); 80); (adds 4 more points to the polygon, and connects them in the order they are called.) Jan 9, 2018 IAT 265

Building Polygons endShape(CLOSE); (connects the last point to the first point, and fills the polygon.) Jan 9, 2018 IAT 265 Lets Use Arrays g Lets store the points that were drawing. int[] xvals = {10, 20, 30, 80, 40}; int[] yvals = {50, 10, 40, 60, 80}; beginShape(); for(int i = 0; i < xvals.length; i++) {

vertex( xvals[i], yvals[i] ); } endShape(CLOSE); Jan 9, 2018 IAT 265 Arrays g Use xvals and yvals arrays to draw the shape elsewhere beginShape(); for(int i = 0; i < xvals.length; i++) { vertex( xvals[i] +10, yvals[i] +10 ); } endShape(CLOSE); Jan 9, 2018 IAT 265

Not very general g g g What if you wanted to move by some other value? What if you wanted multiple copies of the same shape? Need a general method of moving polygons of some given shape Jan 9, 2018 IAT 265 Translation g Translation gives us another way of

drawing in a new location. It in essence, moves the point (0, 0) in our window. (0, 0) beginShape(); for(int i = 0; i < xvals.length; i++) { vertex(xvals[i], yvals[i]); } endShape(CLOSE); Jan 9, 2018 IAT 265 Translation g After the call to translate(), any drawing functions called will treat our new orange point as if it were (0, 0). (0, 0)

translate( 10, 10 ); Jan 9, 2018 (10, 10) IAT 265 Translation g g Draw same polygon again Now located x+10, y+10 (0, 0) (10, 10) beginShape(); for(int i = 0; i < xvals.length; i++) { vertex(xvals[i], yvals[i]); }

endShape(CLOSE); Jan 9, 2018 IAT 265 Rotation g g Much like Translation, Rotation moves our drawing space, so that we can draw at different angles. Most of the time, youll want to use Rotation in conjunction with Translation, because rotate() rotates the drawing window around the point (0, 0). Jan 9, 2018

IAT 265 Rotation g Lets look at an example without translation: (0, 0) rect(10, 10, 50, 50); Jan 9, 2018 IAT 265 Rotation g Make a variable with the value for 45 degrees in Radians. (0, 0)

float angle = radians(45); radians() takes an int or float degree value and returns a float radian value. Jan 9, 2018 IAT 265 Rotation g Rotate our drawing canvas 45 degrees around the origin. (0, 0) rotate(angle); Jan 9, 2018 IAT 265

Rotation g Draw the same square, now on our rotated coordinate system (0, 0) rect(10, 10, 50, 50); (We only get to see about half of our square, and it isnt really rotated in any satisfactory way.) Jan 9, 2018 IAT 265 Rotation g g

Lets try this from the start, using translation. Where should we translate to? The point around which we want to rotate. So lets try and rotate around the center of the square. This means moving the origin, and drawing the square around it. Jan 9, 2018 IAT 265 Rotation g Lets start with setting our rotation point: (0, 0) translate(35, 35);

(35, 35) Jan 9, 2018 IAT 265 Rotation g Now lets draw a square with this point at its center. (0, 0) rect( -25, -25, 50, 50); (35, 35) Jan 9, 2018 IAT 265

Rotation g Then lets do the same rotate we did last time. (0, 0) float angle = radians(45); rotate(angle); (35, 35) Jan 9, 2018 IAT 265 Rotation g Now when we draw the same square as before, it will have the same center point. (0, 0)

float angle = radians(45); rotate(angle); (35, 35) Jan 9, 2018 IAT 265 Rotation g g Try applying rotation to your animations using draw(). What variable will you want to iterate to make a shape rotate over time? Try making a custom polygon rotate instead of a square. Jan 9, 2018

IAT 265 Wait! How do I get back to normal?! g If you plan to do a lot of translations and rotations, it helps to know about the concepts of push and pop (0, 0) 0 (6 5) ,1 rt sta I ju ed

t ck ba go to ! nt h is wa et st fo r be he ow I re Jan 9, 2018

(35, 35) IAT 265 Pushing and Popping g Pushing is a way to say: Remember this orientation! pushMatrix(); g Popping is a way to say: Take me back to the way things once were! popMatrix(); Jan 9, 2018 IAT 265

Push & Pop g If we want to remember the original orientation pushMatrix(); translate(35,35); (0, 0) rotate( radians(45) ); rect(-25,-25,50,50); popMatrix(); rect(-25,-25,50,50); (35, 35) You can push and pop as many times as you want. Its like youre writing an address for the way things were on a card, and putting it on a stack each time you push and pop just takes the first card off the top of the stack.

IAT 265 Stack pushMatrix() and popMatrix() control a stack A stack stores chunks of data like a stack of plates in a cafeteria Last-In, First-out (LIFO) The graphics matrix stack lets you pushMatrix(), draw stuff, popMatrix() Returns drawing to state before pushMatrix Jan 9, 2018 IAT 265 Stack Push A Push B Push C

C B A Stack Base Pop -> yields C Pop -> yields B Pop -> yields A Jan 9, 2018 IAT 265 How is this useful? g g g You dont have to remember the math to reverse all the

translations and rotations youve done! You can make spiral shapes, then go back to normal! You can make drawings with limbs! (You dont want to have to calculate the angles of every finger, do you?) Jan 9, 2018 IAT 265 Review g g g g g

g g g setup() draw() Conditionals Loops Arrays Drawing Polygons Translation and Rotation pushMatrix and popMatrix Stacks Jan 9, 2018 IAT 265 Practice reading code g If code is a medium, then it can be both written and read

g Reading code reveals New programming constructs Strategies and techniques (design patterns) Style Jan 9, 2018 IAT 265 55

Recently Viewed Presentations

  • President IBEW 1687

    President IBEW 1687

    NOJAC's jurisdiction is defined by the IBEW Local 1687 Union Charter, issued by the IBEW International Union Office on February 8, 1951. The total geographical area under NOJAC's jurisdiction is just over . 272,658. square miles. NOJAC Apprentice System.
  • Central Limit Theorem - University of Houston

    Central Limit Theorem - University of Houston

    Find a 95% confidence interval estimate for the mean breaking strength. clt CENTRAL LIMIT THEOREM specifies a theoretical distribution formulated by the selection of all possible random samples of a fixed size n a sample mean is calculated for each...
  • Research: PowerPoint Presentation 60 points March 9-15 Introduction

    Research: PowerPoint Presentation 60 points March 9-15 Introduction

    Graphics should make a key concept clearer. Place your graphics in a similar location within each screen. Numbers and Statistics Big numbers are confusing. If you have more than 5 numbers on a slide, it's too many. Numbers and Stats...
  • Communication, collaboration, and delegation are frequently ...

    Communication, collaboration, and delegation are frequently ...

    Feedback leads to action, development of performance, or improved behavior. Ask the group to explain what feedback is. Give the group time to answer. Explain: The key word is information…i.e. hard facts, concrete data, observable examples of performance and behavior...
  • Insert presentation title here Arial Bold 33pt Insert second ...

    Insert presentation title here Arial Bold 33pt Insert second ...

    Enrol more than half of research higher degree students. Attract the highest performing Australian school students. Offer the lowest student-staff ratios of all Australian universities. Provide strong outcomes for international students. Group of Eight 2014. Go8 universities have nurtured every...
  • OmniSTAR BV Presentation by Ir. Hans Visser March

    OmniSTAR BV Presentation by Ir. Hans Visser March

    OmniSTAR BV Presentation by Ir. Hans Visser Technical Manager& New Business development March 2005 World-Wide real-time decimeter positioning and navigation
  • The Impact of Behavioral Economics on Investor Decision-Making

    The Impact of Behavioral Economics on Investor Decision-Making

    Classical Economics assumes that all investors have a positive discount rate. That discount rate is applied consistently across domains. If true. investors would accelerate good things, defer negative things. Frequently Violated
  • Unit Testing 101 - Winthrop University

    Unit Testing 101 - Winthrop University

    Unit Testing White Box Testing testing a module of code based on the source code Black Box Testing testing a module based on its description and/or the requirements specification Also called "functional" and "behavioral" testing Proof of Correctness mathematically-based analysis...