Chapter 2 - The First Program: Little Crab

Chapter 2 - The First Program: Little Crab

Chapter 6 Interacting Objects: Newtons Lab topics: objects interacting with each other, using helper classes, using classes from the Java library concepts: collection, list, for-each loop, standard class library In

this chapter, we shall investigate more sophisticated interactions between objects in a world. As a start, we shall investigate one of the most universal interactions between objects anywhere: Gravity. Newtons lab Objects in Space

Open the Newtons-Lab-1 scenario from the bookscenarios folder. You will see that a world subclass already exists (called Space). We also have classes SmoothMover, Body, and Vector The only non-abstract Actor-subclass of this scenario What kinds of bodies are in our solar system? Why dont

we see a Sun class? Why no Planet class? Solar System The types of bodies in our solar system include planets, planetoids, moons, asteroids and comets.

For our purposes we will consider each body only with regard to its color, size, mass, and the characteristics of its movement.

This means that we can use abstraction to implement ONE class to handle every type of body. The Space class: - 3 configurations of Space Right-click on the Space world background What happens when you activate one of these

methods? Space Public Methods Constructors within Constructors ? Inspecting Body Methods

Right click on a body. What methods does it have? Inspecting Body Properties Right click on a planet and inspect its properties. How

does the object store its position? Inspecting Body Properties Each Body holds a Vector object. What does the Vector object represent?

Helper Classes SmoothMover is an Abstract class. Abstract classes do not have constructors. We will never place a

SmoothMover on the board. 2 Support Classes - SmoothMover - Vector Helper Classes for Import Edit Menu / Import Class Some Helper Classes Animal

Counter GifImage Label Map Plotter ScoreBoard SimpleTimer SmoothMover Weather

More Helper (or Support) Classes http://www.greenfoot.org/doc/support_classes Some Helper Classes AnimatedActor Counter Explosion FPS GifActor MidiPlayer Mover

Plotter Rotator Slider The SmoothMover Class A SmoothMover is an Object that stores and calculates its position as decimal numbers instead of integers. This allows for smoother and more precise movement.

Each SmoothMover stores its movement as a Vector object. A Vector object stores direction and speed of movement. Methods Inherited from SmoothMover SmoothMover objects have the same method (setLocation) twice.

How do they differ? Why are they necessary? Vectors Cartesian Representation: Two offsets (dx, dy) that determine how the position changes on a Cartesian Plane.

Polar Representation: Change in position is defined by a direction and how far in that direction we move. Vector Class Variables The Vector class implements BOTH Polar and Cartesian representation. All necessary conversions

are handled within the class. Method Inheritance Open and read SmoothMover and Vector. Which methods can we actually execute from the object menu?

Every SmoothMover holds a Vector. Why can we not call Vectors methods from the menu? Constructors A Constructor has no Return Type Specified A Constructor Always has the Same Name as the Class Constructor is Automatically

Executed whenever an Instance (or object) of the Class is Created Default Constructors Does not have any parameters. Makes it easy to create bodies interactively without having to specify details. This is a default constructor.

What about the second constructor? Default and non-Default Constructors Methods can have the same name, as long as their parameters are different. This means

that the methods (or constructors) have different signatures. The Body class has 2 constructors with different parameters. We call this an overloaded constructor this() and this. Invokes the non-default

constructor with the specified values. There are two version of the variable mass in existence at this time. The Parameter mass and the class attribute mass. The this. means that

we are assigning the value of the Parameter to the attribute and NOT the other way around. Constants Means the value cannot be changed. Means its shared between all instances of this class.

These variables are called constants. These variables do not change in a program. Change act() so that it moves without applying any forces Body Behavior Create multiple bodies. How do they

behave? Add Movement (Left) How would you make the body move left? How to make objects go left? -90

270 -180 180 0 360 -270 90 Solution: Left Movement

/** * Construct a Body with default size, mass, movement and color. */ public Body() { this (20, 300, new Vector(180, 1.0), defaultColor); } Change the Direction in the Default Constructor from 0

to 180 Java Packages Programmers typically use packages to organize classes belonging to the same category or providing similar functionality. We can have a look at all the premade packages/classes of Java by selecting Java Library Documentation from the Help-tab.

import java.awt.Color; Imported using dot notation. Importing Java Color Library Representing Color

For example, every color is represented as a mixture of the three additive primary colors Red, Green, and Blue Each color is represented by three numbers between 0 and 255 that

collectively are called an RGB value RGB Color Combinations Color is expressed as an RGB (red-greenblue) value because our eyes have three types of color receptors that respond to light that has some amount of one of those three primary colors in it. The mixture of the different amounts of those three colors creates different colors. An RGB value of (255, 255, 0) maximizes the

contribution of red and green, and minimizes the contribution of blue, which results in a bright yellow The Color class A color in a Java program is represented as an object of the Color class

The Color class also contains several predefined colors, including the following: The Color class Other Predefined Colors:

Custom Colors You can define Custom Colors by declaring your own Color object with different RGB values as follows, where r,g,b are 3 values from 0 to 255: Color theColor = new Color(r,g,b); The above statement declares theColor to be an object variable (instead of a primitive variable) with Color as its type. The term new means that a new instance of the object will be created

with the specified values. Default Color of Body Sets the RBG values Calls the Color class. What is the legal range for colors?

Adding Gravitational Force Apply Force To Do List To apply forces from all other Bodies to a Body, we will: a) Create a list containing all the Bodies currently in Space And

b) Go through the list and apply the gravitational force of each of these bodies in sequence Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: {

apply gravity from that body to our own; { Apply Force Part I Methods (and Variables) only intended to be called from within the class can be labeled private. When methods are intended to

be called from outside the class, they should be labeled public. Greenfoot World Methods http://www.greenfoot.org/files/javadoc/greenfoot/World.ht ml Which methods give us access to objects within the world? We can have a look at all the

Greenfoot-specific classes by selecting Greenfoot Class Documentation from the Help-tab. Getting Objects (World Methods) getObjects(java.lang.Class cls)

getObjects(Body.class) Gets a list of all objects in the world of a particular

class. Gets a list of all objects of class Body in the world. getObjects(null) Keyword null is a special expression that means no object. This call will get a list of ALL object in the world.

Getting the Body Objects World getWorld() There is a method in the Actor class that gives us access to the World class. It signature is World getWorld() This method allows you to get access to all objects that have been added to your World.

getWorld().getObjects(Body.class) Can be used from an actor to get all objects of class Java.util.list What methods can be used to add items to a list? What methods can be used to remove items to a list? What methods can be used to find out how many items are in

a list? Lists can contain different types (or classes) of objects This notation tells us that a List is a generic type. Meaning a List has no data type itself. We provide the Data type by specifying it in the bracket.

List List Apply Force Part II For-Each Loops Helps to step through the items in a list.

for (Type variableName : list) { statements; } You identify the variable type and name, then on the other side of the colon, you identify the list of values. Then the loop goes through the statements for each value in the list, using the variableName as an identifier for the object currently in use.

Apply Force Part III this refers to the current object. Use an if-statement so that gravity is applied from all objects (bodies) in the list except the current object. Applying

Gravity Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: { apply gravity from that body to our own;

{ Newtons Law Newton's Law of Universal Gravitation states that every massive particle in the universe attracts every other massive particle with a force which is directly proportional to the product of their masses and inversely proportional to the square of the distance between them.

Apply Gravity Algorithm Apply gravity from object b) to object a) { calculate the distance between the x-/y- coordinate of the objects; create a new vector using this data to determine direction; calculate the distance between the two bodies using Pythagoras theorem; use Newton's formula to calculate the strength of the force calculate the length (acceleration) of the vector;

apply the vector to object a); } Acceleration Acceleration = Force / Mass Appling Gravity Method

Why do these numbers need to be doubles? Trying it Out Try out the three initializing methods from Space object again. What do you observe?

Experimenting with Gravity Change the gravity constant at the top of the body class. What happens? Change it by , change it by doubling it; change it by 1, change it by a decimal. Experimenting with Mass & Movement

Experiment with changes to the mass and/or initial movement of the bodies defined in the Body class. What happens? size mass vector

movement When experimenting its important to change one variable at a time. r g b

x y Concept Summary

Recently Viewed Presentations

  • Today in Week #4 Quarter 2 (11/4) Biology

    Today in Week #4 Quarter 2 (11/4) Biology

    Week #4 Quarter 2 (11/5) Homework: unit 4 cell cycle, mitosis and meiosis test Tuesday. To Do Today: C. ell cycle, mitosis and meiosis unit test. Fact of the Day
  • Parcc K-2

    Parcc K-2

    : Recount stories, including fables, folktales, and myths from diverse cultures; determine the central message, lesson, or moral and explain how it is conveyed through key details in the text. Provides a recounting of stories, including fables, folktales, and myths...
  • Genomes & The Tree of Life  Archaea -

    Genomes & The Tree of Life Archaea -

    Prokarya - small to very small (e.g., Mycobacterium) circular genomes Eukarya - 3 genomes Mitochondrial - small to micro-sized, linear and circular, prokaryotic origin Chloroplast - small, circular, prokaryotic origin Nucleus - large, linear chromosomes; evidence of archaea, prokaryotic and...
  • Container market Furnaces split 1497 furnaces ; 10 700 tons ...

    Container market Furnaces split 1497 furnaces ; 10 700 tons ...

    FEEDER FUNCTION IN GLASS INDUSTRY. Feeder function: ensure glass temperature level , homogeneity and stability . Continuous temperature decrease from feeder entrance up to the spout, to the right temperature (viscosity)
  • Evaluation of Print Media info.gio.gov.tw/ct.asp?xItem =18902&CtNode=2617&mp=4 http:// Classification

    Evaluation of Print Media info.gio.gov.tw/ct.asp?xItem =18902&CtNode=2617&mp=4 http:// Classification

    Types of Newspapers - Format and Size Tabloid (e.g. 國語日報) & Broadsheet (e.g. 蘋果日報) SAU (standard advertising unit) American Newspaper Publishers Association and Newspaper Advertising Bureau first introduced the SAU system in the early 1980s.
  • History of DPB Requests to UM System Administration

    History of DPB Requests to UM System Administration

    History of DPB Requests to UM System Administration ... Marquette, U Denver, Furman, Elon, Pacific Lutheran, Southern Methodist) Missouri Higher Education Institutionswith Domestic Partner Benefits . ... SPRAC Letter to Owens and the Board of Curators?
  • NIMH: Setting Priorities Thomas R. Insel, M.D. Director

    NIMH: Setting Priorities Thomas R. Insel, M.D. Director

    Epigenetics Bench Bedside Pathophysiology Diagnostic tests Biomarkers New treatments Practice Clinical Trials Networks Practical trials Services research Handoff for dissemination Efficacy trials - short duration, carefully selected subjects often in academic setting, outcome measured by rating scale Example : drug...
  • Vos assurances à la retraite - Université du Québec

    Vos assurances à la retraite - Université du Québec

    Votre choix devra être effectué, selon le cas, dans les 31 ou 60 jours qui suivent la cessation de votre assurance du réseau UQ . Vous ne retrouverez pas ce que vous viendrez de perdre, à moins de payer une...