final - complexified

This commit is contained in:
paull 2024-06-01 16:37:48 +02:00
parent 804060575d
commit 7dde3bc47a
4 changed files with 177 additions and 156 deletions

View File

@ -30,15 +30,37 @@ public abstract class Agent {
return dist<radius; return dist<radius;
} }
public String saveState() {
return String.format("%s;%d;%d;%d;%d;%d",
this.getClass().getSimpleName(),
x, y,
color.getRed(), color.getGreen(), color.getBlue());
}
public static Agent loadState(String state) {
String[] parts = state.split(";");
String className = parts[0];
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int r = Integer.parseInt(parts[3]);
int g = Integer.parseInt(parts[4]);
int b = Integer.parseInt(parts[5]);
Color color = new Color(r, g, b);
// Create the specific agent type based on the class name
switch (className) {
case "Sheep":
return new Sheep(x, y, color);
// Add cases for other agent types here
default:
throw new IllegalArgumentException("Unknown agent type: " + className);
}
}
// Does whatever the agent does during a step // Does whatever the agent does during a step
// then returns a boolean // then returns a boolean
// if false, agent dies at end of turn // if false, agent dies at end of turn
// see step function in Simulator // see step function in Simulator
public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world); public abstract boolean liveTurn(ArrayList<Agent> neighbors, Simulator world);
public static Agent fromString(String line) {
return null;
}
} }

View File

@ -4,15 +4,15 @@ 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;
public Sheep(int x, int y, Color color) {
super(x, y, color);
}
Sheep(int x,int y){ Sheep(int x,int y){
//first we call the constructor of the superClass(Animal) //first we call the constructor of the superClass(Animal)
//with the values we want. //with the values we want.
@ -32,28 +32,38 @@ public class Sheep extends Agent {
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) { public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if(world.getCell(x, y)==1) { if(world.getCell(x, y)==1) {
world.setCell(x, y, 0); world.setCell(x, y, 0);
hunger = 0; // Reset hunger if the sheep finds food
} else { } else {
hunger++; hunger++;
} }
this.moveRandom(); this.moveRandom();
return hunger>10; return hunger <= 10; // Sheep survives if hunger is 10 or less
} }
private void moveRandom() { private void moveRandom() {
int direction = rand.nextInt(4); int direction = rand.nextInt(4);
if(direction == 0) { switch(direction) {
x+=1; case 0: x += 1; break;
} case 1: y += 1; break;
if(direction == 1) { case 2: x -= 1; break;
y+=1; case 3: y -= 1; break;
}
if(direction == 2) {
x-=1;
}
if(direction == 3) {
y-=1;
} }
} }
// Parsing method to create Sheep from a string
public static Sheep parse(String line) {
String[] parts = line.split(";");
int x = Integer.parseInt(parts[0]);
int y = Integer.parseInt(parts[1]);
// We don't parse color here since Sheep is always white
Sheep sheep = new Sheep(x, y);
sheep.hunger = Integer.parseInt(parts[2]); // Parsing hunger value
return sheep;
}
@Override
public String toString() {
return x + ";" + y + ";" + hunger;
}
} }

View File

@ -1,5 +1,6 @@
package backend; package backend;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Random;
import windowInterface.MyInterface; import windowInterface.MyInterface;
@ -7,13 +8,11 @@ public class Simulator extends Thread {
private MyInterface mjf; private MyInterface mjf;
private final int COL_NUM = 100; private boolean[][] grid; // 2D array representing the current state of the grid
private final int LINE_NUM = 100; private boolean[][] newGrid; // 2D array representing the next state of the grid
private final int LIFE_TYPE_NUM = 4; private int LINE_NUM;
//Conway Radius : 1 private int COL_NUM;
private final int LIFE_AREA_RADIUS = 1;
//Animal Neighborhood Radius : 5
private final int ANIMAL_AREA_RADIUS = 2;
private ArrayList<Integer> fieldSurviveValues; private ArrayList<Integer> fieldSurviveValues;
private ArrayList<Integer> fieldBirthValues; private ArrayList<Integer> fieldBirthValues;
@ -25,7 +24,7 @@ public class Simulator extends Thread {
private boolean clickActionFlag; private boolean clickActionFlag;
private int loopDelay = 150; private int loopDelay = 150;
public int[][] grid; private boolean running = false; // New flag to track if the thread is running
public Simulator(MyInterface mjfParam) { public Simulator(MyInterface mjfParam) {
mjf = mjfParam; mjf = mjfParam;
@ -38,12 +37,15 @@ public class Simulator extends Thread {
fieldBirthValues = new ArrayList<Integer>(); fieldBirthValues = new ArrayList<Integer>();
fieldSurviveValues = new ArrayList<Integer>(); fieldSurviveValues = new ArrayList<Integer>();
grid = new int[LINE_NUM][COL_NUM]; LINE_NUM = mjfParam.getX();
COL_NUM = mjfParam.getY();
grid = new boolean[LINE_NUM][COL_NUM];
newGrid = new boolean[LINE_NUM][COL_NUM];
// Default rule : Survive always, birth never // Default rule: Survive on 2 or 3 neighbors, birth on 3 neighbors
for (int i = 0; i < 9; i++) { fieldSurviveValues.add(2);
fieldSurviveValues.add(i); fieldSurviveValues.add(3);
} fieldBirthValues.add(3);
} }
public int getWidth() { public int getWidth() {
@ -54,10 +56,12 @@ public class Simulator extends Thread {
return LINE_NUM; return LINE_NUM;
} }
//Should probably stay as is // Runs the simulation
public void run() { public void run() {
int stepCount=0; if (running) return; // Prevents the thread from being started more than once
while(!stopFlag) { running = true;
int stepCount = 0;
while (!stopFlag) {
stepCount++; stepCount++;
makeStep(); makeStep();
mjf.update(stepCount); mjf.update(stepCount);
@ -66,7 +70,7 @@ public class Simulator extends Thread {
} 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) {
@ -74,61 +78,62 @@ public class Simulator extends Thread {
} }
} }
} }
running = false; // Reset the running flag when the thread finishes
} }
/** /**
* 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[][] newGrid = new int[LINE_NUM][COL_NUM]; try {
for (Agent agent : agents) {
ArrayList<Agent> neighbors = getNeighboringAnimals(agent.getX(), agent.getY(), 2);
if (!agent.liveTurn(neighbors, this)) {
agents.remove(agent);
}
}
for (int y = 0; y < LINE_NUM; y++) { for (int y = 0; y < LINE_NUM; y++) {
for (int x = 0; x < COL_NUM; x++) { for (int x = 0; x < COL_NUM; x++) {
int aliveNeighbors = countAliveNeighbors(x, y); int liveNeighbors = countLiveNeighbors(y, x);
if (grid[y][x]) {
if (grid[y][x] == 1) { newGrid[y][x] = fieldSurviveValues.contains(liveNeighbors);
if (aliveNeighbors < 2 || aliveNeighbors > 3) {
newGrid[y][x] = 0;
} else { } else {
newGrid[y][x] = 1; newGrid[y][x] = fieldBirthValues.contains(liveNeighbors);
}
} else {
if (aliveNeighbors == 3) {
newGrid[y][x] = 1;
} else {
newGrid[y][x] = 0;
} }
} }
} }
} boolean[][] temp = grid;
grid = newGrid; grid = newGrid;
newGrid = temp;
} catch (Exception e) {
boolean[][] temp = grid;
grid = newGrid;
newGrid = temp;
}
} }
// Counts live neighbors
private int countAliveNeighbors(int x, int y) { private int countLiveNeighbors(int y, int x) {
int aliveCount = 0; int count = 0;
int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1}; int[] directions = {-1, 0, 1};
int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1}; for (int i : directions) {
for (int j : directions) {
for (int i = 0; i < 8; i++) { if (i == 0 && j == 0) continue;
int nx = x + dx[i]; int neighbory = y + i;
int ny = y + dy[i]; int neighborCol = x + j;
if (loopingBorder) { if (loopingBorder) {
nx = (nx + COL_NUM) % COL_NUM; neighbory = (neighbory + LINE_NUM) % LINE_NUM;
ny = (ny + LINE_NUM) % LINE_NUM; neighborCol = (neighborCol + COL_NUM) % COL_NUM;
} }
if (isInBounds(neighbory, neighborCol) && grid[neighbory][neighborCol]) {
if (nx >= 0 && nx < COL_NUM && ny >= 0 && ny < LINE_NUM) { count++;
aliveCount += grid[ny][nx];
} }
} }
}
return aliveCount; return count;
} }
/* /*
@ -152,8 +157,7 @@ public class Simulator extends Thread {
if (clickActionFlag) { if (clickActionFlag) {
agents.add(new Sheep(x, y)); agents.add(new Sheep(x, y));
} else { } else {
int currentState = getCell(x, y); grid[x][y] = !grid[x][y];
setCell(x, y, currentState == 0 ? 1 : 0);
} }
} }
@ -164,10 +168,13 @@ public class Simulator extends Thread {
* @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) { int i =1;
return grid[y][x]; try {
return grid[x][y] ? 1 : 0;
}catch (Exception e) {
i = 0;
} }
return 0; return i;
} }
/** /**
@ -202,9 +209,7 @@ public class Simulator extends Thread {
* @param val to set in cell * @param val to set in cell
*/ */
public void setCell(int x, int y, int val) { public void setCell(int x, int y, int val) {
if (x >= 0 && x < COL_NUM && y >= 0 && y < LINE_NUM) { grid[x][y] = (val == 1);
grid[y][x] = val;
}
} }
/** /**
@ -215,14 +220,11 @@ public class Simulator extends Thread {
public ArrayList<String> getSaveState() { public ArrayList<String> getSaveState() {
ArrayList<String> saveState = new ArrayList<String>(); ArrayList<String> saveState = new ArrayList<String>();
for (int y = 0; y < LINE_NUM; y++) { for (int y = 0; y < LINE_NUM; y++) {
StringBuilder sb = new StringBuilder(); StringBuilder line = new StringBuilder();
for (int x = 0; x < COL_NUM; x++) { for (int x = 0; x < COL_NUM; x++) {
sb.append(grid[y][x]); line.append(grid[x][y] ? "1" : "0").append(";");
if (x < COL_NUM - 1) {
sb.append(";");
} }
} saveState.add(line.toString());
saveState.add(sb.toString());
} }
return saveState; return saveState;
} }
@ -232,16 +234,13 @@ public class Simulator extends Thread {
* @param lines of file representing saved world state * @param lines of file representing saved world state
*/ */
public void loadSaveState(ArrayList<String> lines) { public void loadSaveState(ArrayList<String> lines) {
if (lines.size() != LINE_NUM) { if (lines.size() <= 0) return;
return;
} for (int y = 0; y < lines.size(); y++) {
for (int y = 0; y < LINE_NUM; y++) {
String[] lineElements = lines.get(y).split(";"); String[] lineElements = lines.get(y).split(";");
if (lineElements.length != COL_NUM) { for (int x = 0; x < lineElements.length; x++) {
return; int value = Integer.parseInt(lineElements[x]);
} setCell(x, y, value);
for (int x = 0; x < COL_NUM; x++) {
grid[y][x] = Integer.parseInt(lineElements[x]);
} }
} }
} }
@ -253,9 +252,10 @@ public class Simulator extends Thread {
* to be alive in new state * to be alive in new state
*/ */
public void generateRandom(float chanceOfLife) { public void generateRandom(float chanceOfLife) {
Random rand = new Random();
for (int y = 0; y < LINE_NUM; y++) { for (int y = 0; y < LINE_NUM; y++) {
for (int x = 0; x < COL_NUM; x++) { for (int x = 0; x < COL_NUM; x++) {
grid[y][x] = Math.random() < chanceOfLife ? 1 : 0; grid[x][y] = rand.nextFloat() < chanceOfLife;
} }
} }
} }
@ -286,60 +286,44 @@ public class Simulator extends Thread {
*/ */
public ArrayList<String> getRule() { public ArrayList<String> getRule() {
ArrayList<String> rules = new ArrayList<String>(); ArrayList<String> rules = new ArrayList<String>();
StringBuilder surviveBuilder = new StringBuilder(); rules.add("Survive: " + fieldSurviveValues.toString());
StringBuilder birthBuilder = new StringBuilder(); rules.add("Birth: " + fieldBirthValues.toString());
for (int value : fieldSurviveValues) {
surviveBuilder.append(value).append(";");
}
for (int value : fieldBirthValues) {
birthBuilder.append(value).append(";");
}
rules.add(surviveBuilder.toString());
rules.add(birthBuilder.toString());
return rules; return rules;
} }
// Loads the rules of the simulation
public void loadRule(ArrayList<String> lines) { public void loadRule(ArrayList<String> lines) {
if (lines.size() < 2) { if (lines.size() <= 0) return;
System.out.println("empty rule file");
return;
}
fieldSurviveValues.clear(); fieldSurviveValues.clear();
fieldBirthValues.clear(); fieldBirthValues.clear();
for (String line : lines) {
String[] surviveElements = lines.get(0).split(";"); if (line.startsWith("Survive: ")) {
for (String elem : surviveElements) { String[] surviveRules = line.replace("Survive: ", "").replaceAll("[\\[\\]]", "").split(", ");
if (!elem.isEmpty()) { for (String rule : surviveRules) {
fieldSurviveValues.add(Integer.parseInt(elem)); fieldSurviveValues.add(Integer.parseInt(rule));
} }
} else if (line.startsWith("Birth: ")) {
String[] birthRules = line.replace("Birth: ", "").replaceAll("[\\[\\]]", "").split(", ");
for (String rule : birthRules) {
fieldBirthValues.add(Integer.parseInt(rule));
} }
String[] birthElements = lines.get(1).split(";");
for (String elem : birthElements) {
if (!elem.isEmpty()) {
fieldBirthValues.add(Integer.parseInt(elem));
} }
} }
} }
public ArrayList<String> getAgentsSave() { public ArrayList<String> getAgentsSave() {
ArrayList<String> saveState = new ArrayList<>(); ArrayList<String> agentsSave = new ArrayList<>();
for (Agent agent : agents) { for (Agent agent : agents) {
saveState.add(agent.toString()); agentsSave.add(agent.saveState());
} }
return saveState; return agentsSave;
} }
public void loadAgents(ArrayList<String> stringArray) { public void loadAgents(ArrayList<String> lines) {
agents.clear(); agents.clear();
for (String line : stringArray) { for (String line : lines) {
Agent agent = Agent.fromString(line); agents.add(Agent.loadState(line));
if (agent != null) {
agents.add(agent);
}
} }
} }
@ -350,4 +334,9 @@ public class Simulator extends Thread {
public String clickActionName() { public String clickActionName() {
return clickActionFlag ? "sheep" : "cell"; return clickActionFlag ? "sheep" : "cell";
} }
// Checks if the coordinates are in bounds
private boolean isInBounds(int y, int x) {
return y >= 0 && y < LINE_NUM && x >= 0 && x < COL_NUM;
}
} }

View File

@ -44,7 +44,7 @@ public class MyInterface extends JFrame {
*/ */
public MyInterface() { public MyInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10, 10, 700, 600); setBounds(100, 100, 700, 600);
contentPane = new JPanel(); contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0)); contentPane.setLayout(new BorderLayout(0, 0));