Create a simple 2d predator-prey simulation.

Assignment Help JAVA Programming
Reference no: EM13940709

The goal for this programming project is to create a simple 2D predator-prey simulation. In this simulation the prey are ants and the predators are doodlebugs. These critters live in a world composed of a 20x20 grid of cells. Only one critter may occupy a cell at a time. The grid is enclosed, so a critter is not allowed to move off the edges of the world. Time is simulated in time steps. Each critter performs some action every time step.
The ants behave according to the following model:

Move. Every time step, randomly try to move up, down, left or right. If the neighboring cell in the selected direction is occupied or would move the ant off the grid, then the ant stays in the current cell.
Breed. If an ant survives for three time steps, then at the end of the time step (i.e. after moving) the ant will breed. This is simulated by creating a new ant in an adjacent (up, down, left, or right) cell that is empty. If there is no empty cell available then no breeding occurs. Once an offspring is produced an ant cannot produce an offspring until three more time steps have elapsed.
The doodlebugs behave according to the following model:
Move. Every time step, if there is an adjacent ant (up, down, left, or right) then the doodlebug will move to that cell and eat the ant. Otherwise the doodlebug moves according to the same rules as the ant. Note that a doodlebug cannot eat other doodlebugs.
Breed. If a doodlebug survives for eight time steps, then at the end of the time step it will spawn off a new doodlebug in the same manner as the ant.
Starve. If a doodlebug has not eaten an ant within the last three time steps, then at the end of the third time step it will starve and die. The doodlebug should then be removed from the grid of cells.
During one turn, all the doodlebugs should move before the ants.
Write a program to implement this simulation and draw the world using ASCII characters of "o" for an ant and "X" for a doodlebug. Create a class named Organism that encapsulates basic data common to both ants and doodlebugs. This class should have an overridden method named move that is defined in the derived classes of Ant and Doodlebug. You may need additional data structures to keep track of which critters have moved.

Initialize the world with 5 doodlebugs and 100 ants. After each time step prompt the user to press enter to move to the next time step. You should see a cyclical pattern between the population of predators and prey, although random perturbations may lead to the elimination of one or both species.

In this program you should implement classes Ant and DoodleBug with the following constructors and methods:

class Ant extends Organism {
public Ant() { ... }
public Ant(World world, int x, int y) { ... }
public boolean starve() { ... }
public void move() { ... }
public int getType() { ... }
public void breed() { ... }
}

class DoodleBug extends Organism {
public Doodlebug() { ... }
public Doodlebug(World world, int x, int y) { ... }
public void move() { ... }
public int getType() { ... }
public void breed() { ... }
public boolean starve() { ... }
}

/**
* This program simulates a 2D world with predators and prey.
* The predators (doodlebugs) and prey (ants) inherit from the
* Organism class that keeps track of basic information about each
* critter (time ticks since last bred, position in the world).
* <P>
* The 2D world is implemented as a separate class, World,
* that contains a 2D array of pointers to type Organism.
* <P>
* Normally the classes would be defined in separate files, but
* they are all included here for ease of use with CodeMate.
*/
import java.util.Scanner;

public class Simulation {
public static final int WORLDSIZE = 20;
public static final int INITIALANTS = 100;
public static final int INITIALBUGS = 5;
public static final int DOODLEBUG = 1;
public static final int ANT = 2;
public static final int ANTBREED = 3;
public static final int DOODLEBREED = 8;
public static final int DOODLESTARVE = 3;

/**
* Main driver method
*/
public static void main(String[] args) {
World w = new World();

// Randomly create 100 ants
int antcount = 0;
while (antcount < INITIALANTS) {
int x = (int) (Math.random() * WORLDSIZE);
int y = (int) (Math.random() * WORLDSIZE);

// Only put ant in empty spot
if (w.getAt(x, y) == null) {
antcount++;
Ant a1 = new Ant(w, x, y);
}
}

// Randomly create 5 doodlebugs
int doodlecount = 0;
while (doodlecount < INITIALBUGS) {
int x = (int) (Math.random() * WORLDSIZE);
int y = (int) (Math.random() * WORLDSIZE);

// Only put doodlebug in empty spot
if (w.getAt(x,y) == null) {
doodlecount++;
Doodlebug d1 = new Doodlebug(w, x, y);
}
}

Scanner keyboard = new Scanner(System.in);
String s = "";

// Run simulation forever, until user cancels
while (s.length() == 0) {
w.display();
w.simulateOneStep();
System.out.println();
System.out.println(
"Press enter for next step, any key (and enter) to end");
s = keyboard.nextLine();
}
}

}

/**
* The World class stores data about the world by creating a
* WORLDSIZE by WORLDSIZE array of type Organism.
* NULL indicates an empty spot, otherwise a valid object
* indicates an ant or doodlebug. To determine which,
* invoke the virtual function getType of Organism that should return
* ANT if the class is of type ant, and DOODLEBUG otherwise.
*/
class World {
private Organism[][] grid = null;

public World() {
grid = new Organism[Simulation.WORLDSIZE][Simulation.WORLDSIZE];
}

/**
* Returns the entry stored in the grid array at x,y
*/
public Organism getAt(int x, int y) {
if ((x >= 0) && (x < Simulation.WORLDSIZE) &&
(y >= 0) && (y < Simulation.WORLDSIZE)) {
return grid[x][y];
}
return null;
}

/**
* Sets the entry at x,y to the value passed in.
*/
public void setAt(int x, int y, Organism org) {
if ((x >= 0) && (x < Simulation.WORLDSIZE) &&
(y >= 0) && (y < Simulation.WORLDSIZE)) {
grid[x][y] = org;
}
}

/**
* Displays the world in ASCII. Uses o for ant, X for doodlebug.
*/
public void display() {
System.out.println();
System.out.println();
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
if (grid[i][j] == null) {
System.out.print(".");
}
else if (grid[i][j].getType() == Simulation.ANT) {
System.out.print("o");
}
else {
System.out.print("X");
}
}
System.out.println();
}
}

/**
* This is the main routine that simulates one turn in the world.
* First, a flag for each organism is used to indicate if it has moved.
* This is because we iterate through the grid starting from the top
* looking for an organism to move . If one moves down, we don't want
* to move it again when we reach it.
* <P>
* First move doodlebugs, then ants, and if they are still alive then
* we breed them.
*/
public void simulateOneStep() {
// First reset all organisms to not moved
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
if (grid[i][j] != null) {
grid[i][j].moved = false;
}
}
}

// Loop through cells in order and move if it's a Doodlebug
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
if ((grid[i][j] != null) &&
(grid[i][j].getType() == Simulation.DOODLEBUG)) {
if (! grid[i][j].moved) {
grid[i][j].moved = true; // Mark as moved
grid[i][j].move();
}
}
}
}

// Loop through cells in order and move if it's an Ant
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
if ((grid[i][j] != null) &&
(grid[i][j].getType() == Simulation.ANT)) {
if (! grid[i][j].moved) {
grid[i][j].moved = true; // Mark as moved
grid[i][j].move();
}
}
}
}

// Loop through cells in order and check if we should breed
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
// Kill off any doodlebugs that haven't eaten recently
if ((grid[i][j] != null) &&
(grid[i][j].getType() == Simulation.DOODLEBUG)) {
if (grid[i][j].starve()) {
grid[i][j] = null;
}
}
}
}

// Loop through cells in order and check if we should breed
for (int i = 0; i < Simulation.WORLDSIZE; i++) {
for (int j = 0; j < Simulation.WORLDSIZE; j++) {
// Only breed organisms that have moved, since
// breeding places new organisms on the map we
// don't want to try and breed those
if ((grid[i][j] != null) && (grid[i][j].moved)) {
grid[i][j].breed();
}
}
}
}

}

/**
* Definition for the Organism base class. Each organism has a reference
* back to the World object so it can move itself about in the world.
*/
abstract class Organism {
/**
* Position in the world
*/
protected int x;
protected int y;

/**
* Bool to indicate if moved this turn
*/
protected boolean moved;

/**
* Number of ticks since breeding
*/
protected int breedTicks;

protected World world;

public Organism() {
world = null;
moved = false;
breedTicks = 0;
x = 0;
y = 0;
}

public Organism(World world, int x, int y) {
this.world = world;
this.x = x;
this.y = y;
breedTicks = 0;
moved = false;
world.setAt(x, y, this);
}

public abstract void breed(); // Whether or not to breed
public abstract void move(); // Rules to move the critter
public abstract int getType(); // Return if ant or doodlebug
public abstract boolean starve(); // Determine if organism starves
}

Reference no: EM13940709

Questions Cloud

What fundamental assumptions of career criminal programs : What are some of the fundamental assumptions of career criminal programs? What limitations might these assumptions present in our efforts to identify and punish career criminals?
What is the slope of the cal : Draw the CAL of your portfolio on an expected return-standard deviation diagram. What is the slope of the CAL? Show the position of your client on your funds CAL
Compare and determine the smallest number : The main method that begins execution of Java application
Determine human resources requirements : Determine human resources requirements. Analyze the strategic and operational plans to determine human resource requirements and develop options for the delivery of human resource services.
Create a simple 2d predator-prey simulation. : The goal for this programming project is to create a simple 2D predator-prey simulation. In this simulation the prey are ants and the predators are doodlebugs. These critters live in a world composed of a 20x20 grid of cells.
What is ethical for the superintendent to do : Is it ethically justifiable to disregard the minor crime of prostitution if it is believed that it will assist in capturing more dangerous or violent criminals? Use relative statements and arguments to support your stand.
Calculate the vertical height raised : Calculate the vertical height raised, the final angular velocity of the drum, the work done, the input torque to the driving motor and the average power developed.
What types of agencies have the authority to operate jails : What types of agencies (aside from counties) have the authority to operate jails? Give a description and example for the different types of agencies that possess this ability.
What was the cost per unit and gross profit of each model : Assign the total 2014 manufacturing overhead costs to the two products using activity-based costing (ABC).  What was the cost per unit and gross profit of each model using ABC costing

Reviews

Write a Review

JAVA Programming Questions & Answers

  Write a class named month

Write a class named Month. The class should have an int field named monthNumber that holds the number of the month.

  Calculates the average test scores

You are given a list of students' names and their test scores. Design an algorithm that does the following: a. Calculates the average test scores.

  Write a method called printlevel

Write a method called printLevel that takes an integer n as a parameter and that prints the values at level n from left to right. The values should be printed one per line.

  Write a java program that prints the numbers from 1 to 125

Write a Java Program that prints the numbers from 1 to 125. But for multiles of three print "Batman" instead of the number and for the multiples of five print "Superman". For instances which are multiples of both three and five "JusticeLeague".

  Ood methodology

Your local police department wants to design new software to keep track of people, property, and criminal activity. List at least three classes you think should be in the design. For each class, identify some data members and methods.

  Hypothetical situation

Hypothetical Situation - A company lowers its price of an economy car a small amount   ($15,000 to $14,000) Sales go from 10,000 units to 50,000 units. Another company lowers its price on a luxury car a large amount ($80,000 to $40,000). Its sales go..

  Quadratic and double hashing

The methods you should use in building your has functions are linear, quadratic and double hashing. Your code should provide create, insert, ?nd and delete operations on that table.

  Write a reference class called ctatrain

writing a reference class that consist of the 2nd and 3rd instance variables below. my class should consist of an array of values in the 2nd instance variable

  Print the name and number

Question is to print the name and number you entered in order either asked by name or number.

  Savingsaccount and bankaccount objects

The only differences between SavingsAccount and BankAccount objects is that SavingsAccount have an interest rate and can compute interest when necessary. Add an instance variable and a method to SavingsAccount to allow for these items.

  What challenges in planning solution for programming problem

what are the three biggest challenges in planning and designing a solution for a programming problem? What can you do to overcome these challenges? How would you apply these techniques to the programs in this class?

  Write a test application named simpledatetest

Write a test application named SimpleDateTest that demonstrates class SimpleDate's capabilities

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd