Admin. CS 112 Introduction to Programming. Admin. Admin. Recap. Recap: Polymorphism and Arrays. the Google doc to record the teaming

Similar documents
CS 112 Introduction to Programming

CS 112 Introduction to Programming. (Spring 2012)

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

Admin. CS 112 Introduction to Programming. Recap: The Critter Class. Recap: Event-Driven Programming. State Machine Driven Cougar.

Building Java Programs

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

Assignment 11: Critters

What is Polymorphism? CS 112 Introduction to Programming

CSc 110, Spring 2017 Lecture 38: Critters. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Spring 2017 Lecture 37: Critters. Adapted from slides by Marty Stepp and Stuart Reges

CSE 142, Autumn 2018 Programming Assignment #9: Critters (20 points) Due Tuesday, December 4th, 9:00 PM

Critter #1 Attack.ROAR random winner #2 wins #1 wins Attack.POUNCE #1 wins random winner #2 wins Attack.SCRATCH #2 wins #1 wins random winner

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Building Java Programs

Big software. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

File: D:\My Documents\Classes\Computer Science\Class Notes\Fall New\Polymorphism\Employee.java 7/20/1999, 10:53:52 AM

CIS 110 Introduction To Computer Programming. December 19th, 2011 Final. Answer key

Homework 9: Critters (cont.)

CS 312 Final Fall 2016

Topic 31 - inheritance

CS111: PROGRAMMING LANGUAGE II

CS 312 Final Fall 2013

CSE 142 SPRING 2008 FINAL EXAM

CS 312 Final Fall Your Name SOLUTION SOLUTION SOLUTION SOLUTION SOLUTION. Your UTEID SOLUTION SOLUTION SOLUTION SOLUTION SOLUTION _

CS111: PROGRAMMING LANGUAGE II

The class Object. Lecture CS1122 Summer 2008

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Programming in C# Inheritance and Polymorphism

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

What is Inheritance?

BBM 102 Introduction to Programming II

Topic 32 - Polymorphism

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

CSE142 Sample Final Exam Key Autumn 2018

CS 112 Introduction to Programming

Basic Object-Oriented Concepts. 5-Oct-17

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Example: Count of Points

CSE142 Final Exam Key Summer 2018

CS 312 Final Fall 2015

Part 3: GridWorld Classes and Interfaces

C08: Inheritance and Polymorphism

Java Programming Lecture 7

CSE 142, Winter 2007 Final Exam. Name:

CS260 Intro to Java & Android 03.Java Language Basics

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

SE203b: OO Design for Software Engineers. Office: TEB349, Ext

BBM 102 Introduction to Programming II Spring 2017

Lecture 15: Inheritance II

Binghamton University. CS-140 Fall Dynamic Types

Review of Object-Oriented Concepts in JAVA

CIS 110 Introduction To Computer Programming. December 19th, 2011 Final. Answer key for review problems

First IS-A Relationship: Inheritance

CS 112 Introduction to Programming

CLASS DESIGN. Objectives MODULE 4

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

C18a: Abstract Class and Method

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Java Review. Fundamentals of Computer Science

Inheritance, Polymorphism, and Interfaces

CSCI 355 Lab #2 Spring 2007

CSE 143X: Accelerated Computer Programming I/II HW5: Critters (due Friday, October 30, :30pm)

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Chapter 14 Abstract Classes and Interfaces

Inheritance (Outsource: )

Building Java Programs

CO Java SE 8: Fundamentals

Inheritance & Polymorphism

Object Orientated Programming Details COMP360

CSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges)

Java How to Program, 8/e

CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal

S <: T Type compa*bility rela*on.

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSE 142 Sample Final Exam #1

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Topic 7: Algebraic Data Types

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CSE 142 Sample Final Exam #2

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

About this sample exam:

Ant Farm GridWorld Project

CSE 142, Spring 2010 Final Exam Wednesday, June 9, Name: Student ID #: Rules:

C# Programming for Developers Course Labs Contents

CS-202 Introduction to Object Oriented Programming

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Transcription:

Admin CS 112 Introduction to Programming Critters/Event-Driven Programming Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu q Class project teaming is due today: please use the Google doc to record the teaming q We will provide special sessions to cover more background on Android App Google App Engine (Web app backend) q Javascript will be covered in class starting from next week Please read the tutorials listed on class page 2 Admin q Example projects Games Sudoku: http://mrt-sudokusolver.appspot.com/ Target to solve non-solvable by PS6 using recursion Madlib: http://mrt-cs112-0.appspot.com/ Used Google App Engine as backend 2048 http://gabrielecirulli.github.io/2048/ Research, validation Evaluate or train the counting method of blackjack http://en.wikipedia.org/wiki/mit_blackjack_team Admin Tools Health care cost calculator for Yale students Image processing tools (face recognition) based on OpenCV https://www.openshift.com/blogs/day-12-opencv-facedetection-for-java-developers) Transloc api (http://api.transloc.com/doc/) to build a shuttle application for Yale 3 4 Recap q polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. q Polymorphic Reference through Inheritance A polymorphic reference variable of type T can hold an object of class T or descendent of T, e.g., Employee emp = new Employee( Ed ); emp = new Lawyer( Larry ); emp = new LegalSecretary( Lisa ); q When you invoke a method through a polymorphic reference variable, it is the type of the object being referenced, not the reference type, that determines which method is invoked. Recap: Polymorphism and Arrays q A common usage of polymorphism is to define an array of a base type, but different entries refer to different types of objects To handle a heterogeneous population of objects with uniformity 1

Polymorphism and Arrays: Example Extending the Program: Hourly public class Staff { private Employee[] stafflist; public Staff() { stafflist = new Employee[4]; stafflist[0] = new Lawyer("Lisa"); stafflist[1] = new Secretary("Sally"); stafflist[2] = new Marketer("Mike"); stafflist[3] = new LegalSecretary("Lynne"); Works on any mix of Employee objects q Include a new type of secretary who works variable number of hours and is paid by the hours. public void payday() { for (int count = 0; count < stafflist.length; count++) { System.out.printf("%-10s:", stafflist[count].name()); System.out.printf("$%.2f\n", stafflist[count].pay()); System.out.println("-----------------------------------"); 8 Add a new Type of Employee: Hourly Polymorphism and Arrays: Example public class Hourly extends Secretary { private double payrate; private int hours; public Hourly(String name, double payrate) super(name); this.payrate = payrate; hours = 0; public void addhours(int hours) { this.hours += hours; public int hours() { return hours; public double pay() {return hours() * payrate; 9 public class Staff { private Employee[] stafflist; public Staff() { stafflist = new Employee[5]; stafflist[0] = new Lawyer("Lisa"); stafflist[1] = new Secretary("Sally"); stafflist[2] = new Marketer("Mike"); stafflist[3] = new LegalSecretary("Lynne"); Hourly holly = new Hourly( Holly"); holly.addhours(10); stafflist[4] = holly; public void payday() { for (int count = 0; count < stafflist.length; count++) { System.out.printf("%-10s:", stafflist[count].name()); System.out.printf("$%.2f\n", stafflist[count].pay()); System.out.println("-----------------------------------"); No need to change the payday method at all. Payroll + main (args : String[]) : void The pay-roll of a firm Comment: Variable Type and Method Staff -- stafflist: : staffmemeber[] Employee[] + payday() : void Hourly - payrate: double Employee # name : String + tostring() : String Lawyer + tostring() : String q Through a given type of reference variable, we can invoke only the methods defined in that type class Employee{ public double pay() { class Lawyer extends Employee { public void sue() { Partner Employee ed = new Lawyer( Larry ); - bonus : double + awardbonus(bonus : double) : void 11 Can we do the following statements: ed.pay(); ed.sue(); 12 2

Comment: Variable Type and Method q We can promote an object back to its original type through an explicit narrowing cast: stafflist = new Employee[5]; stafflist[0] = new Lawyer("Lisa"); stafflist[1] = new Secretary("Sally"); stafflist[2] = new Marketer("Mike"); stafflist[3] = new LegalSecretary("Lynne"); stafflist[4] = new Hourly( Holly"); Hourly holly = (Hourly)staffList[4]; holly.addhours (5); If the type of object referred to by staff[4] is not Hourly, program error. Outline q Admin and recap q Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy o inheritance and polymorphism o example: Critters 13 14 Critters The Critter Class q A simulation (game) world of animal objects (e.g., Ants, Birds, Cougars) with behaviors such as eat eating food fight animal fighting getcolor color to display getmove movement tostring letter to display // abstract class means not implement every method public abstract class Critter { public boolean eat() public Attack fight(string opponent) // ROAR, POUNCE, SCRATCH, FORFEIT public Color getcolor() public Direction getmove(string[][] grid) // NORTH, SOUTH, EAST, WEST, CENTER public String tostring() // read the class for other methods available Defining a Critter subclass Example Critter World Class Hierarchy public class name extends Critter {... q extends Critter tells the simulator your class is a critter an example of inheritance Critter Ant Bird Hippo Vulture Bulldog q Override some methods to give your new type of animal behaviors. 18 3

Critter Example: Stone The Simulator (Controller) import java.awt.*; public class Stone extends Critter { public Attack fight(string opponent) { return Attack.ROAR; // good ol' ROAR... nothing beats that! public Color getcolor() { return Color.GRAY; // stones are gray in color public String tostring() { return "St"; // the game displays a stone 19 q The simulator is in CritterMain.java q It searches local dir. for all critters types q The simulator creates an array of critters q "Go" loop: move each animal (getmove) if they collide, fight if they find food, eat Next move? % Simulator Pseudo-code Event-Driven Programming Critter[] critters = new Critter[N]; critters[0] = new Ant(); critters[1] = new Bird(); loop foreach critter i in critters call getmove of critter i if it can move foreach critter i in critters if new pos of critter i results in fight ask how critter i will fight if new pos finds food ask critter i whether it will eat if new pos results in mate possibility ask if critter i will mate compute new state of critters q Key concept: The simulator is in control, NOT your animal. Example: getmove can return only one move at a time. getmove can't use loops to return a sequence of moves. It wouldn't be fair to let one animal make many moves in one turn! Your animal must keep state (as fields) so that it can make a single move, and know what moves to make later. We say that you focus on writing the callback functions of objects Critter exercise: Cougar getmove q Write a critter class Cougar (among the dumbest of all animals): Method constructor public Cougar() eat fight getcolor getmove tostring Always eats. Always roars. Behavior Blue if the Cougar has never fought; red if he has. Walks west until he finds food; then walks east until he finds food; then goes west and repeats. "C" q How can a critter move west until it finds food and then moves to east until find food and repeat? public Direction getmove(string[][] grid) { initial currentdirect = WEST loop if (eat) { reverse currentdirect; print currentdirection; Implement Cougar s eat, fight, tostring. 4

getmove for Cougar getcolor for Cougar Blue if the Cougar has never fought; red if he has. q State machine eat() Move West Move East eat() q How to remember the state? a boolean instance variable: boolean west q What is initial state and where to set it? In constructor: west = true; q Who/when updates the state? In eat(): reverse state q State machine fight()! Has fought Has fought q How to remember the state? A boolean instance variable: boolean fought q What is initial state and where to set it? In constructor: fought = false; q Who/when updates the state? In fight(): fought = true 25 26 Cougar solution Cougar solution import java.awt.*; // for Color public class Cougar extends Critter { private boolean west; private boolean fought; public Cougar() { west = true; fought = false; public boolean eat() { west =!west; return true; public Attack fight(string opponent) { fought = true; return Attack.POUNCE;...... public Color getcolor() { if (fought) { return Color.RED; { return Color.BLUE; public Direction getmove(string[][] grid) { if (west) { return Direction.WEST; { return Direction.EAST; public String tostring() { return "C"; Critter : Snake Method Behavior constructor public Snake() eat Never eats fight random pounce or roar getcolor Color(20, 50, 128) getmove 1 E, 1 S; 2 W, 1 S; 3 E, 1 S; 4 W, 1 S; 5 E,... tostring "S" Determining necessary fields q Information required to decide what move to make? Direction to go Length of current cycle Number of moves made in current cycle 5

Non-EDP Version Non-EDP Version // go one cycle for ( steps < cyclelength; steps++) if cyclelength % 2 == 1 Non-EDP Version Non-EDP-> EDP: Guarding Condition steps < cyclelength while (steps < cyclelength) if cyclelength % 2 == 1 steps ++; while (steps < cyclelength) if cyclelength % 2 == 1 steps ++; if (cyclelength % 2 == 1) steps++; steps == cyclelength steps=0; 34 Snake solution import java.awt.*; // for Color public class Snake extends Critter { private int cyclelength; // # steps in curr. Horiz. cycle steps < cyclelength private int steps; // # of cycle's steps already taken public Snake() { public Direction getmove() { if (steps < cyclelength) { steps++; if (cyclelength % 2 == 1) { { { return Direction.EAST; return Direction.WEST; ; return Direction.SOUTH; public String tostring() { return "S"; if (cyclelength % 2 == 1) steps++; steps == cyclelength Go South steps=0; 6