Projet_V4

This commit is contained in:
Paul MATHY 2024-05-31 23:33:05 +02:00
parent ed239ade7e
commit 62a553b71f
22 changed files with 2444 additions and 0 deletions

10
- Copie.classpath Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
- Copie.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OOP</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

10
.classpath Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OOP</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

23
src - Copie/Main.java Normal file
View File

@ -0,0 +1,23 @@
/*
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("toto");
}
}*/
import windowInterface.MyInterface;
public class Main {
public static void main(String[] args) {
MyInterface mjf = new MyInterface();
mjf.setVisible(true);
}
}

View File

@ -0,0 +1,40 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
public abstract class Agent {
protected int x;
protected int y;
protected Color color;
protected Agent(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public Color getDisplayColor() {
return color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isInArea(int x, int y, int radius) {
int diffX = this.x-x;
int diffY = this.y-y;
int dist = (int) Math.floor(Math.sqrt(diffX*diffX+diffY*diffY));
return dist<radius;
}
// Does whatever the agent does during a step
// then returns a boolean
// if false, agent dies at end of turn
// see step function in Simulator
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
}

View File

@ -0,0 +1,17 @@
package backend;
public class Cell {
private int value;
public Cell(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

View File

@ -0,0 +1,103 @@
package backend;
import java.util.ArrayList;
public class Gride {
private int height;
private int width;
private ArrayList<ArrayList<Cell>> gride;
private Simulator simulator;
public Gride(int height, int width, Simulator tempSimulator) {
this.height = height;
this.width = width;
this.simulator = tempSimulator;
gride = new ArrayList<>(height);
for (int i = 0; i < height; i++) {
this.gride.add(i, new ArrayList<Cell>());
for (int j = 0; j < width; j++) {
this.gride.get(i).add(new Cell(0));
}
}
}
public int getheight() {
return this.height;
}
public int getwidth() {
return this.width;
}
public boolean isLoopingBorder() {
return simulator.isLoopingBorder();
}
public Cell getCell(int row,int column) {
return gride.get(row).get(column);
}
public void setCell(int row, int column, Cell cell){
this.gride.get(row).set(column, cell);
}
public int countAround(int row, int column) {
int count = 0;
boolean loopingBorder = isLoopingBorder();
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= column + 1; j++) {
if (i == row && j == column) {
continue;
}
int x = i;
int y = j;
if (loopingBorder) {
x = (x + width) % width;
y = (y + height) % height;
} else {
if (x < 0 || x >= width || y < 0 || y >= height) {
continue;
}
}
count += this.getCell(x, y).getValue();
}
}
return count;
}
//TODO : set agent (x y agent) load an agent to coordinates x,y
//TODO : set random (density) create a random gride of determined density
public void setRandom(double density) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
double random = Math.random();
if (random < density) {
gride.get(i).get(j).setValue(1);
} else {
gride.get(i).get(j).setValue(0);
}
}
}
System.out.println("Created a random field");
}
public void serialPrint(){
for (int i = 0; i < height; i++) {
System.out.print("\n");
for (int j = 0; j < width; j++) {
System.out.print(this.getCell(i, j).getValue() +" ");
}
}
}
}

View File

@ -0,0 +1,49 @@
package backend;
import java.util.ArrayList;
import windowInterface.MyInterface;
public class Rules {
//Attributes
private ArrayList<Integer> fieldSurviveValues;
private ArrayList<Integer> fieldBirthValues;
public Rules() {
fieldSurviveValues = new ArrayList<Integer>();
fieldBirthValues = new ArrayList<Integer>();
this.setConwayRules();
}
public void resetRules() {
fieldSurviveValues.clear();
fieldBirthValues.clear();
}
public void setConwayRules() {
this.fieldSurviveValues.clear();
this.fieldBirthValues.clear();
//Set Conway rules
this.fieldSurviveValues.add(2);
this.fieldSurviveValues.add(3);
this.fieldBirthValues.add(3);
}
public ArrayList<Integer> getSurviveValues(){
return fieldSurviveValues;
}
public ArrayList<Integer> getBirthValues(){
return fieldBirthValues;
}
}

View File

@ -0,0 +1,59 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
// example of basic animal.
// do not hesitate to make it more complex
// and DO add at least another species that interact with it
// for example wolves that eat Sheep
public class Sheep extends Agent {
int hunger;
Random rand;
Sheep(int x,int y){
//first we call the constructor of the superClass(Animal)
//with the values we want.
// here we decide that a Sheep is initially white using this constructor
super(x,y,Color.white);
// we give our sheep a hunger value of zero at birth
hunger = 0;
//we initialize the random number generator we will use to move randomly
rand = new Random();
}
/**
* action of the animal
* it can interact with the cells or with other animals
* as you wish
*/
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if(world.getCell(x, y)==1) {
world.setCell(x, y, 0);
} else {
hunger++;
}
this.moveRandom();
return hunger>10;
}
private void moveRandom() {
int direction = rand.nextInt(4);
if(direction == 0) {
x+=1;
}
if(direction == 1) {
y+=1;
}
if(direction == 2) {
x-=1;
}
if(direction == 3) {
y-=1;
}
}
}

View File

@ -0,0 +1,413 @@
package backend;
import java.util.ArrayList;
import java.util.ListIterator;
import windowInterface.MyInterface;
public class Simulator extends Thread {
private MyInterface mjf;
//Size of the grid
private final int COL_NUM = 100;
private final int LINE_NUM = 100;
private final int LIFE_TYPE_NUM = 4;
private final int LIFE_AREA_RADIUS = 1;
private final int ANIMAL_AREA_RADIUS = 2;
//private ArrayList<Integer> fieldSurviveValues;
//private ArrayList<Integer> fieldBirthValues;
private ArrayList<Agent> agents;
private boolean stopFlag;
private boolean pauseFlag;
private boolean loopingBorder;
private boolean clickActionFlag;
private int loopDelay = 150;
//TODO : add missing attribute(s)
private double randomDansitySlider = 0.5;
private int width;
private int height;
private Gride gride;
//Step put here to be reset when generate new field
private int stepCount=0;
private Rules rules;
public Simulator(MyInterface mjfParam) {
mjf = mjfParam;
stopFlag=false;
pauseFlag=false;
loopingBorder=false;
clickActionFlag=true;
agents = new ArrayList<Agent>();
//fieldSurviveValues = new ArrayList<Integer>();
//fieldBirthValues = new ArrayList<Integer>();
this.width=COL_NUM;
this.height=LINE_NUM;
gride = new Gride(height, width, this);
//Reset rules to Conway rules
//this.resetRules();
rules = new Rules();
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public void run() {
//int stepCount=0;
System.out.println("Step Count: "+ stepCount);
//Set label when starting
mjf.setClickBanner("click : " + this.clickActionName());
mjf.setBorderBanner("border : " + (this.isLoopingBorder()?"loop":"closed"));
while(!stopFlag) {
stepCount++;
makeStep();
mjf.update(stepCount);
try {
Thread.sleep(loopDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(pauseFlag && !stopFlag) {
try {
Thread.sleep(loopDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void makeStep() {
ListIterator<Agent> iter = agents.listIterator();
while(iter.hasNext()){
Agent agent = iter.next();
//System.out.println(agent.getX() + "," + agent.getY());
ArrayList<Agent> neighbors = this.getNeighboringAnimals(
agent.getX(),
agent.getY(),
ANIMAL_AREA_RADIUS);
if(!agent.liveTurn(
neighbors,
this)) {
iter.remove();
}
}
/*
for(Agent agent : agents) {
ArrayList<Agent> neighbors =
this.getNeighboringAnimals(
agent.getX(),
agent.getY(),
ANIMAL_AREA_RADIUS);
if(!agent.liveTurn(
neighbors,
this)) {
agents.remove(agent);
}
}
*/
this.applyStep();
}
public void stopSimu() {
stopFlag=true;
}
public void togglePause() {
pauseFlag = !pauseFlag;
}
public void clickCell(int x, int y) {
int currentCellValue = getCell(x, y);
if (clickActionFlag == true) {
int newCellValue = 0;
if (currentCellValue == 0) {
newCellValue = 1;
} else {
newCellValue = 0;
}
this.setCell(x, y, newCellValue);
} else {
//Apply sheep /agent here
this.agents.add(new Sheep(x, y));
}
return;
}
public int getCell(int x, int y) {
return this.gride.getCell(x,y).getValue();
}
public ArrayList<Agent> getAnimals(){
return agents;
}
public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius){
ArrayList<Agent> inArea = new ArrayList<Agent>();
for(int i=0;i<agents.size();i++) {
Agent agent = agents.get(i);
if(agent.isInArea(x,y,radius)) {
inArea.add(agent);
}
}
return inArea;
}
public void setCell(int x, int y, int val) {
this.gride.getCell(x, y).setValue(val);
}
public void countAround(int x, int y) {
this.gride.countAround(x, y);
}
public ArrayList<String> getSaveState() {
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[this.width];
//Store the state of the GRID
for(int x=0 ;x<this.width; x++) {
for(int y=0 ;y<this.width; y++) {
strArrayLine[y] = Integer.toString(getCell(y, x));
}
System.out.println(String.join(";", strArrayLine));
strArrayList.add(String.join(";", strArrayLine));
}
return strArrayList;
}
// Load a grid from file
public void loadSaveState(ArrayList<String> lines) {
if(lines.size()<=0) {
return;
}
String firstLine = lines.get(0);
String[] firstLineElements = firstLine.split(";");
if(firstLineElements.length<=0) {
return;
}
for(int y =0; y<lines.size();y++) {
String line = lines.get(y);
String[] lineElements = line.split(";");
for(int x=0; x<lineElements.length;x++) {
String elem = lineElements[x];
int value = Integer.parseInt(elem);
setCell(x, y, value);
}
}
//Reset rules
rules.setConwayRules();
//Reset Agents
this.agents.clear();
}
private void resetRules() {
rules.resetRules();
}
public void generateRandom(float chanceOfLife) {
this.gride.setRandom(chanceOfLife);
//Reset the steps
stepCount = 0;
this.mjf.update(stepCount);
}
public boolean isLoopingBorder() {
return loopingBorder;
}
public void toggleLoopingBorder() {
loopingBorder = !loopingBorder;
}
public void setLoopDelay(int delay) {
loopDelay = delay;
}
public void toggleClickAction() {
clickActionFlag = !clickActionFlag;
}
public ArrayList<String> getRule() {
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[rules.getSurviveValues().size()];
//Add survive values
for(int x=0; x<rules.getSurviveValues().size();x++) {
strArrayLine[x] = Integer.toString(rules.getSurviveValues().get(x));
}
strArrayList.add(String.join(";", strArrayLine));
//New array for Birth values
strArrayLine = new String[rules.getBirthValues().size()];
//Add born values
for(int x=0; x<rules.getBirthValues().size();x++) {
strArrayLine[x] = Integer.toString(rules.getBirthValues().get(x));
}
strArrayList.add(String.join(";", strArrayLine));
return strArrayList;
}
public void loadRule(ArrayList<String> lines) {
if(lines.size()<=0) {
System.out.println("empty rule file");
return;
}
rules.resetRules();
String surviveLine = lines.get(0);
String birthLine = lines.get(1);
String[] surviveElements = surviveLine.split(";");
//Load the values to survive
for(int x=0; x<surviveElements.length;x++) {
String elem = surviveElements[x];
int value = Integer.parseInt(elem);
rules.getSurviveValues().add(value);
}
//Load the values given birth
String[] birthElements = birthLine.split(";");
for(int x=0; x<birthElements.length;x++) {
String elem = birthElements[x];
int value = Integer.parseInt(elem);
rules.getBirthValues().add(value);
}
}
public void applyStep() {
Gride newGrideUpdated = new Gride(this.height, this.width, this);
//System.out.println("New Iteration");
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
int cellValue = this.gride.getCell(i, j).getValue();
int newCellValue = cellValue;
int count = this.gride.countAround(i, j);
if (cellValue == 1) {
//Check that count is one of the value making survive the cell
if (rules.getSurviveValues().contains(count)) {
newCellValue = 1;
} else {
newCellValue = 0;
}
} else {
//Check that count is one of the value making generate a cell
if (rules.getBirthValues().contains(count)) {
newCellValue = 1;
}
}
newGrideUpdated.setCell(i, j, new Cell(newCellValue));
//System.out.println("applyStep called : " + newGrideUpdated.getCell(i, j).getValue() + " at " + i + " " + j);
}
}
gride = newGrideUpdated;
}
public ArrayList<String> getAgentsSave() {
//TODO : Same idea as the other save method, but for agents
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[this.agents.size()];
for(int ii=0;ii<this.agents.size();ii++) {
strArrayLine[ii] = this.agents.get(ii).getX() + "," + this.agents.get(ii).getY();
}
strArrayList.add(String.join(";", strArrayLine));
return strArrayList;
}
public void loadAgents(ArrayList<String> stringArray) {
if(stringArray.size()<=0) {
System.out.println("empty rule file");
return;
}
//Get the first line assuming it contains coordinates under format: X1,Y1;X2,Y2;X3,Y3
String strFirstLine = stringArray.get(0);
String[] strListCoordinates = strFirstLine.split(";");
//Loop on agent's coordinates and create one agent for each X,Y
for(int ii=0; ii<strListCoordinates.length;ii++) {
String coordinate = strListCoordinates[ii];
int commaPosition = coordinate.indexOf(",");
int x = Integer.parseInt(coordinate.substring(0,commaPosition));
int y = Integer.parseInt(coordinate.substring(commaPosition+1));
//Add an agent to the lista at x,y position
agents.add(new Sheep(x, y));
}
}
/**
* used by label in interface to show the active click action
* @return String representation of click action
*/
public String clickActionName() {
// TODO : initially return "sheep" or "cell"
// depending on clickActionFlag
if (clickActionFlag) {
return "cell";
} else {
return "sheep";
}
}
}

View File

@ -0,0 +1,94 @@
package windowInterface;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JPanel;
import backend.Agent;
import backend.Simulator;
public class JPanelDraw extends JPanel {
private static final long serialVersionUID = 1L;
private Simulator mySimu;
private MyInterface interfaceGlobal;
public JPanelDraw(MyInterface itf) {
super();
mySimu = null;
interfaceGlobal = itf;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// System.out.println(me);
if(mySimu == null) {
interfaceGlobal.instantiateSimu();
}
int x = (me.getX()*mySimu.getWidth())/getWidth();
int y = (me.getY()*mySimu.getHeight())/getHeight();
mySimu.clickCell(x,y);
repaint();
}
});
}
public void setSimu(Simulator simu) {
mySimu = simu;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.black);
if (mySimu != null) {
// Draw Interface from state of simulator
float cellWidth = (float)this.getWidth()/(float)mySimu.getWidth();
float cellHeight = (float)this.getHeight()/(float)mySimu.getHeight();
g.setColor(Color.gray);
for(int x=0; x<mySimu.getWidth();x++) {
int graphX = Math.round(x*cellWidth);
g.drawLine(graphX, 0, graphX, this.getHeight());
}
for (int y=0; y<mySimu.getHeight(); y++) {
int graphY = Math.round(y*cellHeight);
g.drawLine(0, graphY, this.getWidth(), graphY);
}
for(int x=0; x<mySimu.getWidth();x++) {
for (int y=0; y<mySimu.getHeight(); y++) {
int cellContent = mySimu.getCell(x,y);
if(cellContent == 0) {
continue;
}
if(cellContent == 1) {
g.setColor(Color.green);
}
if(cellContent == 2) {
g.setColor(Color.yellow);
}
if(cellContent == 3) {
g.setColor(Color.cyan);
}
g.fillRect(
(int) Math.round(x*cellWidth),
(int) Math.round(y*cellHeight),
(int) Math.round(cellWidth),
(int) Math.round(cellHeight)
);
}
}
for (Agent animal:mySimu.getAnimals()){
g.setColor(animal.getDisplayColor());
g.fillOval((int)Math.round(animal.getX()*cellWidth),
(int)Math.round(animal.getY()*cellHeight),
(int)Math.round(cellWidth/2),
(int)Math.round(cellHeight/2));
}
}
}
}

View File

@ -0,0 +1,397 @@
package windowInterface;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import backend.Simulator;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.event.ActionEvent;
public class MyInterface extends JFrame {
private static final long serialVersionUID = -6840815447618468846L;
private JPanel contentPane;
private JLabel stepLabel;
private JLabel borderLabel;
private JLabel speedLabel;
private JPanelDraw panelDraw;
private Simulator mySimu=null;
private JSlider randSlider;
private JSlider speedSlider;
private JLabel clickLabel;
/**
* Create the frame.
*/
public MyInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10, 10, 700, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panelTop = new JPanel();
contentPane.add(panelTop, BorderLayout.NORTH);
JPanel panelRight = new JPanel();
panelRight.setLayout(new GridLayout(12,1));
contentPane.add(panelRight, BorderLayout.EAST);
JButton btnGo = new JButton("Start/Pause");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonGo();
}
});
panelTop.add(btnGo);
JButton btnClickAct = new JButton("Toggle Click");
btnClickAct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonToggleClickAction();
}
});
panelTop.add(btnClickAct);
stepLabel = new JLabel("Step : X");
panelTop.add(stepLabel);
speedLabel = new JLabel("speed slider : ");
panelTop.add(speedLabel);
speedSlider = new JSlider();
speedSlider.setValue(3);
speedSlider.setMinimum(0);
speedSlider.setMaximum(10);
speedSlider.setOrientation(SwingConstants.HORIZONTAL);
speedSlider.setPreferredSize(new Dimension(100,30));
speedSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
changeSpeed();
}
});
panelTop.add(speedSlider);
// JButton btnSpeed = new JButton("Set Speed");
// btnSpeed.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// clicButtonSpeed();
// }
// });
// panelTop.add(btnSpeed);
JButton btnLoad = new JButton("Load World");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadFileButton();
}
});
panelRight.add(btnLoad);
JButton btnSave = new JButton("Save World");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveToFileButton();
}
});
panelRight.add(btnSave);
JButton btnLoadRule = new JButton("Load Rule");
btnLoadRule.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadRuleFileButton();
}
});
panelRight.add(btnLoadRule);
JButton btnSaveRule = new JButton("Save Rule");
btnSaveRule.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveRuleToFileButton();
}
});
panelRight.add(btnSaveRule);
JButton btnLoadAgents = new JButton("Load Agents");
btnLoadAgents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadAgentsFileButton();;
}
});
panelRight.add(btnLoadAgents);
JButton btnSaveAgents = new JButton("Save Agents");
btnSaveAgents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveAgentsToFileButton();
}
});
panelRight.add(btnSaveAgents);
JButton btnRandGen = new JButton("Random Field");
btnRandGen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
generateRandomBoard();
}
});
panelRight.add(btnRandGen);
JLabel randLabel = new JLabel("random density slider :");
panelRight.add(randLabel);
randSlider = new JSlider();
randSlider.setValue(50);
randSlider.setMinimum(0);
randSlider.setMaximum(100);
randSlider.setPreferredSize(new Dimension(30,200));
panelRight.add(randSlider);
JButton btnBorder = new JButton("Toggle Border");
btnBorder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonBorder();
}
});
panelRight.add(btnBorder);
panelDraw = new JPanelDraw(this);
contentPane.add(panelDraw, BorderLayout.CENTER);
instantiateSimu();
borderLabel = new JLabel("border : X");
panelRight.add(borderLabel);
borderLabel.setText("border : " +
(mySimu.isLoopingBorder()?"loop":"closed"));
clickLabel = new JLabel("click : X");
panelRight.add(clickLabel);
clickLabel.setText("click : " + mySimu.clickActionName());
}
public void setStepBanner(String s) {
stepLabel.setText(s);
}
public void setBorderBanner(String s) {
borderLabel.setText(s);
}
public void setClickBanner(String s) {
clickLabel.setText(s);
}
public JPanelDraw getPanelDessin() {
return panelDraw;
}
public void instantiateSimu() {
if(mySimu==null) {
mySimu = new Simulator(this);
panelDraw.setSimu(mySimu);
}
}
public void clicButtonGo() {
this.instantiateSimu();
if(!mySimu.isAlive()) {
mySimu.start();
} else {
mySimu.togglePause();
}
}
public void clicButtonToggleClickAction() {
if(mySimu != null) {
mySimu.toggleClickAction();
clickLabel.setText("click : " + mySimu.clickActionName());
}
}
public void clicButtonBorder() {
if(mySimu != null) {
mySimu.toggleLoopingBorder();
borderLabel.setText("border : " +
(mySimu.isLoopingBorder()?"loop":"closed"));
}
}
public void generateRandomBoard() {
this.instantiateSimu();
float chanceOfLife = ((float)randSlider.getValue())/((float)randSlider.getMaximum());
mySimu.generateRandom(chanceOfLife);
panelDraw.repaint();
}
public void changeSpeed() {
if(mySimu != null) {
int delay = (int)Math.pow(2, 10-speedSlider.getValue());
mySimu.setLoopDelay(delay);
} else {
speedSlider.setValue(3);
}
}
public void clicLoadFileButton() {
Simulator loadedSim = new Simulator(this);
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
if(mySimu != null) {
mySimu.stopSimu();
this.eraseLabels();
}
loadedSim.loadSaveState(stringArray);
mySimu = loadedSim;
panelDraw.setSimu(mySimu);
this.repaint();
}
}
public void clicLoadRuleFileButton() {
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
mySimu.loadRule(stringArray);
this.repaint();
}
}
public void clicLoadAgentsFileButton() {
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
mySimu.loadAgents(stringArray);
this.repaint();
}
}
public void clicSaveToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getSaveState();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public void clicSaveRuleToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getRule();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public void clicSaveAgentsToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getAgentsSave();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public String SelectFile() {
String s;
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a file");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
s=chooser.getSelectedFile().toString();
} else {
System.out.println("No Selection ");
s="";
}
return s;
}
public void writeFile(String fileName, String[] content) {
FileWriter csvWriter;
try {
csvWriter = new FileWriter(fileName);
for (String row : content) {
csvWriter.append(row);
csvWriter.append("\n");
}
csvWriter.flush();
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void update (int stepCount) {
this.setStepBanner("Step : "+ stepCount);
this.repaint();
}
public void eraseLabels() {
this.setStepBanner("Step : X");
this.setBorderBanner("border : X");
this.setClickBanner("click : X");
speedSlider.setValue(3);
}
}

23
src/Main.java Normal file
View File

@ -0,0 +1,23 @@
/*
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("toto");
}
}*/
import windowInterface.MyInterface;
public class Main {
public static void main(String[] args) {
MyInterface mjf = new MyInterface();
mjf.setVisible(true);
}
}

40
src/backend/Agent.java Normal file
View File

@ -0,0 +1,40 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
public abstract class Agent {
protected int x;
protected int y;
protected Color color;
protected Agent(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public Color getDisplayColor() {
return color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isInArea(int x, int y, int radius) {
int diffX = this.x-x;
int diffY = this.y-y;
int dist = (int) Math.floor(Math.sqrt(diffX*diffX+diffY*diffY));
return dist<radius;
}
// Does whatever the agent does during a step
// then returns a boolean
// if false, agent dies at end of turn
// see step function in Simulator
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
}

17
src/backend/Cell.java Normal file
View File

@ -0,0 +1,17 @@
package backend;
public class Cell {
private int value;
public Cell(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

103
src/backend/Gride.java Normal file
View File

@ -0,0 +1,103 @@
package backend;
import java.util.ArrayList;
public class Gride {
private int height;
private int width;
private ArrayList<ArrayList<Cell>> gride;
private Simulator simulator;
public Gride(int height, int width, Simulator tempSimulator) {
this.height = height;
this.width = width;
this.simulator = tempSimulator;
gride = new ArrayList<>(height);
for (int i = 0; i < height; i++) {
this.gride.add(i, new ArrayList<Cell>());
for (int j = 0; j < width; j++) {
this.gride.get(i).add(new Cell(0));
}
}
}
public int getheight() {
return this.height;
}
public int getwidth() {
return this.width;
}
public boolean isLoopingBorder() {
return simulator.isLoopingBorder();
}
public Cell getCell(int row,int column) {
return gride.get(row).get(column);
}
public void setCell(int row, int column, Cell cell){
this.gride.get(row).set(column, cell);
}
public int countAround(int row, int column) {
int count = 0;
boolean loopingBorder = isLoopingBorder();
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= column + 1; j++) {
if (i == row && j == column) {
continue;
}
int x = i;
int y = j;
if (loopingBorder) {
x = (x + width) % width;
y = (y + height) % height;
} else {
if (x < 0 || x >= width || y < 0 || y >= height) {
continue;
}
}
count += this.getCell(x, y).getValue();
}
}
return count;
}
//TODO : set agent (x y agent) load an agent to coordinates x,y
//TODO : set random (density) create a random gride of determined density
public void setRandom(double density) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
double random = Math.random();
if (random < density) {
gride.get(i).get(j).setValue(1);
} else {
gride.get(i).get(j).setValue(0);
}
}
}
System.out.println("Created a random field");
}
public void serialPrint(){
for (int i = 0; i < height; i++) {
System.out.print("\n");
for (int j = 0; j < width; j++) {
System.out.print(this.getCell(i, j).getValue() +" ");
}
}
}
}

49
src/backend/Rules.java Normal file
View File

@ -0,0 +1,49 @@
package backend;
import java.util.ArrayList;
import windowInterface.MyInterface;
public class Rules {
//Attributes
private ArrayList<Integer> fieldSurviveValues;
private ArrayList<Integer> fieldBirthValues;
public Rules() {
fieldSurviveValues = new ArrayList<Integer>();
fieldBirthValues = new ArrayList<Integer>();
this.setConwayRules();
}
public void resetRules() {
fieldSurviveValues.clear();
fieldBirthValues.clear();
}
public void setConwayRules() {
this.fieldSurviveValues.clear();
this.fieldBirthValues.clear();
//Set Conway rules
this.fieldSurviveValues.add(2);
this.fieldSurviveValues.add(3);
this.fieldBirthValues.add(3);
}
public ArrayList<Integer> getSurviveValues(){
return fieldSurviveValues;
}
public ArrayList<Integer> getBirthValues(){
return fieldBirthValues;
}
}

59
src/backend/Sheep.java Normal file
View File

@ -0,0 +1,59 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
// example of basic animal.
// do not hesitate to make it more complex
// and DO add at least another species that interact with it
// for example wolves that eat Sheep
public class Sheep extends Agent {
int hunger;
Random rand;
Sheep(int x,int y){
//first we call the constructor of the superClass(Animal)
//with the values we want.
// here we decide that a Sheep is initially white using this constructor
super(x,y,Color.white);
// we give our sheep a hunger value of zero at birth
hunger = 0;
//we initialize the random number generator we will use to move randomly
rand = new Random();
}
/**
* action of the animal
* it can interact with the cells or with other animals
* as you wish
*/
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if(world.getCell(x, y)==1) {
world.setCell(x, y, 0);
} else {
hunger++;
}
this.moveRandom();
return hunger>10;
}
private void moveRandom() {
int direction = rand.nextInt(4);
if(direction == 0) {
x+=1;
}
if(direction == 1) {
y+=1;
}
if(direction == 2) {
x-=1;
}
if(direction == 3) {
y-=1;
}
}
}

413
src/backend/Simulator.java Normal file
View File

@ -0,0 +1,413 @@
package backend;
import java.util.ArrayList;
import java.util.ListIterator;
import windowInterface.MyInterface;
public class Simulator extends Thread {
private MyInterface mjf;
//Size of the grid
private final int COL_NUM = 100;
private final int LINE_NUM = 100;
private final int LIFE_TYPE_NUM = 4;
private final int LIFE_AREA_RADIUS = 1;
private final int ANIMAL_AREA_RADIUS = 2;
//private ArrayList<Integer> fieldSurviveValues;
//private ArrayList<Integer> fieldBirthValues;
private ArrayList<Agent> agents;
private boolean stopFlag;
private boolean pauseFlag;
private boolean loopingBorder;
private boolean clickActionFlag;
private int loopDelay = 150;
//TODO : add missing attribute(s)
private double randomDansitySlider = 0.5;
private int width;
private int height;
private Gride gride;
//Step put here to be reset when generate new field
private int stepCount=0;
private Rules rules;
public Simulator(MyInterface mjfParam) {
mjf = mjfParam;
stopFlag=false;
pauseFlag=false;
loopingBorder=false;
clickActionFlag=true;
agents = new ArrayList<Agent>();
//fieldSurviveValues = new ArrayList<Integer>();
//fieldBirthValues = new ArrayList<Integer>();
this.width=COL_NUM;
this.height=LINE_NUM;
gride = new Gride(height, width, this);
//Reset rules to Conway rules
//this.resetRules();
rules = new Rules();
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public void run() {
//int stepCount=0;
System.out.println("Step Count: "+ stepCount);
//Set label when starting
mjf.setClickBanner("click : " + this.clickActionName());
mjf.setBorderBanner("border : " + (this.isLoopingBorder()?"loop":"closed"));
while(!stopFlag) {
stepCount++;
makeStep();
mjf.update(stepCount);
try {
Thread.sleep(loopDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(pauseFlag && !stopFlag) {
try {
Thread.sleep(loopDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void makeStep() {
ListIterator<Agent> iter = agents.listIterator();
while(iter.hasNext()){
Agent agent = iter.next();
//System.out.println(agent.getX() + "," + agent.getY());
ArrayList<Agent> neighbors = this.getNeighboringAnimals(
agent.getX(),
agent.getY(),
ANIMAL_AREA_RADIUS);
if(!agent.liveTurn(
neighbors,
this)) {
iter.remove();
}
}
/*
for(Agent agent : agents) {
ArrayList<Agent> neighbors =
this.getNeighboringAnimals(
agent.getX(),
agent.getY(),
ANIMAL_AREA_RADIUS);
if(!agent.liveTurn(
neighbors,
this)) {
agents.remove(agent);
}
}
*/
this.applyStep();
}
public void stopSimu() {
stopFlag=true;
}
public void togglePause() {
pauseFlag = !pauseFlag;
}
public void clickCell(int x, int y) {
int currentCellValue = getCell(x, y);
if (clickActionFlag == true) {
int newCellValue = 0;
if (currentCellValue == 0) {
newCellValue = 1;
} else {
newCellValue = 0;
}
this.setCell(x, y, newCellValue);
} else {
//Apply sheep /agent here
this.agents.add(new Sheep(x, y));
}
return;
}
public int getCell(int x, int y) {
return this.gride.getCell(x,y).getValue();
}
public ArrayList<Agent> getAnimals(){
return agents;
}
public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius){
ArrayList<Agent> inArea = new ArrayList<Agent>();
for(int i=0;i<agents.size();i++) {
Agent agent = agents.get(i);
if(agent.isInArea(x,y,radius)) {
inArea.add(agent);
}
}
return inArea;
}
public void setCell(int x, int y, int val) {
this.gride.getCell(x, y).setValue(val);
}
public void countAround(int x, int y) {
this.gride.countAround(x, y);
}
public ArrayList<String> getSaveState() {
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[this.width];
//Store the state of the GRID
for(int x=0 ;x<this.width; x++) {
for(int y=0 ;y<this.width; y++) {
strArrayLine[y] = Integer.toString(getCell(y, x));
}
System.out.println(String.join(";", strArrayLine));
strArrayList.add(String.join(";", strArrayLine));
}
return strArrayList;
}
// Load a grid from file
public void loadSaveState(ArrayList<String> lines) {
if(lines.size()<=0) {
return;
}
String firstLine = lines.get(0);
String[] firstLineElements = firstLine.split(";");
if(firstLineElements.length<=0) {
return;
}
for(int y =0; y<lines.size();y++) {
String line = lines.get(y);
String[] lineElements = line.split(";");
for(int x=0; x<lineElements.length;x++) {
String elem = lineElements[x];
int value = Integer.parseInt(elem);
setCell(x, y, value);
}
}
//Reset rules
rules.setConwayRules();
//Reset Agents
this.agents.clear();
}
private void resetRules() {
rules.resetRules();
}
public void generateRandom(float chanceOfLife) {
this.gride.setRandom(chanceOfLife);
//Reset the steps
stepCount = 0;
this.mjf.update(stepCount);
}
public boolean isLoopingBorder() {
return loopingBorder;
}
public void toggleLoopingBorder() {
loopingBorder = !loopingBorder;
}
public void setLoopDelay(int delay) {
loopDelay = delay;
}
public void toggleClickAction() {
clickActionFlag = !clickActionFlag;
}
public ArrayList<String> getRule() {
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[rules.getSurviveValues().size()];
//Add survive values
for(int x=0; x<rules.getSurviveValues().size();x++) {
strArrayLine[x] = Integer.toString(rules.getSurviveValues().get(x));
}
strArrayList.add(String.join(";", strArrayLine));
//New array for Birth values
strArrayLine = new String[rules.getBirthValues().size()];
//Add born values
for(int x=0; x<rules.getBirthValues().size();x++) {
strArrayLine[x] = Integer.toString(rules.getBirthValues().get(x));
}
strArrayList.add(String.join(";", strArrayLine));
return strArrayList;
}
public void loadRule(ArrayList<String> lines) {
if(lines.size()<=0) {
System.out.println("empty rule file");
return;
}
rules.resetRules();
String surviveLine = lines.get(0);
String birthLine = lines.get(1);
String[] surviveElements = surviveLine.split(";");
//Load the values to survive
for(int x=0; x<surviveElements.length;x++) {
String elem = surviveElements[x];
int value = Integer.parseInt(elem);
rules.getSurviveValues().add(value);
}
//Load the values given birth
String[] birthElements = birthLine.split(";");
for(int x=0; x<birthElements.length;x++) {
String elem = birthElements[x];
int value = Integer.parseInt(elem);
rules.getBirthValues().add(value);
}
}
public void applyStep() {
Gride newGrideUpdated = new Gride(this.height, this.width, this);
//System.out.println("New Iteration");
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
int cellValue = this.gride.getCell(i, j).getValue();
int newCellValue = cellValue;
int count = this.gride.countAround(i, j);
if (cellValue == 1) {
//Check that count is one of the value making survive the cell
if (rules.getSurviveValues().contains(count)) {
newCellValue = 1;
} else {
newCellValue = 0;
}
} else {
//Check that count is one of the value making generate a cell
if (rules.getBirthValues().contains(count)) {
newCellValue = 1;
}
}
newGrideUpdated.setCell(i, j, new Cell(newCellValue));
//System.out.println("applyStep called : " + newGrideUpdated.getCell(i, j).getValue() + " at " + i + " " + j);
}
}
gride = newGrideUpdated;
}
public ArrayList<String> getAgentsSave() {
//TODO : Same idea as the other save method, but for agents
ArrayList<String> strArrayList = new ArrayList<>();
String[] strArrayLine = new String[this.agents.size()];
for(int ii=0;ii<this.agents.size();ii++) {
strArrayLine[ii] = this.agents.get(ii).getX() + "," + this.agents.get(ii).getY();
}
strArrayList.add(String.join(";", strArrayLine));
return strArrayList;
}
public void loadAgents(ArrayList<String> stringArray) {
if(stringArray.size()<=0) {
System.out.println("empty rule file");
return;
}
//Get the first line assuming it contains coordinates under format: X1,Y1;X2,Y2;X3,Y3
String strFirstLine = stringArray.get(0);
String[] strListCoordinates = strFirstLine.split(";");
//Loop on agent's coordinates and create one agent for each X,Y
for(int ii=0; ii<strListCoordinates.length;ii++) {
String coordinate = strListCoordinates[ii];
int commaPosition = coordinate.indexOf(",");
int x = Integer.parseInt(coordinate.substring(0,commaPosition));
int y = Integer.parseInt(coordinate.substring(commaPosition+1));
//Add an agent to the lista at x,y position
agents.add(new Sheep(x, y));
}
}
/**
* used by label in interface to show the active click action
* @return String representation of click action
*/
public String clickActionName() {
// TODO : initially return "sheep" or "cell"
// depending on clickActionFlag
if (clickActionFlag) {
return "cell";
} else {
return "sheep";
}
}
}

View File

@ -0,0 +1,94 @@
package windowInterface;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JPanel;
import backend.Agent;
import backend.Simulator;
public class JPanelDraw extends JPanel {
private static final long serialVersionUID = 1L;
private Simulator mySimu;
private MyInterface interfaceGlobal;
public JPanelDraw(MyInterface itf) {
super();
mySimu = null;
interfaceGlobal = itf;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// System.out.println(me);
if(mySimu == null) {
interfaceGlobal.instantiateSimu();
}
int x = (me.getX()*mySimu.getWidth())/getWidth();
int y = (me.getY()*mySimu.getHeight())/getHeight();
mySimu.clickCell(x,y);
repaint();
}
});
}
public void setSimu(Simulator simu) {
mySimu = simu;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.black);
if (mySimu != null) {
// Draw Interface from state of simulator
float cellWidth = (float)this.getWidth()/(float)mySimu.getWidth();
float cellHeight = (float)this.getHeight()/(float)mySimu.getHeight();
g.setColor(Color.gray);
for(int x=0; x<mySimu.getWidth();x++) {
int graphX = Math.round(x*cellWidth);
g.drawLine(graphX, 0, graphX, this.getHeight());
}
for (int y=0; y<mySimu.getHeight(); y++) {
int graphY = Math.round(y*cellHeight);
g.drawLine(0, graphY, this.getWidth(), graphY);
}
for(int x=0; x<mySimu.getWidth();x++) {
for (int y=0; y<mySimu.getHeight(); y++) {
int cellContent = mySimu.getCell(x,y);
if(cellContent == 0) {
continue;
}
if(cellContent == 1) {
g.setColor(Color.green);
}
if(cellContent == 2) {
g.setColor(Color.yellow);
}
if(cellContent == 3) {
g.setColor(Color.cyan);
}
g.fillRect(
(int) Math.round(x*cellWidth),
(int) Math.round(y*cellHeight),
(int) Math.round(cellWidth),
(int) Math.round(cellHeight)
);
}
}
for (Agent animal:mySimu.getAnimals()){
g.setColor(animal.getDisplayColor());
g.fillOval((int)Math.round(animal.getX()*cellWidth),
(int)Math.round(animal.getY()*cellHeight),
(int)Math.round(cellWidth/2),
(int)Math.round(cellHeight/2));
}
}
}
}

View File

@ -0,0 +1,397 @@
package windowInterface;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import backend.Simulator;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.event.ActionEvent;
public class MyInterface extends JFrame {
private static final long serialVersionUID = -6840815447618468846L;
private JPanel contentPane;
private JLabel stepLabel;
private JLabel borderLabel;
private JLabel speedLabel;
private JPanelDraw panelDraw;
private Simulator mySimu=null;
private JSlider randSlider;
private JSlider speedSlider;
private JLabel clickLabel;
/**
* Create the frame.
*/
public MyInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10, 10, 700, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panelTop = new JPanel();
contentPane.add(panelTop, BorderLayout.NORTH);
JPanel panelRight = new JPanel();
panelRight.setLayout(new GridLayout(12,1));
contentPane.add(panelRight, BorderLayout.EAST);
JButton btnGo = new JButton("Start/Pause");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonGo();
}
});
panelTop.add(btnGo);
JButton btnClickAct = new JButton("Toggle Click");
btnClickAct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonToggleClickAction();
}
});
panelTop.add(btnClickAct);
stepLabel = new JLabel("Step : X");
panelTop.add(stepLabel);
speedLabel = new JLabel("speed slider : ");
panelTop.add(speedLabel);
speedSlider = new JSlider();
speedSlider.setValue(3);
speedSlider.setMinimum(0);
speedSlider.setMaximum(10);
speedSlider.setOrientation(SwingConstants.HORIZONTAL);
speedSlider.setPreferredSize(new Dimension(100,30));
speedSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
changeSpeed();
}
});
panelTop.add(speedSlider);
// JButton btnSpeed = new JButton("Set Speed");
// btnSpeed.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// clicButtonSpeed();
// }
// });
// panelTop.add(btnSpeed);
JButton btnLoad = new JButton("Load World");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadFileButton();
}
});
panelRight.add(btnLoad);
JButton btnSave = new JButton("Save World");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveToFileButton();
}
});
panelRight.add(btnSave);
JButton btnLoadRule = new JButton("Load Rule");
btnLoadRule.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadRuleFileButton();
}
});
panelRight.add(btnLoadRule);
JButton btnSaveRule = new JButton("Save Rule");
btnSaveRule.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveRuleToFileButton();
}
});
panelRight.add(btnSaveRule);
JButton btnLoadAgents = new JButton("Load Agents");
btnLoadAgents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicLoadAgentsFileButton();;
}
});
panelRight.add(btnLoadAgents);
JButton btnSaveAgents = new JButton("Save Agents");
btnSaveAgents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicSaveAgentsToFileButton();
}
});
panelRight.add(btnSaveAgents);
JButton btnRandGen = new JButton("Random Field");
btnRandGen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
generateRandomBoard();
}
});
panelRight.add(btnRandGen);
JLabel randLabel = new JLabel("random density slider :");
panelRight.add(randLabel);
randSlider = new JSlider();
randSlider.setValue(50);
randSlider.setMinimum(0);
randSlider.setMaximum(100);
randSlider.setPreferredSize(new Dimension(30,200));
panelRight.add(randSlider);
JButton btnBorder = new JButton("Toggle Border");
btnBorder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicButtonBorder();
}
});
panelRight.add(btnBorder);
panelDraw = new JPanelDraw(this);
contentPane.add(panelDraw, BorderLayout.CENTER);
instantiateSimu();
borderLabel = new JLabel("border : X");
panelRight.add(borderLabel);
borderLabel.setText("border : " +
(mySimu.isLoopingBorder()?"loop":"closed"));
clickLabel = new JLabel("click : X");
panelRight.add(clickLabel);
clickLabel.setText("click : " + mySimu.clickActionName());
}
public void setStepBanner(String s) {
stepLabel.setText(s);
}
public void setBorderBanner(String s) {
borderLabel.setText(s);
}
public void setClickBanner(String s) {
clickLabel.setText(s);
}
public JPanelDraw getPanelDessin() {
return panelDraw;
}
public void instantiateSimu() {
if(mySimu==null) {
mySimu = new Simulator(this);
panelDraw.setSimu(mySimu);
}
}
public void clicButtonGo() {
this.instantiateSimu();
if(!mySimu.isAlive()) {
mySimu.start();
} else {
mySimu.togglePause();
}
}
public void clicButtonToggleClickAction() {
if(mySimu != null) {
mySimu.toggleClickAction();
clickLabel.setText("click : " + mySimu.clickActionName());
}
}
public void clicButtonBorder() {
if(mySimu != null) {
mySimu.toggleLoopingBorder();
borderLabel.setText("border : " +
(mySimu.isLoopingBorder()?"loop":"closed"));
}
}
public void generateRandomBoard() {
this.instantiateSimu();
float chanceOfLife = ((float)randSlider.getValue())/((float)randSlider.getMaximum());
mySimu.generateRandom(chanceOfLife);
panelDraw.repaint();
}
public void changeSpeed() {
if(mySimu != null) {
int delay = (int)Math.pow(2, 10-speedSlider.getValue());
mySimu.setLoopDelay(delay);
} else {
speedSlider.setValue(3);
}
}
public void clicLoadFileButton() {
Simulator loadedSim = new Simulator(this);
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
if(mySimu != null) {
mySimu.stopSimu();
this.eraseLabels();
}
loadedSim.loadSaveState(stringArray);
mySimu = loadedSim;
panelDraw.setSimu(mySimu);
this.repaint();
}
}
public void clicLoadRuleFileButton() {
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
mySimu.loadRule(stringArray);
this.repaint();
}
}
public void clicLoadAgentsFileButton() {
String fileName=SelectFile();
ArrayList<String> stringArray = new ArrayList<String>();
if (fileName.length()>0) {
try {
BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine();
while (line != null) {
stringArray.add(line);
line = fileContent.readLine();
}
fileContent.close();
} catch (Exception e) {
e.printStackTrace();
}
mySimu.loadAgents(stringArray);
this.repaint();
}
}
public void clicSaveToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getSaveState();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public void clicSaveRuleToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getRule();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public void clicSaveAgentsToFileButton() {
String fileName=SelectFile();
if (fileName.length()>0) {
ArrayList<String> content = mySimu.getAgentsSave();
String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
}
}
public String SelectFile() {
String s;
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a file");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
s=chooser.getSelectedFile().toString();
} else {
System.out.println("No Selection ");
s="";
}
return s;
}
public void writeFile(String fileName, String[] content) {
FileWriter csvWriter;
try {
csvWriter = new FileWriter(fileName);
for (String row : content) {
csvWriter.append(row);
csvWriter.append("\n");
}
csvWriter.flush();
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void update (int stepCount) {
this.setStepBanner("Step : "+ stepCount);
this.repaint();
}
public void eraseLabels() {
this.setStepBanner("Step : X");
this.setBorderBanner("border : X");
this.setClickBanner("click : X");
speedSlider.setValue(3);
}
}