AP "Case Studies" A big program for AP students to understand

Slides:



Advertisements
Similar presentations
GridWorld Case Study The Classes A Summary by Jim Mims.
Advertisements

GridWorld Case Study Part 3 GridWorld Classes and Interfaces A Summary by Jim Mims.
GridWorld Case Study Part 2 Bug Variations A Summary by Jim Mims.
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
Critters A Study in Design Patterns. Design Patterns  Not specific algorithms or data structures  A general reusable solution to a common problem.
Using a different image than normal Multiple images for a class Controlling the mouse click Controlling the keys pressed Launching an input dialog box.
Chapter 13 – Aggregation, Composition, and Inheritance
Inheritance Inheritance is the process of using features (both attributes and methods) from an existing class. The existing class is called the superclass.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
GridWorld Case Study1 Barbara Ericson Georgia Tech Jan 2008.
Chapter 3 Vector Class. Agenda Design and Implementation of Vector class – add, get, set remove, copy, equals, ensureCapacity Hangman using Vector class.
© A+ Computer Science - Row = 0 Column = 0.
Inheritance Inheritance is the process of using features (both attributes and methods) from an existing class. The existing class is called the superclass.
GridWorld Case Study Barbara Ericson March 24, 2007.
Java Arrays  Java has a static array capable of multi-dimensions.  Java has a dynamic array, which is also capable of multi-dimensions.  The ArrayList.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© A+ Computer Science - Grid is an interface that details the behaviors expected of a grid. All its methods are abstract methods.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Teaching with the AP ® Marine Biology Simulation Case Study Materials mostly from: Alyce Brady(Case Study Author) Kathy Larson(Case Study Teachers' Guide.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
The GridWorld Case Study Program Section 1 - Overview of the Class Hierarchies Section 2 - The Actor Class Section 3 - The Rock and Flower Classes Section.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Building Java Programs Chapter 8 Lecture 8-3: Object state; Homework 8 (Critters) reading:
GridWorld Case Study The case study is a program that simulates actions and interactions of objects in a two- dimensional grid. During a single step of.
Polymorphism. ArrayList boxbugs; ArrayList critters; ArrayList kingCrabs; ArrayList workerants; boxbugs.get(i).act(); critters.get(i).act(); kingCrabs.get(i).act();
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
OOP Basics Classes & Methods (c) IDMS/SQL News
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
© A+ Computer Science - Visit us at Full Curriculum Solutions M/C Review Question Banks.
Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction.
© A+ Computer Science - Visit us at Full Curriculum Solutions M/C Review Question Banks.
GridWorld.
Exposure Java 2012 APCS Edition Chapter 13 Slides
Chapter 5 Hierarchies IS-A associations superclasses subclasses
GridWorld Part 4 Meet the Critters.
Agenda About Quiz ChameleonCritter class CrabCritter class homework.
Barbara Ericson Georgia Tech Jan 2008
CS Week 14 Jim Williams, PhD.
CSC 113 Tutorial QUIZ I.
Section 8.7 The Consequences of Scope.
Java Inheritance.
© A+ Computer Science - GridWorld © A+ Computer Science -
© A+ Computer Science - GridWorld © A+ Computer Science -
A closer look at the world
Inheritance.
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Building Java Programs
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
GridWorld Part 4 Meet the Critters.
© A+ Computer Science - GridWorld The GridWorld case study provides a graphical environment where visual objects inhabit and interact.
Greenfoot November 8, 2009.
© A+ Computer Science - GridWorld © A+ Computer Science -
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
More on Creating Classes
Chapter 8 Class Inheritance and Interfaces
Review of Previous Lesson
GridWorld Case Study.
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Chapter 11 Inheritance and Polymorphism Part 1
© A+ Computer Science - GridWorld © A+ Computer Science -
© A+ Computer Science - GridWorld © A+ Computer Science -
CMPE212 – Reminders Assignment 2 due next Friday.
Java Inheritance.
Review for Midterm 3.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
CS 240 – Advanced Programming Concepts
Presentation transcript:

AP "Case Studies" A big program for AP students to understand Approximately 20% of the possible points on the AP exam will come from case study questions First Case Study introduced in 1994: Directory Manager (Pascal) Big Int (C++) Marine Biology (C++) Marine Biology Simulation (Java) GridWorld (Java) New for 2008!

The Program Actors (e.g. Bugs, Rocks) are placed into a grid Each actor has a variety of attributes and behaviors Students modify actors and create new ones Jamie enhances the master/apprentice relationship aspect; provides information when Pat is confused, makes some suggestions showing great foresight, and, at the end, even offers to make needed changes to the graphical user interface.

The Chapters AB Experiment with existing program (run it) Write new classes that extend Bug Explore code needed to create actors Write new classes that extend Critter Grid data structures Chap 5: Alternative representations * interfaces * follow-up part-time job during school year * AB only AB

Bug.java The code for the Bugs is "buried" in the framework folder The Bug class has: a couple constructors act() turn() move() canMove()

Bug.java public void act() { if (canMove()) move(); else turn(); }

BoxBug.java The code for the BoxBugs is in the Projects folder public class BoxBug extends Bug { private int steps; private int sideLength; // and more java

BoxBug.java public BoxBug(int length) { steps = 0; sideLength = length; } //Note: sideLength is measured from //the centers of the grid cells, so //BoxBug(3) will leave 4 flowers on //each side

extending Bug In Chapter 2 you will extend Bug to make: CircleBug SpiralBug ZBug DancingBug

Runner classes constructs an ActorWorld and adds Actors to it When you write a new Actor class, you will also need to write a new Runner class to test it out

Creating a new type of Bug Add a new folder to the Projects folder Save a copy of BoxBug to your new folder. Make sure to give it a new name that ends with .java

Creating a new type of Bug Now save a copy of BoxBugRunner to your new folder. Make sure to also give it a new name that ends with .java Change the code in the two java files to use the new class names public class CircleBugRunner { public static void main(String[] args) ActorWorld world = new ActorWorld(); CircleBug bob = new CircleBug(6); bob.setColor(Color.ORANGE); world.add(new Location(5, 5), bob); world.show(); }

Creating a new type of Bug Before you run the program to test out your new Bug, choose Project | Project Properties and choose the correct runner class

Dancing Bugs A DancingBug is constructed with an array argument (the workbook calls it a parameter) public class CircleBugRunner { public static void main(String[] args) ActorWorld world = new ActorWorld(); int [] naTurns = {1,2,3}; DancingBug bob = new DancingBug(naTurns); bob.setColor(Color.ORANGE); world.add(new Location(5, 5), bob); world.show(); }

Dancing Bugs int [] naTurns = {1,2,3}; DancingBug bob = new DancingBug(naTurns); Everytime bob moves, he will first turn. His first move he will turn once. His second move he will turn twice His third move he will turn 3 times Then the pattern repeats His fourth move he will turn once. His fifth move he will turn twice His sixth move he will turn 3 times

Before Move One

After Move One

After Move Two

After Move Three

Dancing Bugs Your dancing bug should work with any array of any length int [] naTurns = {5,1,3,17,5}; DancingBug bob = new DancingBug(naTurns); You will need a DancingBug class, and a runner to test it

The DancingBug class public class DancingBug extends Bug { private int steps; private int[] naTurns; public DancingBug(int [] naT) steps = 0; naTurns = naT; } public void act() ???

The Location class Stores a location with a row and column Location(int row, int col) int getRow() int getCol() boolean equals(Object other) String toString() What would this display? Location one = new Location(4,5); Location two = new Location(3,5); System.out.println(one); System.out.println( two.getCol()==one.getCol()); System.out.println(two.equals(one));

The Location class Directions are in degrees clockwise from north Location.NORTH is 0 degrees Location.NORTHEAST is 45 degrees Location.EAST is 90 degrees What would this display? System.out.println(Location.SOUTH); System.out.println( Location.SOUTHEAST);

getAdjacentLocation() What would this display? Location loc1 = new Location(4,2); Location loc2 = loc1.getAdjacentLocation( Location.NORTH); System.out.println(loc2);

getDirectionToward() What would this display? Location loc1 = new Location(4,2); Location loc2 = new Location(3,2); int nDir = loc1.getDirectionToward(loc2); System.out.println(nDir);

What is the output of this program fragment? Location loc1 = new Location(2,3); Location loc2 = new Location(5,3); int nDir = loc1.getDirectionToward(loc2); System.out.println(nDir); Location loc3 = loc1.getAdjacentLocation(nDir); System.out.println(loc3); int nDir2 = nDir + Location.LEFT; System.out.println(nDir2); int nDir3 = nDir2 + Location.HALF_CIRCLE; System.out.println(nDir3); Location loc4 = loc1.getAdjacentLocation(nDir3); System.out.println(loc4);

The Grid interface Two classes implement Grid: BoundedGrid UnboundedGrid

Unbounded Grid Choose the type of grid from the World menu

Methods in the Grid interface boolean isValid(Location loc) E put(Location loc, E obj) E remove(Location loc) E get(Location loc) ArrayList <Location> getOccupiedLocations() ArrayList <Location> getValidAdjacentLocations(Location loc) ArrayList <Location> getEmptyAdjacentLocations(Location loc) ArrayList <Location> getOccupiedAdjacentLocations(Location loc) ArrayList <Location> getNeighbors(Location loc) int getNumRows() int getNumCols()

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); System.out.println(theGrid.getNumRows());

What is the output? 10 The default grid is 10 x 10 ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); System.out.println(theGrid.getNumRows()); 10 The default grid is 10 x 10

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); System.out.println( theGrid.isValid(new Location(10,3)));

What is the output? false ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); System.out.println( theGrid.isValid(new Location(10,3))); false

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); System.out.println( theGrid.get(new Location(3,3)));

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); System.out.println( theGrid.get(new Location(3,3))); BoxBug[location=(3, 3), direction=0, color=java.awt.Color[r=255,g=0,b=0]]

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); System.out.println( theGrid.getNeigbors(new Location(2,3)));

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); System.out.println( theGrid.getNeigbors(new Location(2,3))); BoxBug[location=(3, 3), direction=0, color=java.awt.Color[r=255,g=0,b=0]]

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getNeighbors(new Location(2,3)));

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getNeighbors(new Location(2,3))); [BoxBug[location=(1, 3),direction=0, color=java.awt.Color[r=255,g=0,b=0]], BoxBug[location=(3, 3),direction=0, color=java.awt.Color[r=255,g=0,b=0]]]

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getOccupiedAdjacentLocations( new Location(2,3)));

What is the output? [(1, 3), (3, 3)] Press any key to continue... ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getOccupiedAdjacentLocations( new Location(2,3))); [(1, 3), (3, 3)] Press any key to continue...

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getEmptyAdjacentLocations( new Location(2,3)));

What is the output? [(1, 4), (2, 4), (3, 4), (3, 2), (2, 2), (1, 2)] ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getEmptyAdjacentLocations( new Location(2,3))); [(1, 4), (2, 4), (3, 4), (3, 2), (2, 2), (1, 2)] Press any key to continue...

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getValidAdjacentLocations( new Location(2,3)));

What is the output? [(1, 3), (1, 4), (2, 4), (3, 4), ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); System.out.println( theGrid.getValidAdjacentLocations( new Location(2,3))); [(1, 3), (1, 4), (2, 4), (3, 4), (3, 3), (3, 2), (2, 2), (1, 2)] Press any key to continue...

What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); Rock mrSimon = new Rock(); world.add(new Location(4,5), mrSimon); System.out.println( theGrid.getOccupiedLocations());

What is the output? [(1, 3), (3, 3), (4, 5)] ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); BoxBug bob = new BoxBug(2); world.add(new Location(3,3), bob); BoxBug jane = new BoxBug(2); world.add(new Location(1,3), jane); Rock mrSimon = new Rock(); world.add(new Location(4,5), mrSimon); System.out.println(theGrid.getOccupiedLocations()); [(1, 3), (3, 3), (4, 5)] Press any key to continue...

Practice Quiz Question: What is the output? ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); System.out.println(theGrid.getNumCols()); Bug bob = new BoxBug(2); world.add(new Location(1,5), bob); BoxBug jane = new BoxBug(2); world.add(new Location(6,5), jane); Rock mrSimon = new Rock(); world.add(new Location(4,5), mrSimon); System.out.println(theGrid.getOccupiedLocations()); System.out.println( theGrid.getEmptyAdjacentLocations(new Location(5,5))); theGrid.getValidAdjacentLocations(new Location(0,4))); theGrid.getValidAdjacentLocations(new Location(0,4)).size());

The Actor class Actors have accessor methods that access the color, direction, Grid and Location ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); Bug bob = new BoxBug(3); world.add(new Location(1,5), bob); System.out.println(bob.getColor()); //java.awt.Color[r=255,g=0,b=0] System.out.println(bob.getDirection()); //0 System.out.println(bob.getGrid()); /*{(1, 5)=BoxBug[location=(1, 5),direction=0,color=java.awt.Color[r=255,g=0,b=0]]}*/ System.out.println(bob.getLocation()); //(1,5)

BAD, BAD, BAD! Don't do this! Don't place Actors using the grid's put method ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); Bug bob = new BoxBug(3); world.add(new Location(1,5), bob); bob.removeSelfFromGrid(); theGrid.put(new Location(2,6),bob); System.out.println(bob.getLocation()); //Displays null!

Moving Actiors This is ok! ActorWorld world = new ActorWorld(); Grid theGrid = world.getGrid(); Bug bob = new BoxBug(3); world.add(new Location(1,5), bob); bob.moveTo(new Location(2,6)); System.out.println( bob.getLocation()); //Displays (2,6)

p 23, Do you know? Name three properties of every actor. When an actor is constructed, what is its direction and color?

The Bug class Bugs (like Rocks and Flowers) extend the Actor class ActorWorld world = new ActorWorld(); Object bob = new BoxBug(3); System.out.println(bob instanceof Bug); System.out.println(bob instanceof Actor); System.out.println(bob instanceof Rock); instanceof gives true if the Object is an instance of that class

The inheritance hierarchy Actor Bug Flower Rock BoxBug

Jumper project Group project at end of Chapter 3--Feel free to choose some partners, or work on it yourself Jumpers move 2 spaces and jump over other Actors that are in the way You'll need a JumperRunner and Jumper class Put them in a Jumper folder in the projects No one correct way, your Jumper may behave differently than another groups

canMove() public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }

What's the output? ActorWorld world = new ActorWorld(); Bug bob = new BoxBug(3); world.add(new Location(2,2), bob); bob.removeSelfFromGrid(); System.out.println(bob.getGrid());

canMove() if (gr == null) return false; public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }

canMove() Location next = loc.getAdjacentLocation(getDirection()); public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }

canMove() Actor neighbor = gr.get(next); return (neighbor == null) || public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }

move() from Bug public void move() { Grid<Actor> gr = getGrid(); if (gr == null) return; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (gr.isValid(next)) moveTo(next); else removeSelfFromGrid(); Flower flower = new Flower(getColor()); flower.putSelfInGrid(gr, loc); }

What is the output? Object bob = new Flower(); System.out.println( bob instanceof Flower); System.out.println(bob instanceof Rock); System.out.println(bob instanceof Bug); bob instanceof Actor); bob instanceof Object);

Jumper import statements My Jumper class had the following imports: import info.gridworld.actor.*; import info.gridworld.grid.*; My JumperRunner class used: import info.gridworld.grid.Location;

Chapter 4 Critters process a list of other actors and then move getActors() gets a list of all the neighboring actors (max 8) Bugs don't pay attention to other actors, they just check to see if the location they want to move to is available

CritterRunner public class CritterRunner { public static void main(String[] args) ActorWorld world = new ActorWorld(); world.add(new Location(7, 8), new Rock()); world.add(new Location(3, 3), new Rock()); world.add(new Location(2, 8), new Flower(Color.BLUE)); world.add(new Location(5, 5), new Flower(Color.PINK)); world.add(new Location(1, 5), new Flower(Color.RED)); world.add(new Location(7, 2), new Flower(Color.YELLOW)); world.add(new Location(4, 4), new Critter()); world.add(new Location(5, 8), new Critter()); world.show(); }

Any guesses what the Critter will do?

What happened?

Critter public class Critter extends Actor { /** * A critter acts by getting a list of other actors, processing that list, * getting locations to move to, selecting one of them, and moving to the * selected location. */ public void act() if (getGrid() == null) return; ArrayList<Actor> actors = getActors(); processActors(actors); ArrayList<Location> moveLocs = getMoveLocations(); Location loc = selectMoveLocation(moveLocs); makeMove(loc); }

How does a Critter "process" it's neighbors? public void processActors(ArrayList<Actor> actors) { for (Actor a : actors) if (!(a instanceof Rock) && !(a instanceof Critter)) a.removeSelfFromGrid(); }

How does a Critter decide which location to move to? public ArrayList<Location> getMoveLocations() { return getGrid(). getEmptyAdjacentLocations(getLocation()); } public Location selectMoveLocation( ArrayList<Location> locs) int n = locs.size(); if (n == 0) return getLocation(); int r = (int) (Math.random() * n); return locs.get(r);

How does a Critter decide which location to move to? public void makeMove(Location loc) { if (loc == null) removeSelfFromGrid(); else moveTo(loc); }

Any guesses what the Critter will do?

What happened?

What's going to happen?

Which actor moved first?

Practice Quiz Question How many objects will be removed after one step? Right click on this slide and choose Pointers Options | Ballpoint pen. Draw a possible resulting arrangement. X out any actors that are moved or removed.

Chameleon Critters What do you think the Chameleon will do?

Chameleon Critters What do you think the Chameleon will do?

Chameleon Critters Critters process a list of other actors and then move Chameleons process a list of neighbors by randomly choosing a neighbor and assuming its color Then they move

Chameleon Critters public void processActors( ArrayList<Actor> actors) { int n = actors.size(); if (n == 0) return; int r = (int) (Math.random() * n); Actor other = actors.get(r); setColor(other.getColor()); }

Practice Quiz Questions What is the probability that the Chameleon will be red after it acts? that it will be blue after it acts?

The red critter is a chameleon Look carefully for a difference in the way a chameleon moves compared to a "normal" critter

The red critter is a chameleon Look carefully for a difference in the way a chameleon moves compared to a "normal" critter

super classes and sub classes class ChameleonCritter extends Critter Critter is the super class ChameleonCritter is the sub class the sub class extends the super class

super //from ChameleonCritter.class public void makeMove(Location loc) { setDirection( getLocation().getDirectionToward(loc)); super.makeMove(loc); }

super() Super has two meanings: With parenthesis, it calls the super class constructor (e.g. super() ) With a dot, it calls the member methods of the super class (e.g. super.makeMove(loc) )

What is the output? public class SuperDemo extends Applet { public void init() { SuperClass bob = new SuperClass(5); SubClass sue = new SubClass(); System.out.println(bob.myInt); System.out.println(sue.myInt); System.out.println(sue.mySecondInt); } class SuperClass{ int myInt; SuperClass(int nInt){ System.out.println("Building a Super"); myInt = nInt; class SubClass extends SuperClass{ int mySecondInt; SubClass(){ super(3); System.out.println("Building a Sub"); mySecondInt = 4;

What's wrong with SubClass b = new SubClass(3);? class SuperClass{ int myInt; SuperClass(int nInt){ myInt = nInt; } class SubClass extends SuperClass{ int mySecondInt; SubClass(){ super(3); mySecondInt = 4;

Construtors are NEVER inherited Construtors are NEVER inherited. To call a constructor of the super class you have to call super on the first line of the sub class constructor class SuperClass{ int myInt; SuperClass(int nInt){ myInt = nInt; } class SubClass extends SuperClass{ int mySecondInt; SubClass(){ super(3); mySecondInt = 4;

More on super() Every time a new instance of a sub class is created, we start by building a super class SeaHorse extends Fish{…} SeaHorse Bob = new SeaHorse();

More on super() On the very first line of the SeaHorse constructor, there is an "invisible" call to super(); class SeaHorse extends Fish{ public SeaHorse(){ super(); //invisible //lots more java }

More on super() The call is to the default, no argument constructor If we want to call a different version of the constructor, one with arguments, we need to do it on the very first line of the constructor class SeaHorse extends Fish{ public SeaHorse(){ super(??,??); }

What happens if a sub class doesn’t have a constructor? Does it inherit the constructor from the super class? For instance, look at the code for the ChameleonCritter—there's no constructor!

What happens if a sub class doesn’t have a constructor? Does it inherit the constructor from the super class? NO NO NO! Java generates an "invisible" constructor that calls super() class ChameleonCritter extends Critter{ public Critter(){ //invisible super(); } //lots more Java

Buidling new Critters Five methods that may need to be overwritten: getActors(); processActors(); getMoveLocations(); selectMoveLocations(); makeMove();

CrabCritters When Crab critters look for something to eat, they don't look at all the neighbors, just the ones in front (front, right-front and left front) What needs to overwritten getActors() or processActors()?

How does a Critter "process" it's neighbors? public void processActors(ArrayList<Actor> actors) { for (Actor a : actors) if (!(a instanceof Rock) && !(a instanceof Critter)) a.removeSelfFromGrid(); }

How does a Critter get a list of it's neighbors? public ArrayList<Actor> getActors() { return getGrid().getNeighbors(getLocation()); }

Since a Critter and Crab both process the neighbors by eating them, the only difference is the list. getActors() needs to be changed, not processActors() public ArrayList<Actor> getActors() { ArrayList<Actor> actors = new ArrayList<Actor>(); int[] dirs = { Location.AHEAD, Location.HALF_LEFT, Location.HALF_RIGHT }; for (Location loc : getLocationsInDirections(dirs)) Actor a = getGrid().get(loc); if (a != null) actors.add(a); } return actors;

Moving Critters Crab Critters move differently: A CrabCritter can move only to the right or to the left. If both are open, it chooses randomly. (if it can't move it turns 90 degrees) What needs to be overwritten? getMoveLocations(); selectMoveLocations(); makeMove();

Moving Critters Since Critters choose locations randomly, only 1 and 3 need to be changed getMoveLocations(); selectMoveLocations(); makeMove();

Image Information You can create an image for any class you create in GridWorld. The image must have the exact same name as the class. Case matters! public class RockHound ..... RockHound.gif IMPORTANT: Save the image in the same folder as the class file, not the java file!

Image Information The class files for my projects are in the GridWorldCode folder in my JCreator Projects folder (yours is probably Z:\Java\GridWorldCode)

Image Information The picture will load automatically GridWorld will "tint" the picture depending on the actors color setcolor(null) will prevent the image from being tinted

What is the output of this program? public class ThisDemo { public static void main(String[] args) { WhatsIt first = new WhatsIt(); WhatsIt second = new WhatsIt(); first.combine(second); System.out.println(first.getNum()); } class WhatsIt{ private int myNum; public WhatsIt(){myNum = 4;} public int getNum(){return myNum;} public void combine(WhatsIt one){ myNum = myNum + one.myNum;

What is the output of this program? public class ThisDemo { public static void main(String[] args) { WhatsIt first = new WhatsIt(); WhatsIt second = new WhatsIt(); first.combine(second); System.out.println(first.getNum()); } class WhatsIt{ private int myNum; public WhatsIt(){myNum = 4;} public int getNum(){return myNum;} public void combine(WhatsIt one){ myNum = myNum + one.myNum;

Problem: Write a new WhatsIt member method called doubleIt Problem: Write a new WhatsIt member method called doubleIt. doubleIt combines a WhatsIt with itself WhatsIt first = new WhatsIt(); first.doubleIt(); System.out.println(first.getNum()); //8 class WhatsIt{ private int myNum; public WhatsIt(){myNum = 4;} public int getNum(){return myNum;} public void combine(WhatsIt one){ myNum = myNum + one.myNum; } public void doubleIt(){ combine(???);

Problem: Can we use first as the argument? WhatsIt first = new WhatsIt(); first.doubleIt(); System.out.println(first.getNum()); //8 class WhatsIt{ private int myNum; public WhatsIt(){myNum = 4;} public int getNum(){return myNum;} public void combine(WhatsIt one){ myNum = myNum + one.myNum; } public void doubleIt(){ combine(first); //doesn't work

the keyword this means "the object in front of the dot". WhatsIt first = new WhatsIt(); first.doubleIt(); System.out.println(first.getNum()); //8 class WhatsIt{ private int myNum; public WhatsIt(){myNum = 4;} public int getNum(){return myNum;} public void combine(WhatsIt one){ myNum = myNum + one.myNum; } public void doubleIt(){ combine(this); //Now it works!

this is a reference to the object that called the method think: the object in front of the dot

this The scope of bob is shown in yellow We can't use bob in the Thingy class public class ThisDemo extends Applet { private Thingy bob public void init() { bob = new Thingy(); } public void paint(Graphics g) { bob.display(); class Thingy{ private int myNum; public Thingy(){myNum = 3;} public void display(){ System.out.println(bob.myNum); //doesn't work

this myNum by itself means "the myNum that belongs to the object that called the method" public class ThisDemo extends Applet { private Thingy bob public void init() { bob = new Thingy(); } public void paint(Graphics g) { bob.display(); class Thingy{ private int myNum; public Thingy(){myNum = 3;} public void display(){ System.out.println(myNum); //OK

this this.myNum means the same as just myNum public class ThisDemo extends Applet { private Thingy bob public void init() { bob = new Thingy(); } public void paint(Graphics g) { bob.display(); class Thingy{ private int myNum; public Thingy(){myNum = 3;} public void display(){ System.out.println(this.myNum); //OK

this You may use this anywhere you want to refer to the object in front of the dot There is only one situation where you have to use this: When you want to pass the object in front of the dot as an argument Good Style: Don't use this unless you need to

What is the output of this program? public class ThisDemo { public static void main(String[] args) { TryIt first = new TryIt("hello"); TryIt second = new TryIt("world"); second.modify(first); System.out.println(second.getName()); first.mystery(); System.out.println(first.getName());} } class TryIt{ private String myName; public TryIt(String sName){myName = sName;} public String getName(){return myName;} public void modify(TryIt one){ myName = one.myName + "-" + myName; public void mystery(){modify(this);}

When making new Actors The following import statements seem to give you everything you could possibly need import info.gridworld.actor.*; import info.gridworld.grid.*; import java.awt.Color; import java.util.ArrayList; Make sure that you make a new folder for your new Actor class and a new Runner class as well Make sure the runner is putting instances of your new Actor class into the world!

BlusterCritter Has a new private int c for courage Counts all the Critters within 2 steps: If number of critters< c, color brightens If number of critters>= c, color darkens

BlusterCritter Has a new private int c for courage Counts all the Critters within 2 steps: If number of critters< c, color brightens If number of critters>= c, color darkens Which methods need to be overwritten? getActors(); processActors(); getMoveLocations(); selectMoveLocations(); makeMove();

BlusterCritter getActors(); will get a list of all the Critters within 2 steps processActors(); will check the size of the list and lighten or darken accordingly

BlusterCritter public ArrayList<Actor>getActors() { ArrayList <Actor> theList = new ArrayList<Actor>(); ?? return theList; } We need to check 24 locations 5x5 = 25 minus the one location the BlusterCritter is in

BlusterCritter for(int nRow=-2;nRow<=2;nRow++) public ArrayList<Actor>getActors() { ArrayList <Actor> theList = new ArrayList<Actor>(); for(int nRow=-2;nRow<=2;nRow++) for(int nCol=-2;nCol<=2;nCol++) //check all 25 } //remove ourself return theList;

How could I remove the BlusterCritter from the list? public ArrayList<Actor>getActors() { ArrayList <Actor> theList = new ArrayList<Actor>(); for(int nRow=-2;nRow<=2;nRow++) for(int nCol=-2;nCol<=2;nCol++) ?? } theList.remove( ?? ); return theList;

Brightening can make an Exception red = (int) (c.getRed() + 5); green = (int) (c.getGreen() +5); blue = (int) (c.getBlue() +5); ?? setColor(new Color(red, green, blue));

QuickCrab moves two spaces if possible, otherwise moves as a "normal" Crab What should be overwritten? getActors(); processActors(); getMoveLocations(); selectMoveLocations(); makeMove();

QuickCrab getMoveLocations(); moves two spaces if possible, otherwise moves as a "normal" Crab What should be overwritten? getActors(); processActors(); getMoveLocations(); selectMoveLocations(); makeMove();

getMoveLocations() ArrayList<Location> locs = public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); ??? return locs; }

getMoveLocations() //Find the location one to the left public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left return locs; }

getMoveLocations() //Find the location one to the left public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left //Find the location two to the left return locs; }

getMoveLocations() //Find the location one to the left public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left //Find the location two to the left //if they are both valid and unoccupied, add two to the left to the list return locs; }

getMoveLocations() //Find the location one to the left public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left Location oneLeft = ??? return locs; }

getMoveLocations() ???.getAdjacentLocation(???); public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left Location oneLeft = ???.getAdjacentLocation(???); return locs; }

getMoveLocations() getLocation().getAdjacentLocation(???); public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left Location oneLeft = getLocation().getAdjacentLocation(???); return locs; }

getMoveLocations() getLocation().getAdjacentLocation( public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //Find the location one to the left Location oneLeft = getLocation().getAdjacentLocation( getDirection() + Location.LEFT); return locs; }

What if two to the left and two to the right are both unavailable? public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //lots of java if(locs.size == 0) ??? else return locs; }

What if two to the left and two to the right are both unavailable? public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); //lots of java if(locs.size == 0) return /* normal crab locations */ else return locs; }

KingCrab when processing actors, it moves them "one away" If they can't move "one away" they are removed

KingCrab when processing actors, it moves them "one away" If they can't move "one away" they are removed What should be overwritten? getActors(); processActors(); getMoveLocations(); selectMoveLocations(); makeMove();

public class superWhatOutput { public static void main(String args[]) Thingy[] aBunch = new Thingy[5]; for(int nI = 0; nI < aBunch.length; nI++) if(nI % 2 == 0) aBunch[nI] = new Thingy(nI); else aBunch[nI] = new Widget(nI,'x'); aBunch[nI].write(); } class Thingy private int myNum; public Thingy(int nNum){myNum = nNum;} public int getNum(){return myNum;} public String toString() if(myNum%3 == 0) return "three"; return "no"; public void write() System.out.println(this); class Widget extends Thingy { private char myLetter; public Widget(int nNum, char cLetter) super(nNum); myLetter = cLetter; } public String toString() return myLetter + super.toString();

aBunch 1x 2 3x 4 index 1 2 3 4

for(int nI = 0; nI < aBunch.length; nI++) aBunch[nI].write(); aBunch 1x 2 3x 4 index 1 2 3 4

for(int nI = 0; nI < aBunch.length; nI++) aBunch[nI].write(); public void write() { System.out.println(this); } aBunch 1x 2 3x 4 index 1 2 3 4

for(int nI = 0; nI < aBunch.length; nI++) aBunch[nI].write(); public void write() { System.out.println(this); } public String toString() //thingy if(myNum%3 == 0) return "three"; else return "no"; public String toString() //widget return myLetter + super.toString(); aBunch 1x 2 3x 4 index 1 2 3 4