Docsity

Study Notes - Representing Structure and Behavior | CS 1316, Exams of Computer Science

Toggle sidebar
bg1
1
Continuous Simulation
(Wolf/Deer Populations)
CS1316: Representing
Structure and Behavior
WolfDeerSimulation
public class WolfDeerSimulation {
/* Linked lists for tracking wolves and deer */
private AgentNode wolves;
private AgentNode deer;
/** Accessors for wolves and deer */
public AgentNode getWolves(){return wolves;}
public AgentNode getDeer(){return deer;}
Why private?
Only the
simulation should
know its wolves
and deer.
The main run() method
public void run()
{
World w = new World( );
w.setAutoRepaint(fals e);
// Start the lists
wolves = new AgentN ode();
deer = new AgentNod e();
// create some deer
int numDeer = 20;
for (int i = 0; i < numDeer; i++)
{
deer.add(new A gentNode(new Deer(w,thi s)));
}
We want to control
when the world
updates itself.
AgentNodes
contain the
Deer
Head and Rest
Wolves and deer are AgentNodes…but the real
content starts at getNext().
We call this the head of the list.
•It’s a placeholder.
We call the rest the rest or body of the list.
•This makes it possible to remove a node, even if it’s the first
one in the list.
Head
getNext:
Rest
getNext:
wolves
Rest
getNext:
Rest
getNext:
Make some wolves
// create some wolves
int numWolves = 5;
for (int i = 0; i < numWolves; i++)
{
wolves.add(new AgentNode(new Wolf(w,this)));
}
Start our simulation loop
// declare a wolf and deer
Wolf currentWolf = null;
Deer currentDeer = null;
AgentNode currentNode = null;
// loop for a set number of timesteps (50 here)
for (int t = 0; t < 50; t++)
{
// loop through all the wolves
currentNode = (AgentNode) wolves.getNext();
while (currentNode != null)
{
currentWolf = (Wolf) currentNode.getAgent();
currentWolf.act();
currentNode = (AgentNode) currentNode.getNext();
}
What’s going on
here?
It’s our Age ntNodes
that are in a linked
list. Each one of
them contains
(aggregation!) a
Wolf.
Have to pull the
Wolf out to get it to
act()
pf3
pf4
pf5
pf8

Partial preview of the text

Download Study Notes - Representing Structure and Behavior | CS 1316 and more Exams Computer Science in PDF only on Docsity!

Continuous Simulation

(Wolf/Deer Populations)

CS1316: Representing

Structure and Behavior

WolfDeerSimulation

public class WolfDeerSimulation {

/* Linked lists for tracking wolves and deer */

private AgentNode wolves;

private AgentNode deer;

/** Accessors for wolves and deer */

public AgentNode getWolves(){return wolves;}

public AgentNode getDeer(){return deer;}

Why private?

Only the

simulation should

know its wolves

and deer.

The main run() method

public void run()

World w = new World(); w.setAutoRepaint(false);

// Start the lists wolves = new AgentNode();

deer = new AgentNode();

// create some deer

int numDeer = 20;

for ( { int i = 0; i < numDeer; i++)

}^ deer.add(new^ AgentNode(new^ Deer(w,this)));

We want to control

when the world

updates itself.

AgentNodes

contain the

Deer

Head and Rest

 Wolves and deer are AgentNodes…but the real

content starts at getNext().

 We call this the head of the list.

• It’s a placeholder.

 We call the rest the rest or body of the list.

• This makes it possible to remove a node, even if it’s the first

one in the list.

Head

getNext:

Rest

getNext:

wolves

Rest

getNext:

Rest

getNext:

Make some wolves

// create some wolves

int numWolves = 5;

for (int i = 0; i < numWolves; i++)

wolves.add(new AgentNode(new Wolf(w,this)));

Start our simulation loop

// declare a wolf and deer Wolf currentWolf = null; Deer AgentNode currentDeer currentNode = null; = null; // loop for a set number of timesteps (50 here) for ( { int t = 0; t < 50; t++) // loop through all the wolves currentNode while (currentNode = (AgentNode != null)) wolves.getNext(); { currentWolf = (Wolf) currentNode.getAgent(); currentWolf.act currentNode = (();AgentNode) currentNode.getNext(); }

What’s going on

here?

It’s our AgentNodes

that are in a linked

list. Each one of

them contains

(aggregation!) a

Wolf.

Have to pull the

Wolf out to get it to

act()

Give the deer a chance to act // loop through all the deer currentNode = (AgentNode) deer.getNext(); while (currentNode != null) { currentDeer = (Deer) currentNode.getAgent(); currentDeer.act(); currentNode = (AgentNode) currentNode.getNext(); }

Same unpackaging going on

here.

Show us what happened // repaint the world to show the movement w.repaint(); // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); System.out.println("Wolves left: "+wolves.getNext().count()); System.out.println("Deer left: "+deer.getNext().count()); // Wait for one second //Thread.sleep(1000); } }

Does the simulation go too fast?

Make the thread of execution

sleep for 1000 milliseconds

Implementing a Wolf import import java.awt.Colorjava.util.Random;; import java.util.Iterator; /**

  • Class that represents a wolf. * tracks all the living wolves with a linked list. The wolf class
    • @author Barb Ericson [email protected] public class Wolf extends Turtle^ / { /////////////// fields ////////////////////// /* class constant for the color / private static final Color grey = new Color(153,153,153); /* class constant for probability of NOT turning */ protected static final double PROB_OF_STAY = 1.0/10;

A final is something that

won’t change: A

constant. It’s used to

make code more

readable yet easy-to-

change.

Private vs. Protected?

Use Protected if your

subclasses will need to

access (new kinds of

wolves?)

Constants are

typically all-caps

More Wolf fields /** class constant for top speed (max num steps can move in a timestep) / protected static final int maxSpeed = 60; /* My simulation / protected WolfDeerSimulation mySim; /* random number generator */ protected static Random randNumGen = new Random();

There is more than one

kind of random. Treating

it as an object makes it

easier to have different

kinds later.

maxSpeed should

probably be all-caps

(or did you want to

make it variable? Do

wolves get slower

as they get hungry?

Constructors ////////////////////////////// Constructors //////////////////////// /** * Constructor that takes the model display (the original

  • position will be randomly assigned) * @param modelDisplayer thing that displays the model
  • @ /param mySim my simulation public Wolf ( thisSim)ModelDisplay modelDisplayer,WolfDeerSimulation { super(randNumGen.nextInt(modelDisplayer.getWidth()), randNumGen.nextInt(modelDisplayer.getHeight modelDisplayer); ()), }^ init(thisSim); /* Constructor that takes the x and y and a model * display to draw it on
  • @ * @paramparam x the starting x positiony the starting y position
  • @ * @paramparam modelDisplayermySim my simulation the thing that displays the model public Wolf (^ */ int x, int y, ModelDisplay modelDisplayer, {^ WolfDeerSimulation^ thisSim) // let the parent constructor handle it super(x,y,modelDisplayer); }^ init(thisSim);

Remember that a

constructor must

match its superclass,

if you want to use

super(). These are

like the ones in

Turtle.

What’s a

ModelDisplay? The

abstract superclass of

the World.

Using a Random: PseudoRandom Number Generator

Deer Constructors ////////////////////////////// Constructors //////////////////////// /** * Constructor that takes the model display (the original

  • position will be * @param modelDisplayer randomally thing which will display the model assigned public Deer (^ / ModelDisplay modelDisplayer,WolfDeerSimulation {^ thisSim) super(randNumGen.nextInt(modelDisplayer.getWidth randNumGen.nextInt(modelDisplayer.getHeight()),()), init(thisSim^ modelDisplayer); ); } /* Constructor that takes the x and y and a model * display to draw it on
  • @ * @paramparam x the starting x positiony the starting y position
  • @ */param modelDisplayer the thing that displays the model public Deer ( WolfDeerSimulationint x, int y, ModelDisplay thisSim) modelDisplayer, { // let the parent constructor handle it super(x,y,modelDisplayer init(thisSim); ); }

Nothing new

here…

Initializing a Deer

* Method to initialize the new deer object

public void init(WolfDeerSimulation thisSim)

// set the color of this deer

setColor(brown);

// turn some random direction

this.turn(randNumGen.nextInt(360));

// know my simulation

mySim = thisSim;

Nothing new

here…

What Deer Do

* Method to act during a time step

* pick a random direction and move some random amount up to top speed */

public void act()

{ // if the random number is > prob of NOT turning then turn

if (randNumGen.nextFloat() > PROB_OF_STAY)

{ this.turn(randNumGen.nextInt(360));

// go forward some random amount

}^ forward(randNumGen.nextInt(maxSpeed));

Nothing new

here…

When Deer Die

* Method that handles when a deer dies

public void die()

// Leave a mark on the world where I died...

this.setBodyColor(Color.red);

// Remove me from the "live" list

mySim.getDeer().remove(this);

// ask the model display to remove this

// Think of this as "ask the viewable world to remove this turtle"

//getModelDisplay().remove(this);

System.out.println("<SIGH!> A deer died...");

If you want the

body and its trail

to disappear…

Why don’t we

have to say

getNext () before

the remove ()?

AgentNodes  AgentNodes contain Turtles

  • That’s aggregation  It’s a subclass of LLNode
  • It’s a specialization of LLNode AgentNode implementation /**
  • Class to implement a linked list of Turtle-like characters.
  • (Maybe "agents"?) / public class AgentNode extends LLNode { /
  • The Turtle being held **/ private Turtle myTurtle;

AgentNode constructors /** Two constructors: One for creating the head of the list

  • , with no agent / public AgentNode() {super();} /
  • One constructor for creating a node with an agent / public AgentNode(Turtle agent){ super(); this.setAgent(agent); } AgentNode getter/setter /
  • Setter for the turtle / public void setAgent(Turtle agent){ myTurtle = agent; } /
  • Getter for the turtle **/ public Turtle getAgent(){return myTurtle;} AgentNode: Remove node where Turtle is found

* Remove the node where this turtle is found.

public void remove(Turtle myTurtle) {

// Assume we're calling on the head

AgentNode head = this;

AgentNode current = (AgentNode) this.getNext();

while (current != null) {

if (current.getAgent() == myTurtle)

{// If found the turtle, remove that node

head.remove(current);

current = (AgentNode) current.getNext();

It’s just like other

linked list removes, but

now we’re looking for

the node that contains

the input turtle.

Think about it…  What if AgentNodes contained Object s?

  • Object is a class that is the superclass of all classes (even if not explicitly extended ).
  • AgentNodes that contain Objects could be general linked lists that contain anything - Just cast things as you need them as you pull them out. Back to the simulation: What might we change?  Wolves that aren’t always hungry?  Having wolves that chase deer? Have deer run from wolves?  And how do we look at the results? We’ll deal with hunger first, then with comparing, then with running towards/away. Creating a Hungry Wolf /**
  • A class that extends the Wolf to have a Hunger level.
  • Wolves only eat when they're hungry / public class HungryWolf extends Wolf { /
  • Number of cycles before I'll eat again / private int satisfied; / class constant for number of turns before hungry */ private static final int MAX_SATISFIED = 3;

New constants for Deer /** class constant for probability of NOT turning / private static final double PROB_OF_STAY = 1.0/5; /* class constant for how far deer can smell / private static final double SMELL_RANGE = 50; /* class constant for top speed (max num steps can move in a timestep) / private static final int maxSpeed = 30; Deer-finding closest Wolf /* * Method to get the closest wolf within the passed distance

  • to this deer. We'll search the input list of the kind * of objects to compare to. */ public AgentNode getClosest(double distance,AgentNode list) { // get the head of the deer linked list AgentNode AgentNode head = list;curr = head; AgentNode Wolf thisWolf closest = null;; double double closestDistancecurrDistance = 0; = 0; // loop through the linked list looking for the closest deer while (curr != null) { thisWolf = (Wolf) curr.getAgent(); currDistance thisWolf.getDistance(this.getXPos(),this.getYPos = ()); if ( {currDistance < distance) if (closest == null || { currDistance < closestDistance) closest = closestDistance curr; = currDistance; }^ } }^ curr^ = (AgentNode)^ curr.getNext(); }^ return closest;

Strikingly

similar to

Wolf’s for find

Deer, no?

Deer new act() /** * Method to act during a time step

  • pick a random direction and move some random amount up to top speed public void act()^ */ { // get the closest wolf within the smell range AgentNode closeWolf (AgentNode = getClosest(SMELL_RANGE) , mySim.getWolves().getNext()); if ( WolfcloseWolf thisWolf != null) { = (Wolf) closeWolf.getAgent(); // Turn to face the wolf this.turnToFace(thisWolf); // Now directly in the opposite direction this.turn(180); // How far to run? How about half of max speed?? this.forward((int) (maxSpeed/2)); } else { // if the random number is > if (randNumGen.nextFloat() > PROB_OF_STAY) prob of NOT turning then turn { this.turn(randNumGen.nextInt(360)); } // go forward some random amount forward(randNumGen.nextInt(maxSpeed)); }^ }

Think about this in

terms of the values

that can be changed

and their relative

values.

Does this match the

English description

we had a few slides

back?

Wolf Constants /** class constant for probability of NOT turning / protected static final double PROB_OF_STAY = 1.0/10; /* class constant for top speed (max num steps can move in a timestep) / protected static final int maxSpeed = 40; /* class constant for how far wolf can smell / private static final double SMELL_RANGE = 50; /* class constant for how close before wolf can attack */ private static final double ATTACK_RANGE = 30; How Wolf’s smell deer

* Method to act during a time step

* pick a random direction and move some random amount up to top speed

public void act()

// get the closest deer within smelling range

AgentNode closeDeer (AgentNode = getClosest(SMELL_RANGE) mySim.getDeer().getNext, ());

if (closeDeer != null)

Deer thisDeer = (Deer) closeDeer.getAgent();

// Turn torward deer

this.turnToFace(thisDeer);

// How much to move? How about minimum of maxSpeed

// or distance to deer?

this.forward((int) Math.min(maxSpeed,

thisDeer.getDistance(this.getXPos(),this.getYPos())));

The rest of normal Wolf actions // get the closest deer within the attack distance closeDeer = getClosest(ATTACK_RANGE (AgentNode) mySim.getDeer().getNext, ()); if (closeDeer != null) { Deer thisDeer = (Deer) closeDeer.getAgent(); this.moveTo(thisDeer.getXPos(), thisDeer.die^ thisDeer.getYPos(); ()); } else // Otherwise, wander aimlessly { // if the turn randome number is > prob of NOT turning then if ( {randNumGen.nextFloat() > PROB_OF_STAY) }^ this.turn(randNumGen.nextInt(360)); // go forward some random amount } // end else^ forward(randNumGen.nextInt(maxSpeed)); } // end act()

Changes to WolfDeerSimulation…NOTHING!  We have the same interface as we used to have, so nothing changes in WolfDeerSimulation.  Very powerful idea:

  • If changes to a class keep the interface the same, then all users of the class don’t have to change at all. Running the new simulation Welcome to DrJava. > WolfDeerSimulation WolfDeerSimulation wds(); = new > wds.openFile("D:/cs1316/wds- chase.txt") > wds.run(); 02 46 180 1124 1168 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 W Deolevres Explorations  What does the relative speed of Deer and Wolves matter?
  • Does it matter if Deer go faster? Wolves?  What if Deer and Wolves can smell farther away?
  • What if one can smell better than the other?  What’s the effect of having more Deer or more Wolves?  What if HungryWolves could starve (say at - satisfaction)? Do more deer live? Doing More Simulations  How much code would be in common in every simulation we’d build?
  • We already have lots of duplication, e.g., getClosest.  Goal: Can we make an Agent/Actor class and Simulation class that we’d subclass with very little additional code to create new simulations?