IAT 265 Lecture 2 Java Loops Arrays Processing

  • Slides: 55
Download presentation
IAT 265 Lecture 2: Java Loops, Arrays Processing setup, draw, mouse Shapes Transformations, Push/Pop

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

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

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() is a predefined Processing method that you define draw() is called repeatedly by

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);

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); 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

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 don’t 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 Pattern … more later! Jan

Callbacks g. A Callback is an example of the Pattern … more later! Jan 9, 2018 IAT 265 Observer 7

Controlling draw() g frame. Rate() can be used to set the number of times

Controlling draw() g frame. Rate() can be used to set the number of times per second that draw() is called – frame. Rate(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 frame. Rate() to determine how fast you want draw() to be called – frame. Rate() is probably easier g no. Loop() 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 no. Loop() and loop() together to turn repeated drawing on and off Jan 9, 2018 IAT 265 8

Mouse variables g mouse. X and mouse. Y – variables that automatically contain the

Mouse variables g mouse. X and mouse. Y – variables that automatically contain the current mouse location – pmouse. X and pmouse. Y hold the previous location g mouse. Pressed – boolean variable that is true if a mouse button is down – mouse. Button – 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

Mouse callback methods g There are several built-in methods you can fill in to respond to mouse events mouse. Pressed() mouse. Moved() mouse. Released() mouse. Dragged() Example: void mouse. Pressed() { if( mouse. Button == LEFT ){ println( “Left Mouse Button was pressed” ); loop(); // activate drawing again } } Jan 9, 2018 IAT 265 10

If if statements introduce conditional execution if ( <boolean expression> ) { // do

If if statements introduce conditional execution if ( <boolean expression> ) { // do this code } <boolean expressions> have one of two values: true or false Jan 9, 2018 IAT 265 11

Example boolean draw. Rect = true; boolean draw. An. X = true; if (draw.

Example boolean draw. Rect = true; boolean draw. An. X = true; if (draw. Rect) { fill( 0, 200, 0 ); // fill with green rect( 30, 40, 40 ); } if (draw. An. X) { line( 0, 0, 100 ); line( 100, 0, 0, 100 ); } Try changing the values of draw. Rect and draw. An. X Jan 9, 2018 IAT 265 12

Example if / else boolean draw. Rect = true; boolean draw. An. X =

Example if / else boolean draw. Rect = true; boolean draw. An. X = true; if (draw. Rect) { fill( 0, 200, 0 ); // fill with green rect( 30, 40, 40 ); } else { fill( 0, 200, 220 ); // fill with cyan ellipse( 30, 40, 40); } if (draw. An. X) { line( 0, 0, 100 ); line( 100, 0, 0, 100 ); } Jan 9, 2018 IAT 265 13

Nested if boolean draw. Rect = true; boolean draw. Ellipse = true, draw. Triangle

Nested if boolean draw. Rect = true; boolean draw. Ellipse = true, draw. Triangle = true ; if (draw. Rect) { fill( 0, 200, 0 ); // fill with green rect( 30, 40, 40 ); } else if( draw. Ellipse ) { fill( 0, 200, 220 ); // fill with cyan ellipse( 30, 40, 40); } else if( draw. Triangle ) { triangle( 30, 30, 80, 30 ); } Jan 9, 2018 IAT 265 14

Loops g Sometimes you want to execute code multiple times – E. g. draw()

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( <boolean exp. > ) { <code to execute each time> }

while loops while( <boolean exp. > ) { <code to execute each time> } g Repeatedly executes the code body while the boolean expression is true Jan 9, 2018 IAT 265 16

for loops for( <init. statement> ; <boolean expression> ; <final statement> ) { <code

for loops for( <init. statement> ; <boolean expression> ; <final statement> ) { <code 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 Jan 9, 2018 IAT 265 code if true 17

Converting for to while Seeing how for loops can be converted to while loops

Converting for to while Seeing how for loops can be converted to while loops helps you understand for(<init. stmt> ; <boolean exp> ; <final stmt> ) { g <code> } // is the same as <init. stmt> ; while( <boolean exp> ) { <code> <final stmt> ; } Jan 9, 2018 IAT 265 18

Get out of a loop for good behavior while( <boolean exp. > ) {

Get out of a loop for good behavior while( <boolean exp. > ) { <code to execute each time> if( <some other boolean exp. > ) { break ; } <more code to execute each time> } Jan 9, 2018 IAT 265 19

Reading time in Processing int hour() – returns the hour (0 – 23) int

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

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 don’t know how often it will be called Put a println in loop to see how often it gets called long last. Time. Loop. Was. Called = 0; void draw() { long milliseconds = millis(); println(milliseconds - last. Time. Loop. Was. Called); last. Time. Loop. Was. Called = milliseconds ; } Jan 9, 2018 IAT 265 21

Arrays g An array is a contiguous collection of data items of one type

Arrays g An array is a contiguous collection of data items of one type g Allows you to structure data – Accessed by index number Jan 9, 2018 IAT 265 22

Effect of creating an int variable Code Effect Name: an. Int, Type: int //

Effect of creating an int variable Code Effect Name: an. Int, Type: int // Single int an. Int; // Put a value in the int an. Int = 3; Name: an. Int, Type: int 3 // Type error! an. Int = “hello”; Name: an. Int, Type: int “hello” Can’t shove “hello” into an int Jan 9, 2018 IAT 265 23

Creating an array of ints Code Effect Name: int. Array, Type: int[] // declare

Creating an array of ints Code Effect Name: int. Array, Type: int[] // declare int array int[] int. Array; // initialize int array int. Array = new int[5]; // set first element int. Array[0] = 3; 1 2 3 4 0 0 0 each element has type int // set third element int. Array[2] = 5; Jan 9, 2018 0 IAT 265 0 1 2 3 4 3 0 0 0 1 2 3 4 3 0 5 0 0 24

Next g Arrays g Building Complex Shapes g Translation and Rotation g Pushing and

Next g Arrays g Building Complex Shapes g Translation and Rotation g Pushing and Popping Jan 9, 2018 IAT 265

Building Special Shapes g The begin. Shape() and end. Shape() functions allow us to

Building Special Shapes g The begin. Shape() and end. Shape() functions allow us to draw irregular shapes from any number of points we define. g Many types of Shape: – POINTS, LINES, TRIANGLE_STRIP, TRIANGLE_FAN, QUADS, QUAD_STRIP, POLYGON – POLYGON will be the most useful. Jan 9, 2018 IAT 265 …

Building Polygons g begin. Shape( POLYGON ); – Tells the program to start the

Building Polygons g begin. Shape( 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 end. Shape( 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 begin. Shape(); vertex(10, 50); (starts a new polygon, and begins at point

Building Polygons begin. Shape(); 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

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 end. Shape(CLOSE); (connects the last point to the first point, and fills

Building Polygons end. Shape(CLOSE); (connects the last point to the first point, and fills the polygon. ) Jan 9, 2018 IAT 265

Let’s Use Arrays g Let’s store the points that we’re drawing. int[] xvals =

Let’s Use Arrays g Let’s store the points that we’re drawing. int[] xvals = {10, 20, 30, 80, 40}; int[] yvals = {50, 10, 40, 60, 80}; begin. Shape(); for(int i = 0; i < xvals. length; i++) { vertex( xvals[i], yvals[i] ); } end. Shape(CLOSE); Jan 9, 2018 IAT 265

Arrays g Use xvals and yvals arrays to draw the shape elsewhere begin. Shape();

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

Not very general g What if you wanted to move by some other value?

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

Translation gives us another way of drawing in a new location. It in essence,

Translation gives us another way of drawing in a new location. It in essence, moves the point (0, 0) in our window. (0, 0) begin. Shape(); for(int i = 0; i < xvals. length; i++) { vertex(xvals[i], yvals[i]); } end. Shape(CLOSE); Jan 9, 2018 IAT 265

Translation g After the call to translate(), any drawing functions called will treat our

Translation g After the call to translate(), any drawing functions called will treat our new orange point as if it were (0, 0) translate( 10, 10 ); Jan 9, 2018 (10, 10) IAT 265

Translation g Draw same polygon again g Now located x+10, y+10 (0, 0) (10,

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

Rotation g Much like Translation, Rotation moves our drawing space, so that we can

Rotation g Much like Translation, Rotation moves our drawing space, so that we can draw at different angles. g Most of the time, you’ll 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 Let’s look at an example without translation: (0, 0) rect(10, 50, 50);

Rotation g Let’s look at an example without translation: (0, 0) rect(10, 50, 50); Jan 9, 2018 IAT 265

Rotation g Make a variable with the value for 45 degrees in Radians. (0,

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);

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)

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

Rotation g Let’s try this from the start, using translation. g Where should we

Rotation g Let’s try this from the start, using translation. g Where should we translate to? – The point around which we want to rotate. So let’s 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 Let’s start with setting our rotation point: (0, 0) translate(35, 35); (35,

Rotation g Let’s start with setting our rotation point: (0, 0) translate(35, 35); (35, 35) Jan 9, 2018 IAT 265

Rotation g Now let’s draw a square with this point at its center. (0,

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

Rotation g Then time. let’s do the same rotate we did last (0, 0)

Rotation g Then time. let’s do the same rotate we did last (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

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 Try applying rotation to your animations using draw(). What variable will you

Rotation g Try applying rotation to your animations using draw(). What variable will you want to iterate to make a shape rotate over time? g 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

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 ) 15 bac go to his! ant re t st w efo I ju rted b sta kt ow her e. I Jan 9, 2018 (35, 35) IAT 265

Pushing and Popping g Pushing is a way to say: “Remember this orientation!” push.

Pushing and Popping g Pushing is a way to say: “Remember this orientation!” push. Matrix(); g Popping is a way to say: “Take me back to the way things once were!” pop. Matrix(); Jan 9, 2018 IAT 265

Push & Pop g If we want to remember the original orientation… push. Matrix();

Push & Pop g If we want to remember the original orientation… push. Matrix(); translate(35, 35); rotate( radians(45) ); rect(-25, 50, 50); pop. Matrix(); rect(-25, 50, 50); (0, 0) (35, 35) You can push and pop as many times as you want. It’s like you’re 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 push. Matrix() and pop. Matrix() control a stack A stack stores chunks of

Stack push. Matrix() and pop. Matrix() 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 push. Matrix(), draw stuff, pop. Matrix() Returns drawing to state before push. Matrix Jan 9, 2018 IAT 265

Stack Push A Push B Push C C B A Stack Base Pop ->

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? You don’t have to remember the math to reverse all

How is this useful? You don’t have to remember the math to reverse all the translations and rotations you’ve done! g You can make spiral shapes, then go back to normal! g You can make drawings with limbs! g (You don’t want to have to calculate the angles of every finger, do you? ) Jan 9, 2018 IAT 265

Review setup() draw() g Conditionals g Loops g Arrays g Drawing Polygons g Translation

Review setup() draw() g Conditionals g Loops g Arrays g Drawing Polygons g Translation and Rotation g push. Matrix and pop. Matrix g Stacks g Jan 9, 2018 IAT 265

Practice reading code g If code is a medium, then it can be both

Practice reading code g If code is a medium, then it can be both written and g Reading code reveals read – New programming constructs – Strategies and techniques (design patterns) – Style Jan 9, 2018 IAT 265 55