revert updated Simulator and MyInterface
This commit is contained in:
t.leclapart-jublot 2024-05-26 13:03:24 +02:00
parent 94fd880575
commit ce36dc5e09
6 changed files with 938 additions and 532 deletions

View File

@ -1,8 +1,12 @@
import windowInterface.MyInterface; import windowInterface.MyInterface;
public class Main { public class Main {
public static void main(String[] args) {
MyInterface mjf = new MyInterface();
mjf.setVisible(true); public static void main(String[] args) {
} MyInterface mjf = new MyInterface();
} mjf.setVisible(true);
}
}

View File

@ -4,34 +4,37 @@ import java.awt.Color;
import java.util.ArrayList; import java.util.ArrayList;
public abstract class Agent { public abstract class Agent {
protected int x; protected int x;
protected int y; protected int y;
protected Color color; protected Color color;
protected Agent(int x, int y, Color color) { protected Agent(int x, int y, Color color) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.color = color; this.color = color;
} }
public Color getDisplayColor() { public Color getDisplayColor() {
return color; 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;
}
public int getX() { // Does whatever the agent does during a step
return x; // 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);
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;
}
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
} }

View File

@ -4,33 +4,56 @@ import java.awt.Color;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Random; 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 { public class Sheep extends Agent {
int hunger;
Random rand;
public Sheep(int x, int y) { int hunger;
super(x, y, Color.white); Random rand;
hunger = 0;
rand = new Random(); 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;
}
}
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if (world.getCell(x, y) == 1) {
world.setCell(x, y, 0);
hunger = 0;
} else {
hunger++;
}
this.moveRandom(world);
return hunger <= 10;
}
private void moveRandom(Simulator world) {
int newX = x + rand.nextInt(3) - 1;
int newY = y + rand.nextInt(3) - 1;
if (newX >= 0 && newX < world.getWidth() && newY >= 0 && newY < world.getHeight()) {
x = newX;
y = newY;
}
}
} }

View File

@ -1,202 +1,362 @@
package backend; package backend;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Random; import windowInterface.MyInterface;
import java.util.Timer;
import java.util.TimerTask; public class Simulator extends Thread {
import windowInterface.MyInterface; private MyInterface mjf;
public class Simulator { private final int COL_NUM = 100;
private int width; private final int LINE_NUM = 100;
private int height; private final int LIFE_TYPE_NUM = 4;
private int[][] world; //Conway Radius : 1
private ArrayList<Agent> agents; private final int LIFE_AREA_RADIUS = 1;
private boolean loopingBorder; //Animal Neighborhood Radius : 5
private boolean pauseFlag; private final int ANIMAL_AREA_RADIUS = 2;
private int loopDelay; private ArrayList<Integer> fieldSurviveValues;
private MyInterface interfaceGlobal; private ArrayList<Integer> fieldBirthValues;
private Timer timer;
private int stepCount; private ArrayList<Agent> agents;
public Simulator(MyInterface mjfParam) { private boolean stopFlag;
this.interfaceGlobal = mjfParam; private boolean pauseFlag;
this.width = 100; // Example value private boolean loopingBorder;
this.height = 100; // Example value private boolean clickActionFlag;
this.world = new int[width][height]; private int loopDelay = 150;
this.agents = new ArrayList<>(); private int[][] grid;
this.loopingBorder = false;
this.pauseFlag = true; // Start in paused state //TODO : add missing attribute(s)
this.loopDelay = 1000;
this.timer = new Timer(); public Simulator(MyInterface mjfParam) {
this.stepCount = 0; mjf = mjfParam;
} stopFlag=false;
pauseFlag=false;
public void startSimulationLoop() { loopingBorder=false;
timer.scheduleAtFixedRate(new TimerTask() { clickActionFlag=false;
@Override
public void run() { agents = new ArrayList<Agent>();
if (!pauseFlag) { fieldBirthValues = new ArrayList<Integer>();
makeStep(); fieldSurviveValues = new ArrayList<Integer>();
stepCount++; //TODO : add missing attribute initialization
interfaceGlobal.update(stepCount);
} grid = gridCreation();
}
}, 0, loopDelay); //Default rule : Survive always, birth never
} for(int i =0; i<9; i++) {
fieldSurviveValues.add(i);
public void makeStep() { }
int[][] newWorld = new int[width][height];
}
// Apply Game of Life rules public int[][] gridCreation() {
for (int x = 0; x < width; x++) { int[][] newGrid = new int[COL_NUM][LINE_NUM];
for (int y = 0; y < height; y++) { //create the grid
int aliveNeighbors = countAliveNeighbors(x, y); for (int x = 0; x < COL_NUM; x ++) {
if (world[x][y] == 1) { for (int y = 0; y < LINE_NUM; y ++) {
newWorld[x][y] = (aliveNeighbors < 2 || aliveNeighbors > 3) ? 0 : 1; if (grid[x][y] == 0)
} else { System.out.print("0");
newWorld[x][y] = (aliveNeighbors == 3) ? 1 : 0; else
} System.out.print("1");
} //create cell
} //cest fait jpeux pas enlever le todo
}
world = newWorld; System.out.println();
}
// Agents take their turn return newGrid;
ArrayList<Agent> newAgents = new ArrayList<>(); }
for (Agent agent : agents) {
if (agent.liveTurn(getNeighbors(agent), this)) {
newAgents.add(agent);
} //TODO create a new generation
} public int[][] nextGen(int gridCreation[][], int COL_NUM, int LINE_NUM){
agents = newAgents; int[][] future = new int[COL_NUM][LINE_NUM];
for (int x = 0; x < COL_NUM; x++) {
interfaceGlobal.update(stepCount); for (int y = 0; y < LINE_NUM; y++) {
}
}
public void togglePause() { }
pauseFlag = !pauseFlag; }
if (!pauseFlag) {
startSimulationLoop();
} public int getWidth() {
} return COL_NUM;
}
public void toggleLoopingBorder() {
loopingBorder = !loopingBorder; public int getHeight() {
interfaceGlobal.setBorderBanner("border : " + (loopingBorder ? "looping" : "closed")); return LINE_NUM;
} }
public boolean isLoopingBorder() { //Should probably stay as is
return loopingBorder; public void run() {
} int stepCount=0;
while(!stopFlag) {
public void setLoopDelay(int delay) { stepCount++;
loopDelay = delay; makeStep();
timer.cancel(); mjf.update(stepCount);
timer = new Timer(); try {
startSimulationLoop(); Thread.sleep(loopDelay);
} } catch (InterruptedException e) {
e.printStackTrace();
public int getWidth() { }
return width; while(pauseFlag && !stopFlag) {
} try {
Thread.sleep(loopDelay);
public int getHeight() { } catch (InterruptedException e) {
return height; e.printStackTrace();
} }
}
public int getCell(int x, int y) { }
return world[x][y];
} }
public void setCell(int x, int y, int val) { /**
world[x][y] = val; * method called at each step of the simulation
} * makes all the actions to go from one step to the other
*/
public void clickCell(int x, int y) { public void makeStep() {
setCell(x, y, getCell(x, y) == 1 ? 0 : 1); // agent behaviors first
} // only modify if sure of what you do
// to modify agent behavior, see liveTurn method
public void generateRandom(float chanceOfLife) { // in agent classes
Random rand = new Random(); for(Agent agent : agents) {
for (int x = 0; x < width; x++) { ArrayList<Agent> neighbors =
for (int y = 0; y < height; y++) { this.getNeighboringAnimals(
world[x][y] = rand.nextFloat() < chanceOfLife ? 1 : 0; agent.getX(),
} agent.getY(),
} ANIMAL_AREA_RADIUS);
interfaceGlobal.update(stepCount); // Ensure the display updates if(!agent.liveTurn(
} neighbors,
this)) {
public ArrayList<Agent> getAgents() { agents.remove(agent);
return agents; }
} }
//then evolution of the field
public ArrayList<Agent> getNeighbors(Agent agent) { // TODO : apply game rule to all cells of the field
ArrayList<Agent> neighbors = new ArrayList<>();
for (Agent a : agents) { /* you should distribute this action in methods/classes
if (a != agent && a.isInArea(agent.getX(), agent.getY(), 1)) { * don't write everything here !
neighbors.add(a); *
} * the idea is first to get the surrounding values
} * then count how many are alive
return neighbors; * then check if that number is in the lists of rules
} * if the cell is alive
* and the count is in the survive list,
private int countAliveNeighbors(int x, int y) { * then the cell stays alive
int count = 0; * if the cell is not alive
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; * and the count is in the birth list,
for (int[] dir : directions) { * then the cell becomes alive
int nx = x + dir[0]; */
int ny = y + dir[1];
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
count += world[nx][ny];
} else if (loopingBorder) {
nx = (nx + width) % width; }
ny = (ny + height) % height;
count += world[nx][ny]; /*
} * leave this as is
} */
return count; public void stopSimu() {
} stopFlag=true;
}
public ArrayList<String> getRule() {
return new ArrayList<>(); /*
} * method called when clicking pause button
*/
public void loadRule(ArrayList<String> lines) { public void togglePause() {
// Implement loadRule logic pauseFlag= ! pauseFlag;
} // It changes the boolean value associated to pauseFlag (pauseFlag= not pauseFlag)
}
public ArrayList<String> getSaveState() {
ArrayList<String> saveState = new ArrayList<>(); /**
for (int y = 0; y < height; y++) { * method called when clicking on a cell in the interface
StringBuilder line = new StringBuilder(); */
for (int x = 0; x < width; x++) { public void clickCell(int x, int y) {
if (x > 0) line.append(";"); //TODO : complete method
line.append(world[x][y]); }
}
saveState.add(line.toString()); /**
} * get cell value in simulated world
return saveState; * @param x coordinate of cell
} * @param y coordinate of cell
* @return value of cell
public void loadSaveState(ArrayList<String> lines) { */
for (int y = 0; y < lines.size(); y++) { public int getCell(int x, int y) {
String[] values = lines.get(y).split(";"); //get the value (dead or alive) of my cell at x y
for (int x = 0; x < values.length; x++) { return 0;
world[x][y] = Integer.parseInt(values[x]); }
} /**
} *
} * @return list of Animals in simulated world
*/
public ArrayList<String> getAgentsSave() { public ArrayList<Agent> getAnimals(){
return new ArrayList<>(); return agents;
} }
/**
public void loadAgents(ArrayList<String> stringArray) { * selects Animals in a circular area of simulated world
// Implement loadAgents logic * @param x center
} * @param y center
* @param radius
public String clickActionName() { * @return list of agents in area
return ""; */
} 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;
}
/**
* set value of cell
* @param x coord of cell
* @param y coord of cell
* @param val to set in cell
*/
public void setCell(int x, int y, int val) {
//TODO : complete method
}
/**
*
* @return lines of file representing
* the simulated world in its present state
*/
public ArrayList<String> getSaveState() {
//TODO : complete method with proper return
return null;
}
/**
*
* @param lines of file representing saved world state
*/
public void loadSaveState(ArrayList<String> lines) {
/*
* First some checks that the file is usable
* We call early returns in conditions like this
* "Guard clauses", as they guard the method
* against unwanted inputs
*/
if(lines.size()<=0) {
return;
}
String firstLine = lines.get(0);
String[] firstLineElements = firstLine.split(";");
if(firstLineElements.length<=0) {
return;
}
/*
* now we fill in the world
* with the content of the file
*/
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);
}
}
}
/**
* called by button, with slider providing the argument
* makes a new world state with random cell states
* @param chanceOfLife the chance for each cell
* to be alive in new state
*/
public void generateRandom(float chanceOfLife) {
//TODO : complete method
/*
* Advice :
* as you should probably have a separate class
* representing the field of cells...
* maybe just make a constructor in there
* and use it here
*/
}
public boolean isLoopingBorder() {
return loopingBorder;
}
public void toggleLoopingBorder() {
if (loopingBorder){
loopingBorder = false;
}else {
loopingBorder = true;
}
}
public void setLoopDelay(int delay) {
//TODO : complete method
}
public void toggleClickAction() {
//TODO : complete method
}
/**
* prepare the content of a file saving present ruleSet
* as you might want to save a state,
* initialy written in this class constructor
* as a file for future use
* @return File content as an ArrayList of Lines (String)
* @see loadRule for inverse process
*/
public ArrayList<String> getRule() {
//TODO : complete method with proper return
return null;
}
public void loadRule(ArrayList<String> lines) {
if(lines.size()<=0) {
System.out.println("empty rule file");
return;
}
//TODO : remove previous rule (=emptying lists)
String surviveLine = lines.get(0);
String birthLine = lines.get(1);
String[] surviveElements = surviveLine.split(";");
for(int x=0; x<surviveElements.length;x++) {
String elem = surviveElements[x];
int value = Integer.parseInt(elem);
//TODO : add value to possible survive values
}
String[] birthElements = birthLine.split(";");
for(int x=0; x<birthElements.length;x++) {
String elem = birthElements[x];
int value = Integer.parseInt(elem);
//TODO : add value to possible birth values
}
}
public ArrayList<String> getAgentsSave() {
//TODO : Same idea as the other save method, but for agents
return null;
}
public void loadAgents(ArrayList<String> stringArray) {
//TODO : Same idea as other load methods, but for agent list
}
/**
* 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
return "";
}
}

View File

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

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