final code + word document with screenshots for variations

This commit is contained in:
mathe 2024-06-02 22:45:26 +02:00
parent a783e79abc
commit 85a40b7753
1 changed files with 250 additions and 277 deletions

View File

@ -5,45 +5,46 @@ import windowInterface.MyInterface;
public class Simulator extends Thread { public class Simulator extends Thread {
private MyInterface mjf; private MyInterface mjf;
private final int COL_NUM = 100; private final int COL_NUM = 100;
private final int LINE_NUM = 100; private final int LINE_NUM = 100;
private final int LIFE_TYPE_NUM = 4; private final int LIFE_TYPE_NUM = 4;
private final int LIFE_AREA_RADIUS = 1; private final int LIFE_AREA_RADIUS = 1;
private final int ANIMAL_AREA_RADIUS = 2; private final int ANIMAL_AREA_RADIUS = 2;
private ArrayList<Integer> fieldSurviveValues; private ArrayList<Integer> fieldSurviveValues;
private ArrayList<Integer> fieldBirthValues; private ArrayList<Integer> fieldBirthValues;
private ArrayList<Agent> agents; private ArrayList<Agent> agents;
private boolean stopFlag; private boolean stopFlag;
private boolean pauseFlag; private boolean pauseFlag;
private boolean loopingBorder; private boolean loopingBorder;
private boolean clickActionFlag; private boolean clickActionFlag;
private int loopDelay = 150; private int loopDelay = 150;
public int[][] grid; public int[][] grid;
public Simulator(MyInterface mjfParam) { public Simulator(MyInterface mjfParam) {
mjf = mjfParam; mjf = mjfParam;
stopFlag=false; stopFlag=false;
pauseFlag=false; pauseFlag=false;
loopingBorder=false; loopingBorder=false;
clickActionFlag=false; clickActionFlag=false;
grid = new int[COL_NUM][LINE_NUM]; grid = new int[COL_NUM][LINE_NUM];
agents = new ArrayList<Agent>(); agents = new ArrayList<Agent>();
fieldBirthValues = new ArrayList<Integer>(); fieldBirthValues = new ArrayList<Integer>();
fieldSurviveValues = new ArrayList<Integer>(); fieldSurviveValues = new ArrayList<Integer>();
for(int i =0; i<9; i++) { for(int i =0; i<9; i++) {
fieldSurviveValues.add(2); fieldSurviveValues.add(2);
fieldSurviveValues.add(3); fieldSurviveValues.add(3);
fieldBirthValues.add(3); fieldBirthValues.add(3);
} }
} }
private int getSurroundingValues(int x, int y) { private int getSurroundingValues(int x, int y) {
int aliveCount = 0; int aliveCount = 0;
for (int i = -1; i <= 1; i++) { for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) { for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue; if (i == 0 && j == 0) continue;
@ -63,42 +64,42 @@ public class Simulator extends Thread {
} }
} }
return aliveCount; return aliveCount;
} }
public int getWidth() { public int getWidth() {
return COL_NUM; return COL_NUM;
} }
public int getHeight() { public int getHeight() {
return LINE_NUM; return LINE_NUM;
} }
public void run() { public void run() {
int stepCount=0; int stepCount=0;
while(!stopFlag) { while(!stopFlag) {
stepCount++; stepCount++;
makeStep(); makeStep();
mjf.update(stepCount); mjf.update(stepCount);
try { try {
Thread.sleep(loopDelay); Thread.sleep(loopDelay);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
while(pauseFlag && !stopFlag) { while(pauseFlag && !stopFlag) {
try { try {
Thread.sleep(loopDelay); Thread.sleep(loopDelay);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
/** /**
* method called at each step of the simulation * method called at each step of the simulation
* makes all the actions to go from one step to the other * makes all the actions to go from one step to the other
*/ */
public void makeStep() { public void makeStep() {
int[][] nextState = new int[COL_NUM][LINE_NUM]; int[][] nextState = new int[COL_NUM][LINE_NUM];
// Update the state of each cell based on the current state of the grid // Update the state of each cell based on the current state of the grid
@ -118,25 +119,24 @@ public class Simulator extends Thread {
} }
} }
// Update the grid with the new state
for (int x = 0; x < COL_NUM; x++) { for (int x = 0; x < COL_NUM; x++) {
for (int y = 0; y < LINE_NUM; y++) { for (int y = 0; y < LINE_NUM; y++) {
grid[x][y] = nextState[x][y]; grid[x][y] = nextState[x][y];
} }
} }
} }
public void stopSimu() {
stopFlag=true;
public void stopSimu() { }
stopFlag=true; public void togglePause() {
} pauseFlag = !pauseFlag;
public void togglePause() { }
pauseFlag = !pauseFlag;
} /**
* method called when clicking on a cell in the interface
/** */
* method called when clicking on a cell in the interface public void clickCell(int x, int y) {
*/
public void clickCell(int x, int y) {
if (clickActionFlag) { if (clickActionFlag) {
agents.add(new Sheep(x, y)); agents.add(new Sheep(x, y));
} else { } else {
@ -145,20 +145,22 @@ public class Simulator extends Thread {
setCell(x, y, newValue); setCell(x, y, newValue);
} }
} }
/** /**
* get cell value in simulated world * get cell value in simulated world
* @param x coordinate of cell * @param x coordinate of cell
* @param y coordinate of cell * @param y coordinate of cell
* @return value of cell * @return value of cell
*/ */
public int getCell(int x, int y) { public int getCell(int x, int y) {
if (x < 0 || x >= COL_NUM || y < 0 || y >= LINE_NUM) { if (x < 0 || x >= COL_NUM || y < 0 || y >= LINE_NUM) {
return 0; return 0;
} }
return grid[x][y]; return grid[x][y];
} }
/**
private ArrayList<Agent> getNeighboringAgents(int x, int y, int radius) { * @return list of Animals in simulated world
*/
private ArrayList<Agent> getNeighboringAgents(int x, int y, int radius) {
ArrayList<Agent> neighboringAgents = new ArrayList<>(); ArrayList<Agent> neighboringAgents = new ArrayList<>();
// Iterate over agents and check if they are within the radius of the given coordinates // Iterate over agents and check if they are within the radius of the given coordinates
for (Agent agent : agents) { for (Agent agent : agents) {
@ -168,8 +170,9 @@ public class Simulator extends Thread {
} }
return neighboringAgents; return neighboringAgents;
} }
private int countAliveNeighbors(ArrayList<Integer> neighborValues) {
private int countAliveNeighbors(ArrayList<Integer> neighborValues) {
int count = 0; int count = 0;
// Iterate over the neighbor values and count the number of alive cells // Iterate over the neighbor values and count the number of alive cells
for (Integer value : neighborValues) { for (Integer value : neighborValues) {
@ -179,21 +182,19 @@ public class Simulator extends Thread {
} }
return count; return count;
} }
/**
* @return list of Animals in simulated world public void setCell(int x, int y, int val) {
*/ if (x >= 0 && x < COL_NUM && y >= 0 && y < LINE_NUM) {
public ArrayList<Agent> getAnimals(){ grid[x][y] = val;
}
}
public ArrayList<Agent> getAnimals(){
return agents; return agents;
} }
/**
* selects Animals in a circular area of simulated world public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius){
* @param x center
* @param y center
* @param radius
* @return list of agents in area
*/
public ArrayList<Agent> getNeighboringAnimals(int x, int y, int radius){
ArrayList<Agent> inArea = new ArrayList<Agent>(); ArrayList<Agent> inArea = new ArrayList<Agent>();
for(int i=0;i<agents.size();i++) { for(int i=0;i<agents.size();i++) {
Agent agent = agents.get(i); Agent agent = agents.get(i);
@ -203,185 +204,157 @@ public class Simulator extends Thread {
} }
return inArea; return inArea;
} }
public ArrayList<String> getSaveState() {
ArrayList<String> stateLines = new ArrayList<>();
for (int y = 0; y < LINE_NUM; y++) {
StringBuilder line = new StringBuilder();
for (int x = 0; x < COL_NUM; x++) {
line.append(getCell(x, y));
if (x < COL_NUM - 1) {
line.append(";");
}
}
stateLines.add(line.toString());
}
return stateLines;
}
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++) {
* set value of cell String line = lines.get(y);
* @param x coord of cell String[] lineElements = line.split(";");
* @param y coord of cell for(int x=0; x<lineElements.length;x++) {
* @param val to set in cell String elem = lineElements[x];
*/ int value = Integer.parseInt(elem);
public void setCell(int x, int y, int val) { setCell(x, y, value);
if (x >= 0 && x < COL_NUM && y >= 0 && y < LINE_NUM) { }
grid[x][y] = val; }
} }
}
/**
*
* @return lines of file representing
* the simulated world in its present state
*/
public ArrayList<String> getSaveState() {
ArrayList<String> stateLines = new ArrayList<>();
for (int y = 0; y < LINE_NUM; y++) {
StringBuilder line = new StringBuilder();
for (int x = 0; x < COL_NUM; x++) {
line.append(getCell(x, y));
if (x < COL_NUM - 1) {
line.append(";");
}
}
stateLines.add(line.toString());
}
return stateLines;
}
/**
*
* @param lines of file representing saved world state
*/
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++) { public void generateRandom(float chanceOfLife) {
String line = lines.get(y); Random rand = new Random();
String[] lineElements = line.split(";"); for (int x = 0; x < COL_NUM; x++) {
for(int x=0; x<lineElements.length;x++) { for (int y = 0; y < LINE_NUM; y++) {
String elem = lineElements[x]; // Generate a random float between 0 and 1
int value = Integer.parseInt(elem); float randVal = rand.nextFloat();
setCell(x, y, value); if (randVal < chanceOfLife) {
} setCell(x, y, 1);
} } else {
} setCell(x, y, 0);
}
/** }
* 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 boolean isLoopingBorder() {
*/
public void generateRandom(float chanceOfLife) {
Random rand = new Random();
for (int x = 0; x < COL_NUM; x++) {
for (int y = 0; y < LINE_NUM; y++) {
// Generate a random float between 0 and 1
float randVal = rand.nextFloat();
if (randVal < chanceOfLife) {
setCell(x, y, 1);
} else {
setCell(x, y, 0);
}
}
}
}
public boolean isLoopingBorder() {
return loopingBorder; return loopingBorder;
} }
public void toggleLoopingBorder() { public void toggleLoopingBorder() {
loopingBorder = !loopingBorder; loopingBorder = !loopingBorder;
}
public void setLoopDelay(int delay) {
loopDelay = delay;
}
public void toggleClickAction() {
clickActionFlag = !clickActionFlag;
} }
public void setLoopDelay(int delay) {
loopDelay = delay;
}
public void toggleClickAction() {
clickActionFlag = !clickActionFlag;
}
/** public ArrayList<String> getRule() {
* prepare the content of a file saving present ruleSet ArrayList<String> ruleLines = new ArrayList<>();
* as you might want to save a state, StringBuilder surviveLine = new StringBuilder();
* initialy written in this class constructor for (Integer value : fieldSurviveValues) {
* as a file for future use surviveLine.append(value).append(";");
* @return File content as an ArrayList of Lines (String) }
* @see loadRule for inverse process ruleLines.add(surviveLine.toString());
*/
public ArrayList<String> getRule() {
ArrayList<String> ruleLines = new ArrayList<>();
StringBuilder surviveLine = new StringBuilder();
for (Integer value : fieldSurviveValues) {
surviveLine.append(value).append(";");
}
ruleLines.add(surviveLine.toString());
StringBuilder birthLine = new StringBuilder(); StringBuilder birthLine = new StringBuilder();
for (Integer value : fieldBirthValues) { for (Integer value : fieldBirthValues) {
birthLine.append(value).append(";"); birthLine.append(value).append(";");
} }
ruleLines.add(birthLine.toString()); ruleLines.add(birthLine.toString());
return ruleLines; return ruleLines;
} }
public void loadRule(ArrayList<String> lines) { public void loadRule(ArrayList<String> lines) {
if (lines == null || lines.size() < 2) { if (lines == null || lines.size() < 2) {
return; return;
} }
fieldSurviveValues.clear(); fieldSurviveValues.clear();
fieldBirthValues.clear(); fieldBirthValues.clear();
String[] surviveElements = lines.get(0).split(";"); String[] surviveElements = lines.get(0).split(";");
for (String elem : surviveElements) { for (String elem : surviveElements) {
int value = Integer.parseInt(elem); int value = Integer.parseInt(elem);
fieldSurviveValues.add(value); fieldSurviveValues.add(value);
} }
String[] birthElements = lines.get(1).split(";"); String[] birthElements = lines.get(1).split(";");
for (String elem : birthElements) { for (String elem : birthElements) {
int value = Integer.parseInt(elem); int value = Integer.parseInt(elem);
fieldBirthValues.add(value); fieldBirthValues.add(value);
} }
} }
public ArrayList<String> getAgentsSave() { public ArrayList<String> getAgentsSave() {
ArrayList<String> agentLines = new ArrayList<>(); ArrayList<String> agentLines = new ArrayList<>();
for (Agent agent : agents) { for (Agent agent : agents) {
String agentInfo = agent.getClass() + ";" + agent.getX() + ";" + agent.getY(); String agentInfo = agent.getClass() + ";" + agent.getX() + ";" + agent.getY();
agentLines.add(agentInfo); agentLines.add(agentInfo);
} }
return agentLines; return agentLines;
} }
/**public void loadAgents(ArrayList<String> lines) { /**public void loadAgents(ArrayList<String> lines) {
if (lines == null || lines.isEmpty()) { if (lines == null || lines.isEmpty()) {
return; return;
} }
// Clear existing agents // Clear existing agents
agents.clear(); agents.clear();
// Process each line to create agents // Process each line to create agents
for (String line : lines) { for (String line : lines) {
String[] parts = line.split(";"); String[] parts = line.split(";");
if (parts.length >= 3) { if (parts.length >= 3) {
try { try {
// Extract agent class, x-coordinate, and y-coordinate from the line // Extract agent class, x-coordinate, and y-coordinate from the line
String className = parts[0]; String className = parts[0];
int x = Integer.parseInt(parts[1]); int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]); int y = Integer.parseInt(parts[2]);
// Instantiate agent based on the class name and add it to the agents list // Instantiate agent based on the class name and add it to the agents list
Class<?> agentClass = Class.forName(className); Class<?> agentClass = Class.forName(className);
Agent agent = (Agent) agentClass.newInstance(); Agent agent = (Agent) agentClass.newInstance();
agent.setX(x); agent.setX(x);
agent.setY(y); agent.setY(y);
agents.add(agent); agents.add(agent);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NumberFormatException e) { } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NumberFormatException e) {
// Handle any errors (e.g., invalid class name, missing coordinates) // Handle any errors (e.g., invalid class name, missing coordinates)
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
/** /**
* used by label in interface to show the active click action * used by label in interface to show the active click action
* @return String representation of click action * @return String representation of click action
*/ */
public String clickActionName() { public String clickActionName() {
return clickActionFlag ? "sheep" : "cell"; return clickActionFlag ? "sheep" : "cell";
}} }}