Version finale

This commit is contained in:
Utilisateur 2024-06-02 23:50:05 +02:00
parent 160aea46c4
commit ec97401b75
5 changed files with 626 additions and 382 deletions

View File

@ -0,0 +1,29 @@
package backend;
public class Cell {
private int state;
public Cell(int state) {
this.setState(state);
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
if (state == 4) {
this.state = -3;
}
}
public void age() {
if (state > 0 && state < 4) {
state = Math.min(state + 1, 3);
} else if (state < 0) {
this.state++;
}
}
}

View File

@ -0,0 +1,44 @@
package backend;
public class Grid {
private int[][] grid;
// Constructor to initialize the grid with given dimensions
public Grid(int rows, int columns) {
grid = new int[rows][columns];
}
// Method to set the value of a cell at specified coordinates
public void setValue(int x, int y, int value) {
grid[x][y] = value;
}
// Method to get the value of a cell at specified coordinates
public int getValue(int x, int y) {
return grid[x][y];
}
// Method to get the number of rows in the grid
public int getRowCount() {
return grid.length;
}
// Method to get the number of columns in the grid
public int getColumnCount() {
return grid[0].length;
}
// Additional method to get the Cell object for logic purposes
public Cell getCell(int x, int y) {
return new Cell(grid[x][y]);
}
// Additional method to set the Cell object state
public void setCell(int x, int y, Cell cell) {
grid[x][y] = cell.getState();
}
}

View File

@ -1,5 +1,7 @@
package backend;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import windowInterface.MyInterface;
@ -14,17 +16,20 @@ public class Simulator extends Thread {
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> fieldBirthValues;
private List<List<Integer>> survivalRules;
private List<List<Integer>> birthRules;
private ArrayList<Agent> agents;
private boolean stopFlag;
private boolean pauseFlag;
private boolean loopingBorder;
private boolean clickActionFlag;
private String clickActionFlag;
private int loopDelay = 150;
private Grid grid;
//TODO : add missing attribute(s)
public Simulator(MyInterface mjfParam) {
@ -32,31 +37,36 @@ public class Simulator extends Thread {
stopFlag=false;
pauseFlag=false;
loopingBorder=false;
clickActionFlag=false;
clickActionFlag="Cells";
agents = new ArrayList<Agent>();
fieldBirthValues = new ArrayList<Integer>();
fieldSurviveValues = new ArrayList<Integer>();
//TODO : add missing attribute initialization
// Initialize rules
survivalRules = new ArrayList<>();
birthRules = new ArrayList<>();
// Define survival rules for each cell state
survivalRules.add(Arrays.asList()); // State 0 (Dead cells don't survive)
survivalRules.add(Arrays.asList(2, 3)); // State 1 (Young cells)
survivalRules.add(Arrays.asList(2, 3, 4)); // State 2 (Middle-aged cells)
survivalRules.add(Arrays.asList(1, 2, 3)); // State 3 (Old cells)
// Define birth rules for each cell state
birthRules.add(Arrays.asList(3)); // State 0 (Dead cells birth to young cells)
birthRules.add(Arrays.asList()); // State 1 (Young cells don't give birth)
birthRules.add(Arrays.asList()); // State 2 (Middle-aged cells don't give birth)
birthRules.add(Arrays.asList(4)); // State 3 (Old cells give birth to young cells)
//Default rule : Survive always, birth never
for(int i =0; i<9; i++) {
fieldSurviveValues.add(i);
}
grid = new Grid(LINE_NUM, COL_NUM);
}
public int getWidth() {
//TODO : replace with proper return
return 0;
return LINE_NUM;
}
public int getHeight() {
//TODO : replace with proper return
return 0;
return COL_NUM;
}
//Should probably stay as is
@ -87,10 +97,7 @@ public class Simulator extends Thread {
* makes all the actions to go from one step to the other
*/
public void makeStep() {
// agent behaviors first
// only modify if sure of what you do
// to modify agent behavior, see liveTurn method
// in agent classes
// Agent behaviors first
for(Agent agent : agents) {
ArrayList<Agent> neighbors =
this.getNeighboringAnimals(
@ -103,27 +110,75 @@ public class Simulator extends Thread {
agents.remove(agent);
}
}
//then evolution of the field
// TODO : apply game rule to all cells of the field
/* you should distribute this action in methods/classes
* don't write everything here !
*
* 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
* if the cell is alive
* and the count is in the survive list,
* then the cell stays alive
* if the cell is not alive
* and the count is in the birth list,
* then the cell becomes alive
*/
// Then evolution of the field
Grid nextGrid = new Grid(LINE_NUM, COL_NUM);
for (int i = 0; i < LINE_NUM; i++) {
for (int j = 0; j < COL_NUM; j++) {
Cell cell = grid.getCell(i, j);
int liveNeighbors = countLiveNeighbors(i, j);
int cellState = cell.getState();
if (cellState > 0 && cellState < 4) { // For living cells
if (survivalRules.get(cellState).contains(liveNeighbors)) {
cell.age();
nextGrid.setCell(i, j, cell);
} else {
nextGrid.setValue(i, j, 0);
}
} else if (cellState < 0) {
cell.age();
if (cell.getState() == 0) {
nextGrid.setValue(i, j, 0);
} else {
nextGrid.setCell(i, j, cell);
}
} else {
if (birthRules.get(cellState).contains(liveNeighbors)) {
nextGrid.setValue(i, j, 1);
}
}
}
}
grid = nextGrid;
}
/*
* method called to count living cells around one
*/
public int countLiveNeighbors(int x, int y) {
int liveNeighbors = 0;
for (int i = -LIFE_AREA_RADIUS; i <= LIFE_AREA_RADIUS; i++) {
for (int j = -LIFE_AREA_RADIUS; j <= LIFE_AREA_RADIUS; j++) {
if (i == 0 && j == 0) continue;
int neighborX = x + i;
int neighborY = y + j;
if (loopingBorder) {
if (neighborX < 0) neighborX = LINE_NUM - 1;
else if (neighborX >= LINE_NUM) neighborX = 0;
if (neighborY < 0) neighborY = COL_NUM - 1;
else if (neighborY >= COL_NUM) neighborY = 0;
}
if (neighborX >= 0 && neighborX < LINE_NUM && neighborY >= 0 && neighborY < COL_NUM) {
if (grid.getValue(neighborX, neighborY) > 0) {
liveNeighbors++;
}
}
}
}
return liveNeighbors;
}
/*
* leave this as is
@ -136,14 +191,26 @@ public class Simulator extends Thread {
* method called when clicking pause button
*/
public void togglePause() {
// TODO : actually toggle the corresponding flag
if (pauseFlag == true ) {
pauseFlag=false;
}
else {
pauseFlag=true;
}
}
/**
* method called when clicking on a cell in the interface
* Cycles through cell states: 0 (dead), 1 (young), 2 (middle-aged), 3 (old).
*/
public void clickCell(int x, int y) {
//TODO : complete method
if (clickActionFlag.equals("Cells")) {
int currentValue = grid.getValue(x, y);
int nextValue = (currentValue + 1) % 5; // Change to 5 to include infected state
this.setCell(x, y, nextValue);
} else if (clickActionFlag.equals("Virus")) {
agents.add(new Virus(x, y)); // Add a new Virus agent at the clicked location
}
}
/**
@ -153,8 +220,7 @@ public class Simulator extends Thread {
* @return value of cell
*/
public int getCell(int x, int y) {
//TODO : complete method with proper return
return 0;
return grid.getValue(x, y);
}
/**
*
@ -188,7 +254,7 @@ public class Simulator extends Thread {
* @param val to set in cell
*/
public void setCell(int x, int y, int val) {
//TODO : complete method
grid.setValue(x, y, val);
}
/**
@ -197,8 +263,19 @@ public class Simulator extends Thread {
* the simulated world in its present state
*/
public ArrayList<String> getSaveState() {
//TODO : complete method with proper return
return null;
ArrayList<String> saveState = new ArrayList<>();
for (int i = 0; i < LINE_NUM; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < COL_NUM; j++) {
line.append(grid.getValue(i, j));
if (j < COL_NUM - 1) {
line.append(";");
}
}
saveState.add(line.toString());
}
return saveState;
}
/**
*
@ -241,32 +318,41 @@ public class Simulator extends Thread {
* 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
*/
for (int i = 0; i < LINE_NUM; i++) {
for (int j = 0; j < COL_NUM; j++) {
float randomValue = (float) Math.random();
if (randomValue <= chanceOfLife) {
grid.setValue(i, j, 1);
} else {
grid.setValue(i, j, 0);
}
}
}
}
public boolean isLoopingBorder() {
//TODO : complete method with proper return
return false;
return loopingBorder;
}
public void toggleLoopingBorder() {
//TODO : complete method
if (isLoopingBorder() == true) {
loopingBorder=false;
}else {
loopingBorder=true;
}
}
public void setLoopDelay(int delay) {
//TODO : complete method
loopDelay=delay;
}
public void toggleClickAction() {
//TODO : complete method
if (clickActionFlag.equals("Cells")) {
clickActionFlag = "Virus";
} else {
clickActionFlag = "Cells";
}
}
/**
@ -278,45 +364,83 @@ public class Simulator extends Thread {
* @see loadRule for inverse process
*/
public ArrayList<String> getRule() {
//TODO : complete method with proper return
ArrayList<String> rule = new ArrayList<>();
return null;
// Add survival rules for each cell state
for (List<Integer> stateRules : survivalRules) {
rule.add(String.join(";", stateRules.stream().map(Object::toString).toArray(String[]::new)));
}
// Add birth rules for each cell state
for (List<Integer> stateRules : birthRules) {
rule.add(String.join(";", stateRules.stream().map(Object::toString).toArray(String[]::new)));
}
return rule;
}
public void loadRule(ArrayList<String> lines) {
if(lines.size()<=0) {
System.out.println("empty rule file");
if (lines.size() != LIFE_TYPE_NUM * 2) {
System.out.println("Invalid rule file format");
return;
}
//TODO : remove previous rule (=emptying lists)
survivalRules.clear();
birthRules.clear();
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];
for (int i = 0; i < LIFE_TYPE_NUM; i++) {
String survivalLine = lines.get(i);
String[] survivalParts = survivalLine.split(";");
ArrayList<Integer> survivalValues = new ArrayList<>();
for (String part : survivalParts) {
String[] survivalElements = part.split(",");
for (String elem : survivalElements) {
if (!elem.isEmpty()) { // Skip empty elements
int value = Integer.parseInt(elem);
//TODO : add value to possible survive values
survivalValues.add(value);
}
String[] birthElements = birthLine.split(";");
for(int x=0; x<birthElements.length;x++) {
String elem = birthElements[x];
}
}
survivalRules.add(survivalValues);
}
for (int i = LIFE_TYPE_NUM; i < LIFE_TYPE_NUM * 2; i++) {
String birthLine = lines.get(i);
String[] birthParts = birthLine.split(";");
ArrayList<Integer> birthValues = new ArrayList<>();
for (String part : birthParts) {
String[] birthElements = part.split(",");
for (String elem : birthElements) {
if (!elem.isEmpty()) { // Skip empty elements
int value = Integer.parseInt(elem);
//TODO : add value to possible birth values
birthValues.add(value);
}
}
}
birthRules.add(birthValues);
}
}
}
}
public ArrayList<String> getAgentsSave() {
//TODO : Same idea as the other save method, but for agents
return null;
ArrayList<String> saveData = new ArrayList<>();
for (Agent agent : agents) {
saveData.add(agent.getClass().getSimpleName() + "," + agent.getX() + "," + agent.getY());
}
return saveData;
}
public void loadAgents(ArrayList<String> stringArray) {
//TODO : Same idea as other load methods, but for agent list
agents.clear();
for (String line : stringArray) {
String[] parts = line.split(",");
String type = parts[0];
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
if (type.equals("Virus")) {
agents.add(new Virus(x, y));
}
}
}
/**
@ -324,9 +448,11 @@ public class Simulator extends Thread {
* @return String representation of click action
*/
public String clickActionName() {
// TODO : initially return "sheep" or "cell"
// depending on clickActionFlag
return "";
if (clickActionFlag.equals("Cells")) {
return "Cells";
} else {
return "Virus";
}
}
}

View File

@ -0,0 +1,39 @@
package backend;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
public class Virus extends Agent {
Random rand;
Virus(int x, int y){
super(x, y, Color.red);
rand = new Random();
}
public boolean liveTurn(ArrayList<Agent> neighbors, Simulator world) {
if(world.getCell(x, y) > 0 && world.getCell(x, y) < 4) {
world.setCell(x, y, 4); // Infect cell
}
this.moveRandom();
return true;
}
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;
}
}
}

View File

@ -72,6 +72,12 @@ public class JPanelDraw extends JPanel {
if(cellContent == 3) {
g.setColor(Color.cyan);
}
if (cellContent == 4) {
g.setColor(Color.red);
}
if (cellContent >= -3 && cellContent < 0) {
g.setColor(Color.red);
}
g.fillRect(
(int) Math.round(x*cellWidth),
(int) Math.round(y*cellHeight),