updated Simulator and MyInterface

This commit is contained in:
timeo 2024-05-24 22:08:48 +02:00
parent 447e9f74bc
commit 94fd880575
6 changed files with 537 additions and 943 deletions

View File

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

View File

@ -4,37 +4,34 @@ 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 getX() {
} return x;
public int getY() { }
return y;
} public int getY() {
public boolean isInArea(int x, int y, int radius) { return y;
int diffX = this.x-x; }
int diffY = this.y-y;
int dist = (int) Math.floor(Math.sqrt(diffX*diffX+diffY*diffY)); public boolean isInArea(int x, int y, int radius) {
return dist<radius; int diffX = this.x - x;
} int diffY = this.y - y;
int dist = (int) Math.floor(Math.sqrt(diffX * diffX + diffY * diffY));
// Does whatever the agent does during a step return dist < radius;
// 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 abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
} }

View File

@ -4,56 +4,33 @@ 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;
int hunger; Random rand;
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();
}
/** public Sheep(int x, int y) {
* action of the animal super(x, y, Color.white);
* it can interact with the cells or with other animals hunger = 0;
* as you wish rand = new Random();
*/ }
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,362 +1,202 @@
package backend; package backend;
import java.util.ArrayList;
import java.util.ArrayList;
import windowInterface.MyInterface; import java.util.Random;
import java.util.Timer;
public class Simulator extends Thread { import java.util.TimerTask;
private MyInterface mjf; import windowInterface.MyInterface;
private final int COL_NUM = 100; public class Simulator {
private final int LINE_NUM = 100; private int width;
private final int LIFE_TYPE_NUM = 4; private int height;
//Conway Radius : 1 private int[][] world;
private final int LIFE_AREA_RADIUS = 1; private ArrayList<Agent> agents;
//Animal Neighborhood Radius : 5 private boolean loopingBorder;
private final int ANIMAL_AREA_RADIUS = 2; private boolean pauseFlag;
private ArrayList<Integer> fieldSurviveValues; private int loopDelay;
private ArrayList<Integer> fieldBirthValues; private MyInterface interfaceGlobal;
private Timer timer;
private ArrayList<Agent> agents; private int stepCount;
private boolean stopFlag; public Simulator(MyInterface mjfParam) {
private boolean pauseFlag; this.interfaceGlobal = mjfParam;
private boolean loopingBorder; this.width = 100; // Example value
private boolean clickActionFlag; this.height = 100; // Example value
private int loopDelay = 150; this.world = new int[width][height];
private int[][] grid; this.agents = new ArrayList<>();
this.loopingBorder = false;
//TODO : add missing attribute(s) this.pauseFlag = true; // Start in paused state
this.loopDelay = 1000;
public Simulator(MyInterface mjfParam) { this.timer = new Timer();
mjf = mjfParam; this.stepCount = 0;
stopFlag=false; }
pauseFlag=false;
loopingBorder=false; public void startSimulationLoop() {
clickActionFlag=false; timer.scheduleAtFixedRate(new TimerTask() {
@Override
agents = new ArrayList<Agent>(); public void run() {
fieldBirthValues = new ArrayList<Integer>(); if (!pauseFlag) {
fieldSurviveValues = new ArrayList<Integer>(); makeStep();
//TODO : add missing attribute initialization stepCount++;
interfaceGlobal.update(stepCount);
grid = gridCreation(); }
}
//Default rule : Survive always, birth never }, 0, loopDelay);
for(int i =0; i<9; i++) { }
fieldSurviveValues.add(i);
} public void makeStep() {
int[][] newWorld = new int[width][height];
}
public int[][] gridCreation() { // Apply Game of Life rules
int[][] newGrid = new int[COL_NUM][LINE_NUM]; for (int x = 0; x < width; x++) {
//create the grid for (int y = 0; y < height; y++) {
for (int x = 0; x < COL_NUM; x ++) { int aliveNeighbors = countAliveNeighbors(x, y);
for (int y = 0; y < LINE_NUM; y ++) { if (world[x][y] == 1) {
if (grid[x][y] == 0) newWorld[x][y] = (aliveNeighbors < 2 || aliveNeighbors > 3) ? 0 : 1;
System.out.print("0"); } else {
else newWorld[x][y] = (aliveNeighbors == 3) ? 1 : 0;
System.out.print("1"); }
//create cell }
//cest fait jpeux pas enlever le todo }
}
System.out.println(); world = newWorld;
}
return newGrid; // Agents take their turn
} 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){ }
int[][] future = new int[COL_NUM][LINE_NUM]; agents = newAgents;
for (int x = 0; x < COL_NUM; x++) {
for (int y = 0; y < LINE_NUM; y++) { interfaceGlobal.update(stepCount);
}
}
} public void togglePause() {
} pauseFlag = !pauseFlag;
if (!pauseFlag) {
startSimulationLoop();
public int getWidth() { }
return COL_NUM; }
}
public void toggleLoopingBorder() {
public int getHeight() { loopingBorder = !loopingBorder;
return LINE_NUM; interfaceGlobal.setBorderBanner("border : " + (loopingBorder ? "looping" : "closed"));
} }
//Should probably stay as is public boolean isLoopingBorder() {
public void run() { return loopingBorder;
int stepCount=0; }
while(!stopFlag) {
stepCount++; public void setLoopDelay(int delay) {
makeStep(); loopDelay = delay;
mjf.update(stepCount); timer.cancel();
try { timer = new Timer();
Thread.sleep(loopDelay); startSimulationLoop();
} catch (InterruptedException e) { }
e.printStackTrace();
} public int getWidth() {
while(pauseFlag && !stopFlag) { return width;
try { }
Thread.sleep(loopDelay);
} catch (InterruptedException e) { public int getHeight() {
e.printStackTrace(); return height;
} }
}
} public int getCell(int x, int y) {
return world[x][y];
} }
/** public void setCell(int x, int y, int val) {
* method called at each step of the simulation world[x][y] = val;
* makes all the actions to go from one step to the other }
*/
public void makeStep() { public void clickCell(int x, int y) {
// agent behaviors first setCell(x, y, getCell(x, y) == 1 ? 0 : 1);
// only modify if sure of what you do }
// to modify agent behavior, see liveTurn method
// in agent classes public void generateRandom(float chanceOfLife) {
for(Agent agent : agents) { Random rand = new Random();
ArrayList<Agent> neighbors = for (int x = 0; x < width; x++) {
this.getNeighboringAnimals( for (int y = 0; y < height; y++) {
agent.getX(), world[x][y] = rand.nextFloat() < chanceOfLife ? 1 : 0;
agent.getY(), }
ANIMAL_AREA_RADIUS); }
if(!agent.liveTurn( interfaceGlobal.update(stepCount); // Ensure the display updates
neighbors, }
this)) {
agents.remove(agent); public ArrayList<Agent> getAgents() {
} return agents;
} }
//then evolution of the field
// TODO : apply game rule to all cells of the field public ArrayList<Agent> getNeighbors(Agent agent) {
ArrayList<Agent> neighbors = new ArrayList<>();
/* you should distribute this action in methods/classes for (Agent a : agents) {
* don't write everything here ! if (a != agent && a.isInArea(agent.getX(), agent.getY(), 1)) {
* neighbors.add(a);
* the idea is first to get the surrounding values }
* then count how many are alive }
* then check if that number is in the lists of rules return neighbors;
* if the cell is alive }
* and the count is in the survive list,
* then the cell stays alive private int countAliveNeighbors(int x, int y) {
* if the cell is not alive int count = 0;
* and the count is in the birth list, int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
* then the cell becomes alive for (int[] dir : directions) {
*/ 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 }
*/ }
public void stopSimu() { return count;
stopFlag=true; }
}
public ArrayList<String> getRule() {
/* return new ArrayList<>();
* method called when clicking pause button }
*/
public void togglePause() { public void loadRule(ArrayList<String> lines) {
pauseFlag= ! pauseFlag; // Implement loadRule logic
// It changes the boolean value associated to pauseFlag (pauseFlag= not pauseFlag) }
}
public ArrayList<String> getSaveState() {
/** ArrayList<String> saveState = new ArrayList<>();
* method called when clicking on a cell in the interface for (int y = 0; y < height; y++) {
*/ StringBuilder line = new StringBuilder();
public void clickCell(int x, int y) { for (int x = 0; x < width; x++) {
//TODO : complete method if (x > 0) line.append(";");
} line.append(world[x][y]);
}
/** saveState.add(line.toString());
* get cell value in simulated world }
* @param x coordinate of cell return saveState;
* @param y coordinate of cell }
* @return value of cell
*/ public void loadSaveState(ArrayList<String> lines) {
public int getCell(int x, int y) { for (int y = 0; y < lines.size(); y++) {
//get the value (dead or alive) of my cell at x y String[] values = lines.get(y).split(";");
return 0; for (int x = 0; x < values.length; x++) {
} world[x][y] = Integer.parseInt(values[x]);
/** }
* }
* @return list of Animals in simulated world }
*/
public ArrayList<Agent> getAnimals(){ public ArrayList<String> getAgentsSave() {
return agents; return new ArrayList<>();
} }
/**
* selects Animals in a circular area of simulated world public void loadAgents(ArrayList<String> stringArray) {
* @param x center // Implement loadAgents logic
* @param y center }
* @param radius
* @return list of agents in area public String clickActionName() {
*/ 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,94 +1,78 @@
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 static final long serialVersionUID = 1L; private Simulator mySimu;
private Simulator mySimu; private MyInterface interfaceGlobal;
private MyInterface interfaceGlobal;
public JPanelDraw(MyInterface itf) {
public JPanelDraw(MyInterface itf) { super();
super(); mySimu = null;
mySimu = null; interfaceGlobal = itf;
interfaceGlobal = itf; addMouseListener(new MouseAdapter() {
addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) {
public void mousePressed(MouseEvent me) { if (mySimu == null) {
// System.out.println(me); interfaceGlobal.instantiateSimu();
if(mySimu == null) { }
interfaceGlobal.instantiateSimu(); int x = (me.getX() * mySimu.getWidth()) / getWidth();
} int y = (me.getY() * mySimu.getHeight()) / getHeight();
int x = (me.getX()*mySimu.getWidth())/getWidth(); mySimu.clickCell(x, y);
int y = (me.getY()*mySimu.getHeight())/getHeight(); repaint();
mySimu.clickCell(x,y); }
repaint(); });
} }
});
} public void setSimu(Simulator simu) {
mySimu = simu;
}
public void setSimu(Simulator simu) {
mySimu = simu; @Override
} protected void paintComponent(Graphics g) {
super.paintComponent(g);
@Override this.setBackground(Color.black);
protected void paintComponent(Graphics g) { if (mySimu != null) {
super.paintComponent(g); float cellWidth = (float) this.getWidth() / (float) mySimu.getWidth();
this.setBackground(Color.black); float cellHeight = (float) this.getHeight() / (float) mySimu.getHeight();
if (mySimu != null) { g.setColor(Color.gray);
// Draw Interface from state of simulator for (int x = 0; x < mySimu.getWidth(); x++) {
float cellWidth = (float)this.getWidth()/(float)mySimu.getWidth(); int graphX = Math.round(x * cellWidth);
float cellHeight = (float)this.getHeight()/(float)mySimu.getHeight(); g.drawLine(graphX, 0, graphX, this.getHeight());
g.setColor(Color.gray); }
for(int x=0; x<mySimu.getWidth();x++) { for (int y = 0; y < mySimu.getHeight(); y++) {
int graphX = Math.round(x*cellWidth); int graphY = Math.round(y * cellHeight);
g.drawLine(graphX, 0, graphX, this.getHeight()); g.drawLine(0, graphY, this.getWidth(), graphY);
} }
for (int y=0; y<mySimu.getHeight(); y++) { for (int x = 0; x < mySimu.getWidth(); x++) {
int graphY = Math.round(y*cellHeight); for (int y = 0; y < mySimu.getHeight(); y++) {
g.drawLine(0, graphY, this.getWidth(), graphY); int cellContent = mySimu.getCell(x, y);
} if (cellContent == 0) {
for(int x=0; x<mySimu.getWidth();x++) { continue;
for (int y=0; y<mySimu.getHeight(); y++) { }
int cellContent = mySimu.getCell(x,y); if (cellContent == 1) {
if(cellContent == 0) { g.setColor(Color.white);
continue; } else {
} g.setColor(Color.getHSBColor(cellContent / 10.0f, 1.0f, 1.0f));
if(cellContent == 1) { }
g.setColor(Color.green); g.fillRect(Math.round(x * cellWidth), Math.round(y * cellHeight), Math.round(cellWidth), Math.round(cellHeight));
} }
if(cellContent == 2) { }
g.setColor(Color.yellow); for (Agent ag : mySimu.getAgents()) {
} g.setColor(ag.getDisplayColor());
if(cellContent == 3) { int graphX = Math.round(ag.getX() * cellWidth);
g.setColor(Color.cyan); int graphY = Math.round(ag.getY() * cellHeight);
} 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,397 +1,197 @@
package windowInterface; package windowInterface;
import java.awt.BorderLayout;
import java.awt.Dimension; import java.awt.BorderLayout;
import java.awt.GridLayout; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame; import java.io.FileWriter;
import javax.swing.JPanel; import java.io.IOException;
import javax.swing.JSlider; import java.util.ArrayList;
import javax.swing.SwingConstants; import java.util.Arrays;
import javax.swing.border.EmptyBorder; import javax.swing.JButton;
import javax.swing.event.ChangeEvent; import javax.swing.JFileChooser;
import javax.swing.event.ChangeListener; import javax.swing.JFrame;
import javax.swing.JLabel;
import backend.Simulator; import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JButton;
import javax.swing.JFileChooser; import backend.Simulator;
import javax.swing.JLabel;
public class MyInterface extends JFrame {
import java.awt.event.ActionListener; private static final long serialVersionUID = 1L;
import java.io.BufferedReader; private Simulator mySimu;
import java.io.FileReader; private JPanelDraw drawPanel;
import java.io.FileWriter; private JLabel stepBanner;
import java.io.IOException; private JLabel borderBanner;
import java.util.ArrayList; private JLabel clickBanner;
import java.util.Arrays; private JSlider speedSlider;
import java.awt.event.ActionEvent;
public MyInterface() {
public class MyInterface extends JFrame { super("Simulator Interface");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
private static final long serialVersionUID = -6840815447618468846L; this.setSize(800, 600);
private JPanel contentPane;
private JLabel stepLabel; drawPanel = new JPanelDraw(this);
private JLabel borderLabel; this.add(drawPanel, BorderLayout.CENTER);
private JLabel speedLabel;
private JPanelDraw panelDraw; JPanel controlPanel = new JPanel();
private Simulator mySimu=null;
private JSlider randSlider; JButton startPauseButton = new JButton("Start/Pause");
private JSlider speedSlider; startPauseButton.addActionListener(new ActionListener() {
private JLabel clickLabel; public void actionPerformed(ActionEvent e) {
if (mySimu != null) {
/** mySimu.togglePause();
* Create the frame. }
*/ }
public MyInterface() { });
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); controlPanel.add(startPauseButton);
setBounds(10, 10, 700, 600);
contentPane = new JPanel(); JButton stopButton = new JButton("Stop");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); stopButton.addActionListener(new ActionListener() {
contentPane.setLayout(new BorderLayout(0, 0)); public void actionPerformed(ActionEvent e) {
setContentPane(contentPane); if (mySimu != null) {
mySimu = null;
JPanel panelTop = new JPanel(); drawPanel.setSimu(null);
contentPane.add(panelTop, BorderLayout.NORTH); drawPanel.repaint();
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");
btnGo.addActionListener(new ActionListener() { JButton toggleBorderButton = new JButton("Toggle Border");
public void actionPerformed(ActionEvent arg0) { toggleBorderButton.addActionListener(new ActionListener() {
clicButtonGo(); public void actionPerformed(ActionEvent e) {
} if (mySimu != null) {
}); mySimu.toggleLoopingBorder();
panelTop.add(btnGo); }
}
JButton btnClickAct = new JButton("Toggle Click"); });
btnClickAct.addActionListener(new ActionListener() { controlPanel.add(toggleBorderButton);
public void actionPerformed(ActionEvent arg0) {
clicButtonToggleClickAction(); JButton randomButton = new JButton("Random");
} randomButton.addActionListener(new ActionListener() {
}); public void actionPerformed(ActionEvent e) {
panelTop.add(btnClickAct); if (mySimu != null) {
mySimu.generateRandom(0.2f); // Example chance of life
stepLabel = new JLabel("Step : X"); drawPanel.repaint();
panelTop.add(stepLabel); }
}
speedLabel = new JLabel("speed slider : "); });
panelTop.add(speedLabel); controlPanel.add(randomButton);
speedSlider = new JSlider(); speedSlider = new JSlider(1, 10, 3);
speedSlider.setValue(3); speedSlider.addChangeListener(e -> {
speedSlider.setMinimum(0); if (mySimu != null) {
speedSlider.setMaximum(10); mySimu.setLoopDelay(1000 / speedSlider.getValue());
speedSlider.setOrientation(SwingConstants.HORIZONTAL); }
speedSlider.setPreferredSize(new Dimension(100,30)); });
speedSlider.addChangeListener(new ChangeListener() { controlPanel.add(speedSlider);
public void stateChanged(ChangeEvent arg0) {
changeSpeed(); this.add(controlPanel, BorderLayout.SOUTH);
}
}); JPanel infoPanel = new JPanel();
panelTop.add(speedSlider);
stepBanner = new JLabel("Step : X");
// JButton btnSpeed = new JButton("Set Speed"); infoPanel.add(stepBanner);
// btnSpeed.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) { borderBanner = new JLabel("border : X");
// clicButtonSpeed(); infoPanel.add(borderBanner);
// }
// }); clickBanner = new JLabel("click : X");
// panelTop.add(btnSpeed); infoPanel.add(clickBanner);
JButton btnLoad = new JButton("Load World"); this.add(infoPanel, BorderLayout.NORTH);
btnLoad.addActionListener(new ActionListener() { }
public void actionPerformed(ActionEvent arg0) {
clicLoadFileButton(); public void instantiateSimu() {
} mySimu = new Simulator(this);
}); drawPanel.setSimu(mySimu);
panelRight.add(btnLoad); setStepBanner("Step : 0");
setBorderBanner("border : closed");
JButton btnSave = new JButton("Save World"); setClickBanner("click : cell");
btnSave.addActionListener(new ActionListener() { mySimu.setLoopDelay(1000 / speedSlider.getValue());
public void actionPerformed(ActionEvent arg0) { mySimu.startSimulationLoop();
clicSaveToFileButton(); }
}
}); public void setStepBanner(String text) {
panelRight.add(btnSave); stepBanner.setText(text);
}
JButton btnLoadRule = new JButton("Load Rule"); public void setBorderBanner(String text) {
btnLoadRule.addActionListener(new ActionListener() { borderBanner.setText(text);
public void actionPerformed(ActionEvent arg0) { }
clicLoadRuleFileButton();
} public void setClickBanner(String text) {
}); clickBanner.setText(text);
panelRight.add(btnLoadRule); }
JButton btnSaveRule = new JButton("Save Rule"); public void clicSaveToFileButton() {
btnSaveRule.addActionListener(new ActionListener() { String fileName = SelectFile();
public void actionPerformed(ActionEvent arg0) { if (fileName.length() > 0) {
clicSaveRuleToFileButton(); ArrayList<String> content = mySimu.getSaveState();
} String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
}); writeFile(fileName, strArr);
panelRight.add(btnSaveRule); }
}
JButton btnLoadAgents = new JButton("Load Agents");
btnLoadAgents.addActionListener(new ActionListener() { public void clicSaveRuleToFileButton() {
public void actionPerformed(ActionEvent arg0) { String fileName = SelectFile();
clicLoadAgentsFileButton();; if (fileName.length() > 0) {
} ArrayList<String> content = mySimu.getRule();
}); String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
panelRight.add(btnLoadAgents); writeFile(fileName, strArr);
}
JButton btnSaveAgents = new JButton("Save Agents"); }
btnSaveAgents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void clicSaveAgentsToFileButton() {
clicSaveAgentsToFileButton(); String fileName = SelectFile();
} if (fileName.length() > 0) {
}); ArrayList<String> content = mySimu.getAgentsSave();
panelRight.add(btnSaveAgents); String[] strArr = Arrays.copyOf(content.toArray(), content.toArray().length, String[].class);
writeFile(fileName, strArr);
JButton btnRandGen = new JButton("Random Field"); }
btnRandGen.addActionListener(new ActionListener() { }
public void actionPerformed(ActionEvent arg0) {
generateRandomBoard(); public String SelectFile() {
} String s;
}); JFileChooser chooser = new JFileChooser();
panelRight.add(btnRandGen); chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a file");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JLabel randLabel = new JLabel("random density slider :"); chooser.setAcceptAllFileFilterUsed(true);
panelRight.add(randLabel); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
s = chooser.getSelectedFile().toString();
randSlider = new JSlider(); } else {
randSlider.setValue(50); System.out.println("No Selection ");
randSlider.setMinimum(0); s = "";
randSlider.setMaximum(100); }
randSlider.setPreferredSize(new Dimension(30,200)); return s;
panelRight.add(randSlider); }
public void writeFile(String fileName, String[] content) {
JButton btnBorder = new JButton("Toggle Border"); FileWriter csvWriter;
btnBorder.addActionListener(new ActionListener() { try {
public void actionPerformed(ActionEvent arg0) { csvWriter = new FileWriter(fileName);
clicButtonBorder(); for (String row : content) {
} csvWriter.append(row);
}); csvWriter.append("\n");
panelRight.add(btnBorder); }
csvWriter.flush();
panelDraw = new JPanelDraw(this); csvWriter.close();
contentPane.add(panelDraw, BorderLayout.CENTER); } catch (IOException e) {
e.printStackTrace();
instantiateSimu(); }
}
borderLabel = new JLabel("border : X");
panelRight.add(borderLabel); public void update(int stepCount) {
borderLabel.setText("border : " + this.setStepBanner("Step : " + stepCount);
(mySimu.isLoopingBorder()?"loop":"closed")); this.repaint();
}
clickLabel = new JLabel("click : X");
panelRight.add(clickLabel); public void eraseLabels() {
clickLabel.setText("click : " + mySimu.clickActionName()); this.setStepBanner("Step : X");
} this.setBorderBanner("border : X");
this.setClickBanner("click : X");
public void setStepBanner(String s) { speedSlider.setValue(3);
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);
}
}