1 / 49

Continuation F rom Last Time

Continuation F rom Last Time. 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!. Change in Design Strategy.

Download Presentation

Continuation F rom Last Time

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Continuation From Last Time

  2. 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. 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. Example ColorPanelApp JFrame ColorPanel JSlider SliderListener 77 of 95

  5. 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. 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 00:01 00:02 00:00 00:03 00:04 00:05 00:06 00:07

  7. 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. 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 PolygonShapeextends Shape { • public PolygonShape(intnumSides) { • super(new cs015.geom.Polygon2D.Double(numSides)); • } • }

  9. Shape’s Methods • double getX() • double getY() • void setLocation(double x, double y) • double getWidth() • double getHeight() • void setSize(double width, double height) • intgetBorderWidth() • 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) • booleangetVisible() • 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. Lecture 11 Loops “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 “Life is just one damn thing after another.” -Mark Twain

  11. Turtle • Before we see loops, we need some tools • Turtle: will draw on the screen for us (based on Seymour Papert’sLogo, a language for beginners)* • Geometric Patterns: instructions for the turtle • 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. 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 Turtleclass

  13. /* 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. Drawing with Turtle • Need class to tell Turtle how to draw some basic shapes • First, determine what shapes we want • this lecture: square, random walk • next lecture: recursive spiral, tree, fractal • How will we code it? • create GeometricPatternsclass which defines methods for drawing each shape • doesn’t contain but associates a Turtle instance in _turtle • pass the reference in the constructor

  15. 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. A Repetitive Solution • Let’s write the drawSquaremethod in the GeometricPatternsclass • 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. A Repetitive Solution What if we wanted to make more general method that handles regular shapes such as pentagons or octagons? need to call forward and right for each side cannot fix how many sides we need in generic method There must be an easier way!

  18. Looping • Execute a section of code repeatedly- • uses booleans (true and false) as loop conditions; when booleanis false, loop condition equals exit condition and loop is terminated • as with conditionals, code in the loop can be a single line or many lines enclosed in curly braces • section of code executed is typically called loop’s body

  19. Looping • Three loop structures in Java • while loop • do while loop • for loop • Differ in relation between body and loop condition, as well as length of execution • do while loops execute body and then test condition; the others test condition before executing body • forloops run for a predetermined number of iterations, others run for indefinite amount of time Let’s look at whileloop first

  20. The while loop • Execute whilecertain condition is true • tests loop condition beforeexecuting body • if loop condition is falsefirst time through, the body is not executed at all while (<loop condition>) { <loop body> }

  21. The while loop • Examples of loop conditions: numClasses < 6 peopleStanding <= maxPeople this.checkAmount() <= acctBalance this.isSquare() //predicate, a method that returns a boolean Follow the same rules as conditions for if-elsestatements Multiple conditions can be combined using logical operators (and, or, not) (numClasses >= 3) && (numClasses <=5) (peopleStanding <= maxPeople) || (maxPeople < 50)

  22. A while Flowchart whileloops continue whilethe loop condition is true Loop condition can be any boolean expression <previous statement> Is <loop condition> true? Yes <loop body> <rest of program> No

  23. All Flow of Control Structures: 1-in, 1-out Benefits of predictable flow of control: much easier debugging compiler can optimize must better <previous statement> One way in Contrast with “spaghetti” code produced by having go to construct which allows for jumping to another line of code Go To Statement Considered Harmful letter by EdsgerDijkstra, published in Communications of the ACM in 1968 Go-to-less programming called “structured programming”- took a while to get traction Flow of Control Structure One way out <rest of program>

  24. So, just how bad is goto?

  25. public void randomWalk(){ DrawingPanelturtlePanel = _turtle.getPanel(); // while _turtle’s position is inside its // frame, move _turtle randomly while (turtlePanel.contains(_turtle.getLocation()){ _turtle.forward ((int) (Math.random()*15)); // cast to [0-14] _turtle.right ((int) (Math.random()*360)); //cast to [0-359] } } Syntax: Random Walk Using while Method of GeometricPatterns class: draws random lines while turtle is within its frame On last step of walk, _turtle will move forward out of panel the line is clipped by Swing since we don’t explicitly tell it to wrap around no point in continuing to walk outside the panel

  26. The do while Loop <previous statement> do while always executes loop body at least once by switching order of test and body <loop condition> is boolean exression Is <loop condition> true? Yes <loop body> <rest of program> No

  27. Example: Another Random Walk • Method of GeometricPatterns class: • draws random lines while turtle is within its frame • starts turtle in center of drawing panel, so first step guaranteed to be within drawing panel public void centeredRandomWalk(){ DrawingPanelturtlePanel = _turtle.getPanel(); // moves turtle to Frame’s center _turtle.home(); // moves turtle randomly within frame do { _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. do while vs. while In both loops stops executing body if loop condition is false must make sure loop condition becomes false by some computations to avoid an “infinite loop” infinite loop means your loop condition will never turn false- i.e., the exit condition never occurs (and your program “freezes up”!)

  29. do while vs. while What is the difference between these two? do while body always executed at least once loop condition tested at bottom of loop while (_andyIsAway) { _tas.takeADayOff(); } while may not execute at all loop condition tested before body; loop condition variables must be set before loop entry useful for screening bad data that might cause statements within loop to fail (e.g. while (ref != null) ) Condition tested before body do { _tas.takeADayOff(); } while(_andyIsAway); Body executes before condition is tested

  30. forloops • Most specialized loop construct: typically used to execute loop body a predetermined number of times • whileand do while loops can execute body for undetermined number of times; based on boolean for (<init-expr>; <loop condition>; <update>){ <loop body> } <init-expr> expression for setting initial value of loop counter (traditionally use single char. identifier; e.g., i) executed at start of loop code, i.e., only once, not for each time through the loop

  31. forloops • Most specialized loop construct: typically used to execute loop body a predetermined number of times • whileand do while loops can execute body for undetermined number of times; based on boolean for (<init-expr>; <loop condition>; <update>){ <loop body> } <loop condition> true or false test involves loop counter to determine if loop should execute checked at the start of every loop (including the first)

  32. forloops • Most specialized loop construct: typically used to execute loop body a predetermined number of times • whileand do while loops can execute body for undetermined number of times; based on boolean for (<init-expr>; <loop condition>; <update>){ <loop body> } <update> expression that modifies loop counter run at end of every <loop body>, just before returning to the top of the loop

  33. drawSquareRevisited • Better way of drawing square than explicitly drawing each side: public void drawSquare(intsideLen){ /* start with integer i initialized to 0; execute as long as i < 4; each execution increments i by 1 */ for (inti = 0; i < 4; i++){ _turtle.forward(sideLen); _turtle.right(90); } }

  34. forFlowchart • for loop has four parts • initialize value of counter • test loop condition • loop body • counter update <init-counter> <update-counter> Is <loop condition> true? Yes <rest of program> No <loop body>

  35. Choosing the right loop • forloop is called a definiteloop because you can typically predict how many ties it will loop • while and do while loops are indefiniteloops, as you do not know a priori when they will end • forloop 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 whileloop, but when code should execute at least once • When more than one type of loop wll solve problem, use the cleanest, simplest one

  36. Syntax: Nested loops • Loops, as with ifstatements, can be nested! • Example: drawFilledSquare public void drawFilledSquare(intsideLen){ // fill in concentric squares for (inti = 0; i < (sideLen/2); i++){ // drawSquare contains a loop this.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? we are dividing sideLenby 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. Syntax for Nested Loops Explained Turtle starts upright! • Turtle is represented by • What is the outer loop doing? • first draws outer square Rotate 90 degrees right! Move forward 1 unit! Rotate 90 degrees left! Move forward 1 unit! drawFilledSquaredraws concentric squares; each individual square is drawn using the nested loop • then the last 4 lines move turtle right and up 1 unit

  38. Decrementing Counter We can count backwards in our loop too just change the counter update expression in fact, we can update however we want public void countDownSeconds(){ /*change counter to decrement, and change the loop condition accordingly */ for(inti = 3; i > 0; i--){ timer.display(i); } } forloops end in one of two ways when counter value equals limit (for < or >) when counter value “goes past” limit (for <= or >=) thus, countDownSeconds() would display 4 seconds if used i >= 0 (not a good idea because the movie should play on the 0th second) Beware of such “off-by-one” errors!

  39. break • breakcauses immediate exit from a flow-of-control structure (e.g. while, do while, for, switch) • Example: for (inti = 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. continue When used in a while, for, or do while structure, continueskips remaining statements in body of that structure and proceeds with the next iteration of loop 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 whileand do while structures, execution continues by evaluating loop-continuation condition In forstructure, execution continues by incrementing counter and then evaluating loop condition

  41. continue Example // We’d like to try on shirts that hang on a rack for (inti = 0; i < 20; i++) { if(!rack.isShirtOnHanger(i)) { // If there’s no shirt on the current hanger, skip to the next iteration continue; } // Only do this if there’s a shirt on the hanger Shirt shirtToTry= rack.shirtOnHanger(i); // get the shirt this.tryOnShirt(shirtToTry); // try on shirt } // more code here

  42. Boolean Flags • A boolean flag is a boolean variable that denotes a condition (e.g., isDone, isWorking, isAvailable) • set in one place, tested in another • 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 forloop, using while): Notice that boolean flag is set within loop in previous slides, all checking was done through delegation (to methods that returned booleans) here, we do it ourselves (not practical) booleanisDone = false; inti = 0; while (!isDone){ i++; if(i == 5){ isDone = true; } }

  43. 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? Answer: body of loop is not executed Why? boolean is false for initial counter value public int sum() { inttempSum = 0; for (inti = 1; i < 1; i++) { tempSum+= i; } return tempSum; }

  44. Correct Example What about this loop? /*This method sums all numbers from 1 up to and including 10 */ public int sum() { inttempSum = 0; for (inti = 1; i<= 10; i++) { tempSum+= i; } return tempSum; } It will work!

  45. 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 numberis assigned an even value. Values from 2 to number-2 will be added (i.e. numberis excluded) Should be: Now, the value of number is included in the summation while (count <= number){ ... }

  46. Syntax: Other Loop Errors • Make sure test variables have proper values before loop is entered ... product = 0; do { product *=2; } while (product < 100); /* What will happen here? */ Make sure tests check proper conditions ... for (inti = 1; i != 100; i += 2) { // do something here } /* Will we ever get here? */

  47. Syntax: Other Loop Errors • ALWAYS HAND SIMULATE first, last, and typical cases through a loop to avoid off-by-one or infinite loop errors • the first and last cases of a loop’s execution are called boundary conditions or edge cases • hand simulation doesn’t just apply to loops – use it for everything! Trust us – it saves debugging time!

  48. 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. 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!

More Related