latest version

This commit is contained in:
Alperen 2024-06-01 00:00:59 +02:00
parent 7237dc0311
commit 19d55e3803
5 changed files with 774 additions and 880 deletions

View File

@ -1,52 +1,37 @@
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;
}
// Move the agent to a new position
public void move(int newX, int newY) {
this.x = newX;
this.y = newY;
// Add logic for movement restrictions or checks if necessary
}
// Interact with another agent
public abstract void interact(Agent other);
// Example method to check if the agent is at a specific position
public boolean isAtPosition(int checkX, int checkY) {
return this.x == checkX && this.y == checkY;
}
// Abstract method to be implemented by subclasses
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
// Add any additional methods or functionality below as required for the project.
}
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;
}
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
}

View File

@ -1,65 +1,53 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
// Example of a 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 = new Random();
Sheep(int x, int y) {
super(x, y, Color.WHITE); // Sheep are initially white
this.hunger = 5; // Initial hunger level
}
// Method to simulate eating behavior
public void eat() {
if (hunger > 0) {
hunger--;
}
}
// Detailed implementation of interaction with other agents, e.g., wolves
@Override
public void interact(Agent other) {
if (other instanceof Wolf) {
// Logic for being eaten by a wolf
// This could be an indicator to remove this sheep from the world
// This is a placeholder, actual removal should be handled in the simulation logic
}
}
// Retaining original liveTurn and moveRandom methods as per user's code
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;
}
}
// Additional methods or functionality can be added below as required for the project.
// For example, reproduction or aging
}
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
public class Sheep extends Agent {
int hunger;
Random rand;
public Sheep(int x, int y) {
super(x, y, Color.white);
hunger = 0;
rand = new Random();
}
public Sheep(int x, int y, Color color) {
super(x, y, color);
hunger = 0;
rand = new Random();
}
@Override
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if (world.getCell(x, y) == 1) {
world.setCell(x, y, 0);
hunger = 0; // Reset hunger if the Sheep eats
} else {
hunger++;
}
moveRandom(world);
return hunger <= 10; // Sheep dies if hunger exceeds 10
}
private void moveRandom(Simulator world) {
int direction = rand.nextInt(4);
int newX = x, newY = y;
if (direction == 0) {
newX = (x + 1) % world.getWidth();
} else if (direction == 1) {
newY = (y + 1) % world.getHeight();
} else if (direction == 2) {
newX = (x - 1 + world.getWidth()) % world.getWidth();
} else if (direction == 3) {
newY = (y - 1 + world.getHeight()) % world.getHeight();
}
if (world.isLoopingBorder() || (newX >= 0 && newX < world.getWidth() && newY >= 0 && newY < world.getHeight())) {
x = newX;
y = newY;
}
}
}

View File

@ -1,272 +1,232 @@
package backend;
import java.util.ArrayList;
import java.util.Iterator;
import windowInterface.MyInterface;
public class Simulator extends Thread {
private MyInterface mjf;
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;
private int[][] world; // Added missing attribute for the world grid
public Simulator(MyInterface mjfParam) {
mjf = mjfParam;
stopFlag = false;
pauseFlag = false;
loopingBorder = false;
clickActionFlag = false;
agents = new ArrayList<Agent>();
fieldBirthValues = new ArrayList<Integer>();
fieldSurviveValues = new ArrayList<Integer>();
world = new int[COL_NUM][LINE_NUM]; // Initializing the world grid
// Default rule: Survive always, birth never
for (int i = 0; i < 9; i++) {
fieldSurviveValues.add(i);
}
}
public int getWidth() {
return COL_NUM;
}
public int getHeight() {
return LINE_NUM;
}
public void run() {
int stepCount = 0;
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() {
Iterator<Agent> agentIterator = agents.iterator();
while (agentIterator.hasNext()) {
Agent agent = agentIterator.next();
ArrayList<Agent> neighbors = this.getNeighboringAnimals(agent.getX(), agent.getY(), ANIMAL_AREA_RADIUS);
if (!agent.liveTurn(neighbors, this)) {
agentIterator.remove();
}
}
int[][] newWorld = new int[COL_NUM][LINE_NUM];
for (int i = 0; i < COL_NUM; i++) {
for (int j = 0; j < LINE_NUM; j++) {
int liveNeighbors = countLiveNeighbors(i, j);
if (world[i][j] == 1 && fieldSurviveValues.contains(liveNeighbors)) {
newWorld[i][j] = 1;
} else if (world[i][j] == 0 && fieldBirthValues.contains(liveNeighbors)) {
newWorld[i][j] = 1;
} else {
newWorld[i][j] = 0;
}
}
}
world = newWorld;
}
private int countLiveNeighbors(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
int nx = x + i;
int ny = y + j;
if (loopingBorder) {
nx = (nx + COL_NUM) % COL_NUM;
ny = (ny + LINE_NUM) % LINE_NUM;
}
if (nx >= 0 && nx < COL_NUM && ny >= 0 && ny < LINE_NUM) {
count += world[nx][ny];
}
}
}
return count;
}
public void stopSimu() {
stopFlag = true;
}
public void togglePause() {
pauseFlag = !pauseFlag;
}
public void clickCell(int x, int y) {
if (clickActionFlag) {
// Example agent creation (Sheep) at clicked coordinates
agents.add(new Sheep(x, y));
} else {
world[x][y] = world[x][y] == 1 ? 0 : 1;
}
}
public int getCell(int x, int y) {
return world[x][y];
}
public ArrayList<Agent> getAnimals() {
return agents;
}
public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius) {
ArrayList<Agent> inArea = new ArrayList<Agent>();
for (Agent agent : agents) {
if (agent.isInArea(x, y, radius)) {
inArea.add(agent);
}
}
return inArea;
}
public void setCell(int x, int y, int val) {
world[x][y] = val;
}
public ArrayList<String> getSaveState() {
ArrayList<String> lines = new ArrayList<String>();
for (int y = 0; y < LINE_NUM; y++) {
StringBuilder line = new StringBuilder();
for (int x = 0; x < COL_NUM; x++) {
line.append(world[x][y]);
if (x < COL_NUM - 1) {
line.append(";");
}
}
lines.add(line.toString());
}
return lines;
}
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);
}
}
}
public void generateRandom(float chanceOfLife) {
for (int x = 0; x < COL_NUM; x++) {
for (int y = 0; y < LINE_NUM; y++) {
world[x][y] = Math.random() < chanceOfLife ? 1 : 0;
}
}
}
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> lines = new ArrayList<String>();
StringBuilder surviveLine = new StringBuilder();
StringBuilder birthLine = new StringBuilder();
for (int i = 0; i < fieldSurviveValues.size(); i++) {
surviveLine.append(fieldSurviveValues.get(i));
if (i < fieldSurviveValues.size() - 1) {
surviveLine.append(";");
}
}
for (int i = 0; i < fieldBirthValues.size(); i++) {
birthLine.append(fieldBirthValues.get(i));
if (i < fieldBirthValues.size() - 1) {
birthLine.append(";");
}
}
lines.add(surviveLine.toString());
lines.add(birthLine.toString());
return lines;
}
public void loadRule(ArrayList<String> lines) {
if (lines.size() <= 0) {
System.out.println("empty rule file");
return;
}
fieldSurviveValues.clear();
fieldBirthValues.clear();
String surviveLine = lines.get(0);
String birthLine = lines.get(1);
String[] surviveElements = surviveLine.split(";");
for (String elem : surviveElements) {
int value = Integer.parseInt(elem);
fieldSurviveValues.add(value);
}
String[] birthElements = birthLine.split(";");
for (String elem : birthElements) {
int value = Integer.parseInt(elem);
fieldBirthValues.add(value);
}
}
public ArrayList<String> getAgentsSave() {
ArrayList<String> lines = new ArrayList<String>();
for (Agent agent : agents) {
lines.add(agent.toString());
}
return lines;
}
public void loadAgents(ArrayList<String> stringArray) {
agents.clear();
for (String line : stringArray) {
// Example agent loading (assuming the toString format contains necessary info)
String[] parts = line.split(",");
if (parts.length == 3 && parts[0].equals("Sheep")) {
agents.add(new Sheep(Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
}
}
}
public String clickActionName() {
return clickActionFlag ? "Sheep" : "Cell";
}
}
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import windowInterface.MyInterface;
public class Simulator extends Thread {
private MyInterface mjf;
private final int COL_NUM = 100;
private final int LINE_NUM = 100;
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;
private boolean[][] world;
public Simulator(MyInterface mjfParam) {
mjf = mjfParam;
stopFlag = false;
pauseFlag = false;
loopingBorder = false;
clickActionFlag = false;
agents = new ArrayList<Agent>();
fieldBirthValues = new ArrayList<Integer>();
fieldSurviveValues = new ArrayList<Integer>();
world = new boolean[LINE_NUM][COL_NUM];
// Default rules: Conway's Game of Life (B3/S23)
fieldSurviveValues.add(2);
fieldSurviveValues.add(3);
fieldBirthValues.add(3);
}
public int getWidth() {
return COL_NUM;
}
public int getHeight() {
return LINE_NUM;
}
@Override
public void run() {
int stepCount = 0;
while (!stopFlag) {
if (!pauseFlag) {
stepCount++;
makeStep();
mjf.update(stepCount);
}
try {
Thread.sleep(loopDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void makeStep() {
boolean[][] newWorld = new boolean[LINE_NUM][COL_NUM];
for (int i = 0; i < LINE_NUM; i++) {
for (int j = 0; j < COL_NUM; j++) {
int neighbors = countNeighbors(i, j);
if (world[i][j]) {
newWorld[i][j] = fieldSurviveValues.contains(neighbors);
} else {
newWorld[i][j] = fieldBirthValues.contains(neighbors);
}
}
}
world = newWorld;
// Agent behavior
Iterator<Agent> agentIterator = agents.iterator();
while (agentIterator.hasNext()) {
Agent agent = agentIterator.next();
ArrayList<Agent> neighbors = this.getNeighboringAnimals(agent.getX(), agent.getY(), 1);
if (!agent.liveTurn(neighbors, this)) {
agentIterator.remove();
}
}
}
private int countNeighbors(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
int nx = (x + i + LINE_NUM) % LINE_NUM;
int ny = (y + j + COL_NUM) % COL_NUM;
if (world[nx][ny]) count++;
}
}
return count;
}
public void toggleLoopingBorder() {
loopingBorder = !loopingBorder;
}
public boolean isLoopingBorder() {
return loopingBorder;
}
public void togglePause() {
pauseFlag = !pauseFlag;
}
public void setLoopDelay(int delay) {
loopDelay = delay;
}
public void clickCell(int x, int y) {
if (clickActionFlag) {
agents.add(new Sheep(x, y));
} else {
world[y][x] = !world[y][x];
}
}
public int getCell(int x, int y) {
return world[y][x] ? 1 : 0;
}
public void setCell(int x, int y, int val) {
world[y][x] = val == 1;
}
public ArrayList<Agent> getAnimals() {
return agents;
}
public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius) {
ArrayList<Agent> inArea = new ArrayList<Agent>();
for (Agent agent : agents) {
if (agent.isInArea(x, y, radius)) {
inArea.add(agent);
}
}
return inArea;
}
public ArrayList<String> getSaveState() {
ArrayList<String> saveState = new ArrayList<String>();
for (int i = 0; i < LINE_NUM; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < COL_NUM; j++) {
line.append(world[i][j] ? 1 : 0);
if (j < COL_NUM - 1) line.append(";");
}
saveState.add(line.toString());
}
return saveState;
}
public void loadSaveState(ArrayList<String> lines) {
for (int i = 0; i < lines.size(); i++) {
String[] lineElements = lines.get(i).split(";");
for (int j = 0; j < lineElements.length; j++) {
world[i][j] = Integer.parseInt(lineElements[j]) == 1;
}
}
}
public void generateRandom(float chanceOfLife) {
for (int i = 0; i < LINE_NUM; i++) {
for (int j = 0; j < COL_NUM; j++) {
world[i][j] = Math.random() < chanceOfLife;
}
}
}
public void toggleClickAction() {
clickActionFlag = !clickActionFlag;
}
public ArrayList<String> getRule() {
ArrayList<String> rule = new ArrayList<String>();
StringBuilder surviveRule = new StringBuilder();
for (Integer val : fieldSurviveValues) {
surviveRule.append(val).append(";");
}
StringBuilder birthRule = new StringBuilder();
for (Integer val : fieldBirthValues) {
birthRule.append(val).append(";");
}
rule.add(surviveRule.toString());
rule.add(birthRule.toString());
return rule;
}
public void loadRule(ArrayList<String> lines) {
fieldSurviveValues.clear();
fieldBirthValues.clear();
String[] surviveElements = lines.get(0).split(";");
for (String elem : surviveElements) {
fieldSurviveValues.add(Integer.parseInt(elem));
}
String[] birthElements = lines.get(1).split(";");
for (String elem : birthElements) {
fieldBirthValues.add(Integer.parseInt(elem));
}
}
public ArrayList<String> getAgentsSave() {
ArrayList<String> agentSaves = new ArrayList<String>();
for (Agent agent : agents) {
agentSaves.add(agent.getX() + ";" + agent.getY() + ";" + agent.getDisplayColor().getRGB());
}
return agentSaves;
}
public void loadAgents(ArrayList<String> lines) {
agents.clear();
for (String line : lines) {
String[] elements = line.split(";");
int x = Integer.parseInt(elements[0]);
int y = Integer.parseInt(elements[1]);
Color color = new Color(Integer.parseInt(elements[2]));
agents.add(new Sheep(x, y, color));
}
}
public String clickActionName() {
return clickActionFlag ? "sheep" : "cell";
}
}

View File

@ -1,94 +1,77 @@
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));
}
}
}
}
package windowInterface;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
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) {
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) {
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);
} else if (cellContent == 2) {
g.setColor(Color.yellow);
} else 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

@ -1,397 +1,375 @@
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);
}
}
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;
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 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.stop();
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);
}
}