IN JAVA LANGUAGE: The goal for this programming project is to create a Predator-
ID: 3822602 • Letter: I
Question
IN JAVA LANGUAGE:
The goal for this programming project is to create a Predator-Prey Simulation in a two-dimensional ecosystem based on agent-based modeling. The Predator and Prey will act as agents in an ecosystem in this simulation.
The ecosystem should be modeled as an N x N grid of cells. Only one prey can occupy a cell at a time. The grid is enclosed, so a prey always stays inside the grid of cells. A prey is not allowed to move outside of the eco-system.
Time is simulated in time steps. Each prey and predator agent performs some action in every time step.
The Prey follows the following rules at each time step:
• Move: Every time step, randomly try to move up, down, left, or right. If the cell in the selected direction is occupied or would move the prey off the grid then the prey stays in the current cell.
• Breed. If a prey survives for three time steps, then at the end of the third time step (i.e., after moving), the prey will breed. This is simulated by creating a new prey in an adjacent (up, down, left, or right) cell that is empty. If there is no empty cell available, no breeding occurs. Once an offspring is produced, the prey cannot produce an offspring until three more time steps have elapsed.
A Predator behaves according to the following model:
• Move. Every time step, if there is an adjacent cell (up, down, left, or right) occupied by a prey, then the predator will move to that cell and eat the prey. Otherwise, the predator moves according to the same rules as the prey. Note that a predator cannot eat other predator objects.
• Breed. If a predator survives for eight time steps, then at the end of the time step, it will spawn off a new predator in the same manner as the prey.
• Starve. If a predator has not eaten a prey within the last three time steps, then at the end of the third time step, it will starve and die. The predator should then be removed from the grid of cells. During one turn, all the predators should move before the preys.
Before the simulation begins, the initial positions of all Preys should be randomly assigned first. Then the initial positions of the Predators should be assigned next. Note that the Simulation stops when the number of time steps ends or when one or both species population become zero.
Implement a java GUI that will allow the user to interact with the system. A suggested GUI is given below. User should be able to enter the following through the GUI:
Initial Predator count
Initial Prey count
No. of row cells in the ecosystem
No. of column cells in the ecosystem
No. of time steps.
The user clicks the “Simulate” Button and this should run the simulation. Once the simulation is over, a separate window should be shown that shows how the population of predator and prey with respect to time (x-axis: time and y-axis: No. of predator and prey). Most likely, 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. The GUI should also have a button (“Positions”) which when clicked will simply print to the console the grid of cells as ASCII characters (‘x’: if cell is occupied by a Predator, ‘o’: if cell is occupied by a Prey, and ‘.’ If cell is empty).
General guidelines: In this class project, you are encouraged to follow the general guideline to an object-oriented design:
Identify the classes in the system.
Identify the responsibilities (attributes and methods) for each class.
Identify any class interactions or hierarchy to understand the order of implementation of the classes. Remember important class interactions (inheritance, aggregation, and composition).
Note that you might have to come back to your class definitions and add, remove, or adjust the responsibilities. You might even need to add or remove classes.
Create a UML class diagrams and class interactions (For this purpose, you can use regular pencil and paper since most likely you might edit your diagrams as your project progresses).
Implement the individual classes. While implementing the individual classes, don’t worry too much about the simulation of the system. The simulation should be implemented as a separate demo class (a GUI) at the end.
Explanation / Answer
package predator_prey_sim;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* PredatorPreySimGUI class
*
*/
public class PredatorPreySimGUI {
protected static int predatorCount=0;
protected static int preyCount=0;
protected static int rowCellsCount=-1;
protected static int columnCellsCount=-1;
protected static int timeStepsCount=-1;
protected static Cell cellsGrid[][];
protected static Prey preys[];
protected static Predator predators[];
protected static Random rand=new Random();
/**
* creates and shows GUI
*/
public static void createAndShowGUI()
{
JFrame frame=new JFrame("Predator Prey Simulation GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setSize(new Dimension(400, 400));
JPanel panel=new JPanel();
GridLayout gridLayout = new GridLayout(6, 2, 1, 1);
panel.setLayout(gridLayout);
JLabel predatorCountLabel=new JLabel("Initial Predator Count:");
JLabel preyCountLabel=new JLabel("Initial Prey Count:");
JLabel rowCellsCountLabel=new JLabel("Row Cells Count:");
JLabel columnCellsCountLabel=new JLabel("Column Cells Count:");
JLabel timeStepsCountLabel=new JLabel("Time Steps Count:");
JTextField predatorCountField=new JTextField();
JTextField preyCountField=new JTextField();
JTextField rowCellsCountField=new JTextField();
JTextField columnCellsCountField=new JTextField();
JTextField timeStepsCountField=new JTextField();
JButton simulateButton=new JButton("Simulate");
JButton positionsButton=new JButton("Positions");
simulateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(predatorCountField.getText().equals("") || preyCountField.getText().equals(""))
{
JOptionPane.showMessageDialog(frame, "Please enter values in fields");
}
else
{
predatorCount=Integer.parseInt(predatorCountField.getText());
preyCount=Integer.parseInt(preyCountField.getText());
rowCellsCount=Integer.parseInt(rowCellsCountField.getText());
columnCellsCount=Integer.parseInt(columnCellsCountField.getText());
timeStepsCount=Integer.parseInt(timeStepsCountField.getText());
try
{
cellsGrid=new Cell[rowCellsCount][columnCellsCount];
initializeCellsGrid();
preys=new Prey[preyCount];
predators=new Predator[predatorCount];
initializePreys();
initializePredators();
simulate();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
positionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
showPositions();
}
});
panel.add(predatorCountLabel,0,0);
panel.add(predatorCountField,0,1);
panel.add(preyCountLabel,1,0);
panel.add(preyCountField,1,1);
panel.add(rowCellsCountLabel,2,0);
panel.add(rowCellsCountField,2,1);
panel.add(columnCellsCountLabel,3,0);
panel.add(columnCellsCountField,3,1);
panel.add(timeStepsCountLabel,4,0);
panel.add(timeStepsCountField,4,1);
panel.add(simulateButton);
panel.add(positionsButton);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
/**
* initialize preys
* @throws Exception
*/
protected static void initializePreys() throws Exception {
// TODO Auto-generated method stub
int preyInitialized=0;
if(preyCount <= rowCellsCount*columnCellsCount)
{
for(int i=0;i<preyCount;i++)
{
int row=rand.nextInt(rowCellsCount);
//System.out.println(row);
int col=rand.nextInt(columnCellsCount);
//System.out.println(col);
if(cellsGrid[row][col].label.equals("Empty"))
{
cellsGrid[row][col].label="Prey";
Prey prey=new Prey(cellsGrid[row][col]);
preys[i]=prey;
preyInitialized++;
}
}
preyCount=preyInitialized;
System.out.println("Prey initialized:"+preyCount);
}
else
throw new Exception("Illegal Prey Count!!! Can't initialize.");
}
/**
* initialize predators
* @throws Exception
*/
protected static void initializePredators() throws Exception {
// TODO Auto-generated method stub
int predatorInitialized=0;
if(predatorCount <= rowCellsCount*columnCellsCount)
{
for(int i=0;i<predatorCount;i++)
{
int row=rand.nextInt(rowCellsCount);
//System.out.println(row);
int col=rand.nextInt(columnCellsCount);
//System.out.println(col);
if(cellsGrid[row][col].label.equals("Empty"))
{
cellsGrid[row][col].label="Predator";
Predator predator=new Predator(cellsGrid[row][col]);
predators[i]=predator;
predatorInitialized++;
}
}
predatorCount=predatorInitialized;
System.out.println("Predator initialized:"+predatorCount);
}
else
throw new Exception("Illegal Predator Count!!! Can't initialize.");
}
/**
* shows positions in cell grid
*/
protected static void showPositions() {
// TODO Auto-generated method stub
for(int i=0;i<rowCellsCount;i++)
{
for(int j=0;j<columnCellsCount;j++)
{
if(cellsGrid[i][j].label.equals("Predator"))
{
System.out.print("x ");
}
else if(cellsGrid[i][j].label.equals("Prey"))
{
System.out.print("o ");
}
else if(cellsGrid[i][j].label.equals("Empty"))
{
System.out.print(". ");
}
}
System.out.println();
}
}
/**
* Performs simulation
*/
private static void simulate()
{
System.out.println("Performing simulation");
}
/**
* initializes cells grid
*/
private static void initializeCellsGrid()
{
for(int i=0;i<rowCellsCount;i++)
{
for(int j=0;j<columnCellsCount;j++)
{
Cell cell=new Cell(i,j,"Empty");
cellsGrid[i][j]=cell;
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PredatorPreySimGUI.createAndShowGUI();
}
}
-----------------------------------------
2. Cell class: Cell.java
--------------------------------------------
package predator_prey_sim;
/**
*
* Cell class
*
*/
class Cell
{
int row;
int col;
String label;
/**
* @param row
* @param col
* @param label
*/
Cell(int row, int col, String label) {
this.row = row;
this.col = col;
this.label = label;
}
}
--------------------------------------
3. Predator class layout: Predator.java
---------------------------------
package predator_prey_sim;
/**
* Predator class
*
*/
public class Predator {
private Cell cell; //cell position of Predator
/**
* Constructor
*/
public Predator(Cell cell) {
// TODO Auto-generated constructor stub
this.cell=cell;
}
/**
* @return the cell
*/
Cell getCell() {
return cell;
}
/**
* @param cell the cell to set
*/
void setCell(Cell cell) {
this.cell = cell;
}
/**
* Every time step, if there is an adjacent cell (up, down, left, or right) occupied by a prey,
* then the predator will move to that cell and eat the prey. Otherwise, the predator moves according
* to the same rules as the prey. Note that a predator cannot eat other predator objects.
*/
void Move()
{
}
/**
* If a predator survives for eight time steps, then at the end of the time step, it will spawn off a new
* predator in the same manner as the prey.
*/
void Breed()
{
}
/**
* If a predator has not eaten a prey within the last three time steps, then at the end of the third time step,
* it will starve and die. The predator should then be removed from the grid of cells. During one turn, all the
* predators should move before the preys.
*/
void Starve()
{
}
}
----------------------------------
4. Prey class layout: Prey.java
-------------------------------------
package predator_prey_sim;
/**
* Prey class
*
*/
public class Prey {
private Cell cell; //cell position of Prey
/**
* Constructor
*/
public Prey(Cell cell) {
// TODO Auto-generated constructor stub
this.cell=cell;
}
/**
* Moves Prey randomly at each time step in up, down, right or left direction.
* If cell in selected direction is occupied or Prey is likely to fall
* off the grid, it would remanin in current cell.
*/
void Move()
{
}
/**
* If a prey survives for three time steps, then at the end of the third time step (i.e., after moving),
* the prey will breed. This is simulated by creating a new prey in an adjacent (up, down, left, or right)
* cell that is empty. If there is no empty cell available, no breeding occurs. Once an offspring is produced,
* the prey cannot produce an offspring until three more time steps have elapsed.
*/
void Breed()
{
}
/**
* @return the cell
*/
Cell getCell() {
return cell;
}
/**
* @param cell the cell to set
*/
void setCell(Cell cell) {
this.cell = cell;
}
}