49
1 of 47 Continuation From Last Time

0 of 47 Continuation From Last Time 1 of 47 Your Next Project: Cartoon! ●You’ll be building a Swing application that displays your own custom “cartoon”,

Embed Size (px)

Citation preview

1 of 47

Continuation From Last Time

2 of 47

Your Next Project: Cartoon!

● You’ll be building a Swing application that displays your own custom “cartoon”, much like the examples in this lecture

● But your cartoon will be animated!

3 of 47

Change in Design Strategy • Previously, because we did not use Swing directly, we had you make a

“top-level” class inside the App. ie. TASafeHouse.• Now that we do have graphics, a slight change of design, as shown in the

3 examples in lecture 9.• We no longer have a top-level class named for the program, we create in

the App a JFrame and a MainPanel, and add the MainPanel to the JFrame.• Thus, JFrame and MainPanel are peers in the logical sense, but the

MainPanel is contained graphically inside the JFrame, which should be seen as the Window in which the action takes place.

• The MainPanel will likely create subpanels for Shapes and various controls.

• This will all be gone over again in the Help Session.

4 of 47

Example

ColorPanelApp

JFrame ColorPanel

JSlider SliderListener

77 of 95

5 of 47

Animation• How can we animate our alien?

• As in film and video animation, we can create apparent motion with many small changes in position

• If we move fast enough and in small enough increments, we get smooth motion

• Same goes for size, orientation, shape change, etc…

-all time-varying attributes are called “behaviors”

6 of 47

Animation

• How to create incremental change?- We need a timer that emits “ticks”

• We also need an object to listen for ticks from the timer and respond appropriately

7 of 47

How to use the TA’s Shape package

• Shape is an abstract class that takes a RectangularShape in its constructor

• When you subclass Shape, you should pass in a RectangularShape when you call super()

- Ex) super(new java.awt.geom.Rectangle2D.Double());

• The TAs have provided you with some shape classes that you can use:

- java.awt.geom.Rectangle2D.Double - java.awt.geom.Ellipse2D.Double

• But what if you want triangles, pentagons, dodecagons??

8 of 47

Polygons

• The TAs have created a class that models a polygon and takes an int in its constructor that represents the number of sides of your shape

public class TriangleShape extends Shape {public TriangleShape() {

super(new cs015.geom.Polygon2D.Double(3));}

}And public class PolygonShape extends Shape {

public PolygonShape(int numSides) {super(new cs015.geom.Polygon2D.Double(numSides));

} }

9 of 47

Shape’s Methods• double getX()• double getY()• void setLocation(double x, double y)• double getWidth()• double getHeight()• void setSize(double width,

double height)• int getBorderWidth()• void setBorderWidth(int width)• double getRotation()• void setRotation(double degrees)

• Color getBorderColor()• void setBorderColor(Color c)• Color getFillColor()• void setFillColor(Color c)• void setColor(Color c)• boolean getVisible()• void setVisible(boolean visible)• void setTransparency(int

transparency)• void paint(Graphics brush)• boolean contains(java.awt.Point p)• void react()

See the handout for more information on the TA’s Shape package!

10 of 47

Lecture 11Loops

“Life is just one damn thing after another.”

-Mark Twain

“Life isn’t just one damn thing after another… it’s the same damn thing

over and over and over again.”-Edna St. Vincent Millay

11 of 47

Turtle ● Before we see loops, we need some tools

o Turtle: will draw on the screen for us (based on Seymour Papert’s Logo, a language for beginners)*

o Geometric Patterns: instructions for the turtleo Reminiscent of our first Robot example…

● Turtles know where they are and what direction they are facing, can move and turn

● Turtles can draw lines behind them as they move around the screen, or just move w/o drawing

● Now let’s look at Turtle’s public interface*See his Mindstorms, a provocative book on how kids “learn by doing,” and also the instrumented Legos, Mindstorms

12 of 47

Turtle’s Public Interface (1 of 2)

public class Turtle extends gfx.Shape { // instance variables elided /* constructor for Turtle takes the panel where the

turtle “lives” as paramter to set up an association */ public Turtle(DrawingPanel panel) { // some code here, including storing panel } /* reset turtle to center panel */ public void home() { // some code here }/* turn right a specified number of degrees

*/public void right(int degrees) { // some code here}/* turn left a specified number of degrees */public void left(int degrees) { // some code here}// continued

● TAs have written a Turtle class

13 of 47

/* move forward a specified fistance, drawing a line as the turtle moves */public void forward(int distance) {

// some code here}/* move backward a specified distance, drawing a line as the turtle moves */public void back(int distance) {

// some code here}/* move turtle to a specified position without drawing a line */public void setLocation(java.awt.Point loc) {

// some code here}/* return turtle’s location */public java.awt.Point getLocation() {

// some code here}/* return turtle’s drawing panel */public DrawingPanel getPanel() {

// some code here}

Turtle’s Public Interface (2 of 2)

14 of 47

Drawing with Turtle

● Need class to tell Turtle how to draw some basic shapes

● First, determine what shapes we wanto this lecture: square,

random walko next lecture: recursive

spiral, tree, fractal

● How will we code it?o create GeometricPatterns class

which defines methods for drawing each shape

o doesn’t contain but associates a

Turtle instance in _turtleo pass the reference in the constructor

15 of 47

Drawing with Turtle

public class GeometricPatterns {

private Turtle _turtle; // draws each pattern

public GeometricPatterns(Turtle newTurtle) {_turtle = newTurtle;

}// methods for each geometric pattern to follow…

}

● Time for some code!

16 of 47

A Repetitive Solution● Let’s write the drawSquare method in the GeometricPatterns class

● Brute force: write line of code for each side

public void drawSquare(int sideLen) {_turtle.forward(sideLen);_turtle.right(90);_turtle.forward(sideLen);_turtle.right(90);_turtle.forward(sideLen);_turtle.right(90);_turtle.forward(sideLen);_turtle.right(90);

}

17 of 47

● What if we wanted to make more general method that handles regular shapes such as pentagons or octagons?o need to call forward and right for each sideo cannot fix how many sides we need in generic method

● There must be an easier way!

A Repetitive Solution

18 of 47

Looping

● Execute a section of code repeatedly-o uses booleans (true and false) as loop conditions; when

boolean is false, loop condition equals exit condition and loop is terminated

o as with conditionals, code in the loop can be a single line or many lines enclosed in curly braces

o section of code executed is typically called loop’s body

19 of 47

Looping● Three loop structures in Java

o while loopo do while loopo for loop

● Differ in relation between body and loop condition, as well as length of executiono do while loops execute body and then test condition; the others

test condition before executing bodyo for loops run for a predetermined number of iterations, others run for

indefinite amount of time● Let’s look at while loop first

20 of 47

The while loop

● Execute while certain condition is trueo tests loop condition before executing bodyo if loop condition is false first time through, the body is not

executed at all

while (<loop condition>) {<loop body>

}

21 of 47

The while loop● Examples of loop conditions:

numClasses < 6peopleStanding <= maxPeoplethis.checkAmount() <= acctBalancethis.isSquare() //predicate, a method that returns a boolean

● Follow the same rules as conditions for if-else statements

● Multiple conditions can be combined using logical operators (and, or, not)

(numClasses >= 3) && (numClasses <=5)

(peopleStanding <= maxPeople) || (maxPeople < 50)

22 of 47

A while Flowchart

● while loops continue while the loop condition is true

● Loop condition can be any boolean expression

<previous statement>

<rest of program>

<loop body>Is <loop

condition> true? Yes

No

23 of 47

All Flow of Control Structures: 1-in, 1-out

<previous statement>

Flow of Control Structure

<rest of program>

● Contrast with “spaghetti” code produced by having go to construct which allows for jumping to another line of codeo Go To Statement Considered Harmful letter

by Edsger Dijkstra, published in Communications of the ACM in 1968

● Go-to-less programming called “structured programming”- took a while to get traction

● Benefits of predictable flow of control:o much easier debuggingo compiler can optimize must better

One way in

One way out

24 of 47

So, just how bad is goto?

25 of 47

Syntax: Random Walk Using while● Method of GeometricPatterns class:

o draws random lines while turtle is within its frame

● On last step of walk, _turtle will move forward out of panelo the line is clipped by Swing since we don’t explicitly tell it to wrap aroundo no point in continuing to walk outside the panel

public void randomWalk(){DrawingPanel turtlePanel = _turtle.getPanel();// while _turtle’s position is inside its // frame, move _turtle randomlywhile (turtlePanel.contains(_turtle.getLocation()){

_turtle.forward ((int) (Math.random()*15)); // cast to [0-14]

_turtle.right ((int) (Math.random()*360)); //cast to [0-359]

}}

26 of 47

The do while Loop

● do while always executes loop body at least once by switching order of test and body

● <loop condition> is boolean exression

<previous statement>

<rest of program>

<loop body>

Is <loop condition> true? Yes

No

27 of 47

Example: Another Random Walk● Method of GeometricPatterns class:

o draws random lines while turtle is within its frameo starts turtle in center of drawing panel, so first step guaranteed

to be within drawing panelpublic void centeredRandomWalk(){

DrawingPanel turtlePanel = _turtle.getPanel();

// moves turtle to Frame’s center_turtle.home();

// moves turtle randomly within framedo {

_turtle.forward((int)(Math.random()*15));_turtle.right((int)Math.random()*360));

} while (panel.contains(_turtle.getLocation()));}

Note the semicolon at the end of while statement

28 of 47

do while vs. while

● In both loopso stops executing body if loop condition is falseo must make sure loop condition becomes false by some

computations to avoid an “infinite loop”o infinite loop means your loop condition will never turn false- i.e.,

the exit condition never occurs (and your program “freezes up”!)

29 of 47

do while vs. while● do while

o body always executed at least onceo loop condition tested at bottom of loop

● whileo may not execute at allo loop condition tested before body;

loop condition variables must be set before loop entry

o useful for screening bad data that might cause statements within loop to fail (e.g. while (ref != null) )

while (_andyIsAway) {

_tas.takeADayOff();}

do {

_tas.takeADayOff();} while(_andyIsAway);

What is the difference between these two?

Condition tested before body

Body executes before condition is tested

30 of 47

for loops● Most specialized loop construct: typically used to

execute loop body a predetermined number of timeso while and do while loops can execute body for

undetermined number of times; based on boolean

for (<init-expr>; <loop condition>; <update>){

<loop body>}● <init-expr>

o expression for setting initial value of loop counter (traditionally use single char. identifier; e.g., i)

o executed at start of loop code, i.e., only once, not for each time through the loop

31 of 47

for loops● Most specialized loop construct: typically used to

execute loop body a predetermined number of timeso while and do while loops can execute body for

undetermined number of times; based on boolean

for (<init-expr>; <loop condition>; <update>){

<loop body>}

● <loop condition>o true or falseo test involves loop counter to determine if loop should executeo checked at the start of every loop (including the first)

32 of 47

for loops● Most specialized loop construct: typically used to

execute loop body a predetermined number of timeso while and do while loops can execute body for

undetermined number of times; based on boolean

for (<init-expr>; <loop condition>; <update>){

<loop body>}

● <update>o expression that modifies loop countero run at end of every <loop body>, just before returning to the

top of the loop

33 of 47

drawSquare Revisited

● Better way of drawing square than explicitly drawing each side:

public void drawSquare(int sideLen){

/* start with integer i initialized to 0;

execute as long as i < 4; each execution

increments i by 1 */

for (int i = 0; i < 4; i++){_turtle.forward(sideLen);_turtle.right(90);

}}

34 of 47

for Flowchart

● for loop has four partso initialize value of

countero test loop conditiono loop bodyo counter update

<init-counter>

<rest of program>

<loop body>Is <loop

condition> true? Yes

No

<update-counter>

35 of 47

Choosing the right loop● for loop is called a definite loop because you can

typically predict how many ties it will loop● while and do while loops are indefinite loops, as you

do not know a priori when they will end● for loop is typically used for math-related loops like

counting finite sums● while loop is good for situations where boolean condition

could turn false at any time● do while loop is used in same type of situation as

while loop, but when code should execute at least once● When more than one type of loop wll solve problem, use

the cleanest, simplest one

36 of 47

Syntax: Nested loops● Loops, as with if statements, can be nested!● Example: drawFilledSquare

public void drawFilledSquare(int sideLen){

// fill in concentric squaresfor (int i = 0; i < (sideLen/2);

i++){// drawSquare contains a

loopthis.drawSquare(sideLen

– (2*i);/* note we can use loop

counter in body but never reset it there! */

// position turtle for next iteration

_turtle.right(90);_turtle.forward(1);_turtle.left(90);_turtle.forward(1);

}}

● What does this do?o we are dividing sideLen

by 2 in order to guarantee that each “inner square” that is drawn by drawSquare(…) is exactly one unit away on either side from the square immediately “outside” of it (hence, one+one = two)

37 of 47

Syntax for Nested Loops Explained

● Turtle is represented by● What is the outer loop doing?

o first draws outer square

Turtle starts upright!

drawFilledSquare draws concentric squares; each individual square is drawn using the nested loop

o then the last 4 lines move turtle right and up 1 unit

Rotate 90 degrees right!

Move forward 1 unit!

Rotate 90 degrees left!

Move forward 1 unit!

38 of 47

Decrementing Counter● We can count backwards in our loop too

o just change the counter update expressiono in fact, we can update however we want

● for loops end in one of two wayso when counter value equals limit (for < or >)o when counter value “goes past” limit (for <= or >=)o thus, countDownSeconds() would display 4 seconds if used i >=

0 (not a good idea because the movie should play on the 0th second)o Beware of such “off-by-one” errors!

public void countDownSeconds(){/*change counter to decrement, and change the loop condition

accordingly */for(int i = 3; i > 0; i--){

timer.display(i); }

}

39 of 47

break● break causes immediate exit from a flow-of-control

structure (e.g. while, do while, for, switch)● Example:for (int i = 0; i < 10; i++){

if(_cookieJar.getNumberOfCookies() == 0){break; //If there are no cookies left, we should break out

of the loop!}this.eatACookie();

} //Execution continues here after loop is done or after break statement is executed● Execution continues with first line of code after structure● There are other ways to do this loop…

40 of 47

continue

● When used in a while, for, or do while structure, continue skips remaining statements in body of that structure and proceeds with the next iteration of loopo useful if there is list of data that you are looping over and you

want to skip processing of data that is somehow “not allowed”

● In while and do while structures, execution continues by evaluating loop-continuation condition

● In for structure, execution continues by incrementing counter and then evaluating loop condition

41 of 47

continue Example

// We’d like to try on shirts that hang on a rackfor (int i = 0; i < 20; i++) {

if(!rack.isShirtOnHanger(i)) {// If there’s no shirt on the current hanger, skip to the next

iterationcontinue;

}// Only do this if there’s a shirt on the hangerShirt shirtToTry = rack.shirtOnHanger(i); // get the shirtthis.tryOnShirt(shirtToTry); // try on shirt

}// more code here

42 of 47

Boolean Flags● A boolean flag is a boolean variable that denotes a condition

(e.g., isDone, isWorking, isAvailable)o set in one place, tested in anothero similar to boolean methods, often starts with “is” or “has” by convention

● Boolean flags can also be used as the loop condition● Example (implementing a for loop, using while):

boolean isDone = false;int i = 0;while (!isDone){

i++;if(i == 5){

isDone = true;

}}

● Notice that boolean flag is set within loopo in previous slides, all checking was done

through delegation (to methods that returned booleans)

o here, we do it ourselves (not practical)

43 of 47

Empty Intervals● Example scenario: we want to keep a running sum of a

sequence of numbers● What happens if we try to add integers in this loop?

public int sum() {int tempSum = 0;for (int i = 1; i < 1; i++) {

tempSum += i;}return tempSum;

}

● Answer: body of loop is not executed

● Why?o boolean is false for

initial counter value

44 of 47

Correct Example

/*This method sums all numbers from 1 up to and including 10 */public int sum() {

int tempSum = 0;for (int i = 1; i <= 10; i++) {

tempSum += i;}return tempSum;

}

● What about this loop?

● It will work!

45 of 47

Off-by-one Errors● Occur when loop executes one too many or one too few times● Example: add even integers from 2 to some number, inclusive

...count = 2;result = 0;while (count < number){

result += count;count += 2;

}

● Produces incorrect result if number is assigned an even value. Values from 2 to number-2 will be added (i.e. number is excluded)

● Should be:while (count <= number){...}

● Now, the value of number is included in the summation

46 of 47

Syntax: Other Loop Errors

● Make sure test variables have proper values before loop is entered

● Make sure tests check proper conditions...for (int i = 1; i != 100; i += 2) {

// do something here}/* Will we ever get here? */

...product = 0;do {

product *=2;} while (product < 100);/* What will happen here? */

47 of 47

Syntax: Other Loop Errors

● ALWAYS HAND SIMULATE first, last, and typical cases through a loop to avoid off-by-one or infinite loop errorso the first and last cases of a loop’s execution are called boundary

conditions or edge caseso hand simulation doesn’t just apply to loops – use it for everything!

Trust us – it saves debugging time!

48 of 47

Which loop to use?● You want to send a candygram to each of

your twelve friends● Your job is to stand at the end of the bowling

alley and pick up all the pins, one by one, that have been knocked over

● Ask a question. Keep asking while the answer is incorrect

● Sleep until your clock reads 7:00AM or later

?

49 of 47

Announcements

• Cartoon is out! DQs due Sunday at 2PM.

• Help Session Sunday at 6PM in Barus and Holley 166

• Early handin is Thursday 10/16 at 11:59PM, on time is Saturday 10/18 at 10:00PM, and late is Monday 10/20 at 11:59PM.

• We will pick the best Cartoons and show them to the class. Be creative!