RobotsControl

Uploaded from authorPOINTLite
Views:
 
Category: Education
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Creating Class Behaviors: 

Creating Class Behaviors In the Robot world 1 mile = 8 blocks Suppose we want a robot to run a marathon (26+ miles)? Does our program have to have (26+) * 8 move() statements? Wouldn’t it be nice to tell a robot to run a marathon Karel.runMarathon();

Building a Marathon-Running Robot: 

Building a Marathon-Running Robot Let us build a robot to run a marathon If we define a moveMile() behavior as eight move() messages we can reduce the size of our program by (26+) * 8 / 8 or down to 26+ instructions Can we do better than these 26 instructions? we can specify as many behaviors as we need for a class of robots Can we think of other behaviors to further simplify the problem? HAS – A relationships Marathon Robot HAS A move mile behavior or characteristic (that is different from a ur-Robot)

Defining New Classes of Robots: 

Defining New Classes of Robots To build a new class of robots, we include a class specification in a new file of our program The general form of this specification: class <new-class-name> extends <old-class-name> { <list-of-new-methods> }

Specification Details: 

Specification Details Reserved Words and symbols class extends braces { } We must replace the elements in angle brackets < > appropriately <new-class-name> what do we call this new type of robot? <old-class-name> what old robot to add features to? <list-of-new-methods> list of new features

Naming Things: 

Naming Things In developing the names for robots and new methods any uppercase and lowercase letters {A..Z, a..z}, digits {0..9}, and underscore { _ } can be used unique name to the program does not match any reserved words must begin with a letter typically upper case for a class lower case for a method or instruction

Specifying a Marathon Robot: 

Specifying a Marathon Robot class MarathonRobot extends Robot { void moveMile() { // instructions omitted for now } // other instructions }

extends Robot?: 

extends Robot? class MarathonRobot extends Robot we indicate the MarathonRobot inherits all the capabilities of the Robot class in other words MarathonRobot knows all about move(), turnLeft(), pickBeeper(), putBeeper(), and shutOff() Robot is the base class of MarathonRobot MarathonRobot is a derived class of Robot IS-A relationship MarathonRobot IS A ur-Robot

Defining new methods in a program: 

Defining new methods in a program Download Stair SweeperDemo Verify this program is correct by tracing the code before running it

Robot Program Format: 

Robot Program Format We use at least two files in creating new robots and robot methods The Main Class file which is where the robot is constructed and given its task The Main Class is defined, the world is accessed, the speed is set The robot is constructed and receives its task instructions in the task() method The second file contains the description of the new robot, and the definition of its methods A constructor which describes how we build the robot And the definitions of the new instructions

Main Class: 

Main Class public class Main implements Directions { public static void task() { Stair_Sweeper Karel = new Stair_Sweeper(1, 1, East, 0); Karel.climbStair(); Karel.pickBeeper(); // other instructions … Karel.turnOff(); } // Main entry point static public void main(String[] args) { World.setDelay(20); World.readWorld("stairs.txt"); task(); } }

Class Header: Main: 

Class Header: Main public class Application implements Directions { // details of the class specification here } Name of class will be same as the name of the file, with a .java suffix This class is contained in the file Main.java Capitalization counts Directions is an interface that is is implemented by Main In other words Main fleshes out the details of Directions Main has the remaining details specific to the particular task the robot has to perform

StairSweeper class: 

StairSweeper class class Stair_Sweeper extends Robot { // constructor public Stair_Sweeper(int street, int avenue, Directions.Direction dir, int count) { super(street, avenue, dir, count); } //methods public void turnRight() { turnLeft(); turnLeft(); turnLeft(); } public void climbStair() { turnLeft(); move(); turnRight(); move(); } }

Class header: StairSweeper: 

Class header: StairSweeper class Stair_Sweeper extends Robot { } Name of class will be same as the name of the file, with a .java suffix This class is specified in the file StairSweeper.java The StairSweeper robot inherits information and extends the capabilities of the Robot robot Everything a Robot can do, a StairSweeper can do move(), turnLeft(), pickBeeper(), putBeeper(), turnOff() But a StairSweeper will be able to do more (have more features)

Constructing a new robot: 

Constructing a new robot public Stair_Sweeper(int street, int avenue, Directions.direction dir, int count) { super(street, avenue, dir, count); } This specifies how a robot is to be constructed Go back and look at the main() The instruction new Stair_Sweeper(1, 1, East, 0); is using this method, known as a constructor We are specifying location, direction, and number of beepers A constructor has the same name as the class The super keyword is indicating that this object is to be built the same way as its parent, Robot Our robot constructors will always look like this at the beginning

New robot methods: 

New robot methods public void turnRight() { turnLeft(); turnLeft(); turnLeft(); } public void climbStair() { turnLeft(); move(); turnRight(); move(); } public is a modifier letting us know that we can access this method from outside the class (in main() for example) Notice that climbStair() can use turnRight() as part of its definition The method headers are known as signatures (name and paramter list) All of the signatures of a class are known as the class interface or API Interface vs. interface?

Advantages of building new robots: 

Advantages of building new robots Structure problem solutions Programs become easier to understand and read Lead to fewer errors Enable future modifications Debugging programs is easier New instructions can be tested independently New instructions impose structure, which makes it easier to find bugs

Conditionals: 

Conditionals How do we solve tasks in which every particular of a task is not specifically known? A robot needs the ability to survey its immediate environment and make decisions about what to do next The IF and the IF/ELSE provide robots with decision making abilities Robot programs contain several different kinds of instructions Messages to robots, either primitives or new instructions Constructors (specifications on how to build a robot) Control statements: IF and IF/ELSE are the first examples of these

The IF instruction: 

The IF instruction General form if ( <test> ) { <instruction-list> } Robot determines whether <test> is true or false <instruction-list> is a sequence of any valid robot commands that will be performed when the robot determines the <test> is true Nothing will happen when the <test> is false

Example of IF statement: 

Example of IF statement // in a method // in a main task block if (nextToABeeper()) if (Karel.nextToABeeper()) { { pickBeeper(); Karel.pickBeeper(); } } turnLeft(); Karel.turnLeft(); A beeper will be picked up only if there is a beeper on the same corner as the robot Dependent upon the results of the test The robot will turn left, regardless of whether a beeper is on the corner or not Independent of the results of the test

Conditions that a robot can test: 

Conditions that a robot can test class Robot extends Robot { boolean frontIsClear(); boolean nextToABeeper(); boolean nextToARobot(); boolean facingNorth(); boolean facingSouth(); boolean facingEast(); boolean facingWest(); boolean anyBeepersInBeeperBag(); boolean isVisible(); } // notice we are checking the state of the robot // we can also use accessors to build our own tests

Negative conditions?: 

Negative conditions? Suppose we want a negative form of a predicate? We can precede a predicate with the negative operator ! if (! Karel.next-To-A-Beeper()) { // stuff }

For practice – two methods: 

For practice – two methods public void faceNorth() { } public void faceNorthIfFacingSouth() { }

The IF/ELSE instruction: 

The IF/ELSE instruction General form if ( <test> ) { // note lack of semicolon <instruction-list-1> } else { // note lack of semicolon <instruction-list-2> } Robot determines whether <test> is true or false <instruction-list-1> is a sequence of any valid robot commands that will execute when the robot determines the <test> is true <instruction-list-2> will execute when the <test> is false

Racer Robot: 

Racer Robot A hurdle jumping race A robot will run a mile. The course may or may not have an obstacle (wall) in the path. If the robot encounters a wall, it will go around (hurdle) the wall. Otherwise it will continue on it’s path… Download Sprinter demo

Nested IF Instructions: 

Nested IF Instructions Written with an IF instruction nested inside the THEN or ELSE clause of another IF As an example: if ( <test> ) { if ( <test> ) { <instruction-list-1> } else { <instruction-list-2> } } else { <instruction-list-2> }

New predicate instructions: 

New predicate instructions We could create a new subclass of the robot class and provide a new predicate method class myRobot extends Robot { // assume constructor boolean frontIsBlocked() { return ! frontIsCLear(); } // more stuff }

Use of the new predicate: 

Use of the new predicate public static void main(String [] args) { myRobot R = new myRobot(1, 1, North, 0); if (R.frontIsBlocked()) { // stuff } // and so on }

Walls to the right or left?: 

Walls to the right or left? Suppose we needed to determine if there is a wall to the right or left? public boolean leftIsClear() { turnLeft(); if (frontIsClear()) { turnRight(); // assume definition return true; // method terminates here } turnRight(); return false; } Return statement immediately terminates the method

When to Use an IF Instruction: 

When to Use an IF Instruction The IF instruction allows a robot to decide whether to execute or skip entirely the block of instructions within the THEN clause The IF/ELSE instruction allows a robot to decide whether to execute or skip the block of instructions within the THEN clause or the ELSE clause Nesting these instructions allows robots to make more complex choices

Loops: 

Loops We have already seen instances where a robot needs to repeat instructions to perform a task turnRight(); moveMile(); By defining new instructions we can minimize repetitive instructions runMarathon();

Loops for known number of repetitions: 

Loops for known number of repetitions There are times when you know how many times an instruction needs to be repeated… turnRight() is always 3 left turns moveMile() is always 8 moves() Method turnRight() with a loop: void turnRight() { for (int count = 0; count < 3; count++) { turnLeft(); } }

FOR loop: General form: 

FOR loop: General form for (int count = 0; count < <numberOfTimes>; count++) { <instruction-list>; } int count: count is the name of a variable that stores integers (whole numbers); it’s initial value is 0 count < <numberOfTimes> : as long as the current value of count is less than the number of loops we want, we keep looping; count will be equal to the number of loops we wanted when the loop is finished count++: we increment (add 1 to) the value of count <instructions>: Any valid robot instructions, including other loops

FOR loop: What does this do?: 

FOR loop: What does this do? void whatDoIDo() { for (int count = 0; count < 4; count++) { for (int count2 = 0; count2 < 6; count2++) { move(); } turnLeft(); } }

An unknown number of repetitions: 

An unknown number of repetitions Suppose we know we want a robot to repeat a series of instructions, but we do not know how many times… Task: There is a beeper somewhere on the same street in front of the robot, but we do not know exactly where… How does the robot find the beeper? FOR loop requires an upper limit (and there is no guarantee the beeper will fall within the range) IF statements are a one-time execute statement We need something to combine the testing ability of the IF statement with the iteration of a FOR loop

WHILE loop: General form: 

WHILE loop: General form while ( <test> ) { <instruction-list>; } Reserved word while starts the instruction, parentheses enclose the <test> , and braces enclose the <instruction-list>; in the usual way <test>: The same conditions used in the IF instructions A robot starts the loop by checking the <test> in it’s current situation If TRUE, the robot executes the <instruction-list>; and rechecks the situation If FALSE, the robot executes instructions that follow the WHILE loop

WHILE loop: find the beeper: 

WHILE loop: find the beeper class BeeperFinder extends Robot { // usual constructor // assumes no intervening wall segments void findBeeper() { while (! nextToABeeper()) { move(); } }

WHILE loop: Clear a corner: 

WHILE loop: Clear a corner A robot is on a corner that may or may not have beepers on it. The robot is to make sure that the corner is clear of all beepers // fill in the blanks void clearCorner() { while ( _____________________) { _____________________; } }

When to use repeating instructions: 

When to use repeating instructions

Random Walks: 

Random Walks A random walk is a model built on mathematical and physical concepts that is used to explain how molecules move in a closed space. Can be used as the basis for several mathematical models that predict stock market prices Owen Astrachan “A Computer Science Tapestry”, Chapter 7 McGraw Hill, New York, 1997

Random Walks: 

Random Walks We will use random walks as a way to further our understanding of the use and development of classes We will look at a random walk in Karel This will coincide with moving from a one-dimensional random walk with a single object, to two objects walking in the same environment Karel provides a graphical interface in our exploration

A Random Walk with Karel: 

A Random Walk with Karel See RandomWalker Demo This application will tell us in a walk of 50 steps, how far a Robot will end up from origin

Two-D Robots: 

Two-D Robots Suppose we wanted to track our robots in two-dimensional space, what changes do we have to make: To Main.java program To RandomWalker.java) Do we need another class?

Two Robots Walk: 

Two Robots Walk See CountWalker project Suppose we wanted to track two robots in the same space, and see how many times they collide? Remember, a random walk is a model ... that is used to explain how molecules move in a closed space, among other things

Two Robots Walk: 

Two Robots Walk This presents a special problem: It is very difficult for an object of one class to be “aware” of a specific object of another class… You can pass one object of a class to another object of a class, but it is a very difficult for the receiving object to know that the sent object is a specific object The best solution is to create a superclass or reporting class that can keep track of the sub-classes activities; in our case, we could create a “pond” class that could watch our robots, and report on the number of times they collide We could do this, but not at this time; we will come back to this issue later in the course

Minilab: 

Minilab Use the RandomWalker class to solve these problems: Prompt the user for a location. Report the number of steps the robot takes until it reaches that position. Given a maximum number of steps from the user, report the number of collisions of two robots in a two dimensional space… Right now, a 2D robot can move in only a north, south, east, or west direction with each step. Modify the class so that a 2D robot could move along 8 possible compass points, including, northeast, southeast, southwest, and northwest (in other words, move diagonally from it’s current position) Play hide and seek with other robots using visibility

Simulating Board Games: 

Simulating Board Games See RobotChutesLadders using GamePiece interface class Try Uncle Wiggly, Parcheesi