diff --git a/scenariovirus.txt b/scenariovirus.txt new file mode 100644 index 0000000000000000000000000000000000000000..d43e533bb6bbb2ca17d9d80a418b2e6f13b7b03b --- /dev/null +++ b/scenariovirus.txt @@ -0,0 +1,15 @@ +Patients : +- Interactions et mouvement : Se déplacent et interagissent socialement, augmentant ainsi les chances de transmission du virus. Certains peuvent être asymptomatiques. +- Réaction en cas de maladie : S'ils se rendent compte qu'ils sont malades, ils cherchent un docteur pour se faire soigner. Sinon, ils continuent leur vie normalement, pouvant transmettre le virus sans le savoir. + + +Virus : +- Mouvement et infection : Entité unique sur le plateau qui se déplace aléatoirement, infectant les patients lorsqu'il passe à proximité. +- Le virus infecte les patients lorsqu'il passe à proximité. +- Évolue tous les 30 tours pour donner un nouveau variant, lorsqu'un nouveau variant est détecté, les médecins mettent plus de temps à le soigner au début + + +Docteurs : +- Traitement des patients : Traitent les patients malades qui se trouvent dans des cases adjacentes à leur position. +- Statique : Ne se déplacent pas entre les tours, ce qui nécessite que les patients viennent à eux pour être soignés. + diff --git a/src/main/java/app/SimulatorApplication.java b/src/main/java/app/SimulatorApplication.java index a2d7b95bdd1335ff818e23b64d4d5cf1b574323e..10fa4af1b221ac2dd223eb45bd7fbe5a8b97fa48 100644 --- a/src/main/java/app/SimulatorApplication.java +++ b/src/main/java/app/SimulatorApplication.java @@ -18,10 +18,10 @@ public class SimulatorApplication extends javafx.application.Application { private static final int BOX_WIDTH = 15; private static final int BOX_HEIGHT = 15; public static final int INITIAL_FIRE_COUNT = 8; - public static final int INITIAL_FIREFIGHTER_COUNT = 6; + public static final int INITIAL_FIREFIGHTER_COUNT = 12; public static final int INITIAL_MOTORIZED_FIREFIGHTER_COUNT = 8; - public static final int INITIAL_CLOUD_COUNT = 20; - public static final int INITIAL_MOUNTAIN_COUNT= 20; + public static final int INITIAL_CLOUD_COUNT = 8; + public static final int INITIAL_MOUNTAIN_COUNT= 6; public static final int TURNS_FOR_SPAWNING_AIRTANKER = 10; private Stage primaryStage; diff --git a/src/main/java/controller/Controller.java b/src/main/java/controller/Controller.java index 1cf89653fbc8e469e235f1f8a9ba3fddc836b6b0..97a8c819e04f4036c399b435a844740cfc98727f 100644 --- a/src/main/java/controller/Controller.java +++ b/src/main/java/controller/Controller.java @@ -20,7 +20,10 @@ import javafx.scene.control.ToggleGroup; import javafx.util.Duration; import javafx.util.Pair; import model.Board; +import model.EmptySquare; +import model.Entity; import model.EntityFactory; +import model.Model; import model.Square; import model.firefighterscenario.Cloud; import model.firefighterscenario.Fire; @@ -50,6 +53,7 @@ public class Controller { private Grid<ViewElement> grid; private Timeline timeline; private Board<Square> board; + private Model model; @FXML private void initialize() { @@ -63,12 +67,13 @@ public class Controller { pauseToggleButton.setSelected(true); } - private void setModel(Board<Square> board) { - this.board = requireNonNull(board, "board is null"); + private void setModel(Model model) { + this.board = requireNonNull(model.getBoard(), "board is null"); + this.model = model; } private void updateBoard() { - List<Position> updatedPositions = board.updateToNextGeneration(); + List<Position> updatedPositions = model.updateToNextGeneration(); List<Pair<Position, ViewElement>> updatedSquares = new ArrayList<>(); for (Position updatedPosition : updatedPositions) { Square squareState = board.getStates(updatedPosition); @@ -91,6 +96,12 @@ public class Controller { } private ViewElement getViewElement(Square square) { + if (!square.getEntities().isEmpty()) { + for (Entity entity : square.getEntities()) { + if(entity instanceof EmptySquare)continue; + return entity.getViewElement(); + } + } return new ViewElement(square.getViewColor()); } @@ -121,6 +132,7 @@ public class Controller { public void restartButtonAction() { this.pause(); board.reset(); + System.gc(); pauseToggleButton.setSelected(true); repaintGrid(); } @@ -128,21 +140,33 @@ public class Controller { public void initialize(int squareWidth, int squareHeight, int columnCount, int rowCount, int initialFireCount, int initialFirefighterCount, int initialMotorizedFirefightersCount, int initialcloudCount, int initialmountaincount, int turnsForSpawningAirTanker) { grid.setDimensions(columnCount, rowCount, squareWidth, squareHeight); - Board<Square> model = new FireFighterScenario(columnCount, rowCount); + Map<EntityFactory, Integer> entityCounts = new HashMap<EntityFactory, Integer>(); - + entityCounts.put((pos, b) -> new Fire(pos), initialFireCount); entityCounts.put((pos, b) -> new FireFighter(pos,b), initialFirefighterCount); entityCounts.put((pos, b) -> new MotorizedFireFighter(pos, b), initialMotorizedFirefightersCount); entityCounts.put((pos, b) -> new Cloud(pos, b), initialcloudCount); entityCounts.put((pos, b) -> new Mountain(pos), initialmountaincount); entityCounts.put((pos, b) -> new Rockery(pos), 3); - - model.placeInitialEntities(entityCounts); + + + /* + entityCounts.put((pos, b) -> new Rock(pos), 10); + entityCounts.put((pos, b) -> new Cisor(pos), 10); + entityCounts.put((pos, b) -> new Paper(pos), 10); + */ + + /* + entityCounts.put((pos, b) -> new Patient(pos), 70); + entityCounts.put((pos, b) -> new Virus(pos), 6); + entityCounts.put((pos, b) -> new Doctor(pos), 3); + */ + Model model = new FireFighterScenario(columnCount, rowCount, entityCounts); this.setModel(model); repaintGrid(); } - + public void oneStepButtonAction() { this.pause(); updateBoard(); diff --git a/src/main/java/model/Board.java b/src/main/java/model/Board.java index 6d51304610a1f242df6974939c6a4b92a5841c52..6fc78ddca79a959bf915ed614020208bd9016cc4 100644 --- a/src/main/java/model/Board.java +++ b/src/main/java/model/Board.java @@ -43,15 +43,6 @@ public interface Board<S> { */ int columnCount(); - /** - * Update the board to its next generation or state. This method may modify the - * internal state of the board and return a list of positions that have changed - * during the update. - * - * @return A list of positions that have changed during the update. - */ - List<Position> updateToNextGeneration(); - /** * Reset the board to its initial state. */ @@ -73,7 +64,7 @@ public interface Board<S> { public void clearCaseFrom(Entity entity, Position position); - public Position getNearestEntity(Position fromPos, Class<?> entityType); + public Position getNearestEntity(Position fromPos, Class<?> entityType, List<Entity> exclusionList); public boolean doesSquareContainEntity(Position squarePos, Class<?> entityType); diff --git a/src/main/java/model/EmptySquare.java b/src/main/java/model/EmptySquare.java index a196fe418145e94a1cf48bca393158abe603cf95..e14e38d7c9164b0f00a3146efd551e1bf7ded8c7 100644 --- a/src/main/java/model/EmptySquare.java +++ b/src/main/java/model/EmptySquare.java @@ -4,7 +4,9 @@ import java.util.ArrayList; import java.util.List; import javafx.scene.paint.Color; +import model.firefighterscenario.Cloud; import util.Position; +import view.ViewElement; public class EmptySquare implements Entity { @@ -12,6 +14,15 @@ public class EmptySquare implements Entity { private final Color viewColor = Color.WHITE; private int age; private final int priotity = -1; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/img.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public EmptySquare(Position p) { this.position = p; @@ -61,4 +72,9 @@ public class EmptySquare implements Entity { public int getPriority(){ return this.priotity; } + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } diff --git a/src/main/java/model/Entity.java b/src/main/java/model/Entity.java index 3270ae89da793de0e332c5802f70d4f60b88c933..2b53e3ae3319c167dfee1d7843b73d3fa312c4bf 100644 --- a/src/main/java/model/Entity.java +++ b/src/main/java/model/Entity.java @@ -1,9 +1,9 @@ package model; - import java.util.List; import javafx.scene.paint.Color; import util.Position; +import view.ViewElement; public interface Entity { @@ -21,4 +21,5 @@ public interface Entity { public void incrementAge(); public Color getViewColor(); public int getPriority(); + public ViewElement getViewElement(); } diff --git a/src/main/java/model/EntityNotFoundException.java b/src/main/java/model/EntityNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..9902ad982952d8d34e0ceb55266b8782b9901a98 --- /dev/null +++ b/src/main/java/model/EntityNotFoundException.java @@ -0,0 +1,7 @@ +package model; + +class EntityNotFoundException extends Exception { + public EntityNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/model/EntityScenario.java b/src/main/java/model/EntityScenario.java deleted file mode 100644 index fdbedaac570216fd1e5fb9626d1f0fb78b17c1b7..0000000000000000000000000000000000000000 --- a/src/main/java/model/EntityScenario.java +++ /dev/null @@ -1,15 +0,0 @@ -package model; - -import util.Matrix; -import util.Position; - -public abstract class EntityScenario implements Scenario{ - public void initScenario(Matrix<Square> matrix){ - for(int x = 0; x < matrix.getRows(); x++){ - for(int y = 0; y < matrix.getColumns(); y++){ - Square s = new Square(new Position(x, y), new EmptySquare(new Position(x,y))); - matrix.set(x,y, s); - } - } - } -} diff --git a/src/main/java/model/EntitySpawner.java b/src/main/java/model/EntitySpawner.java index c8f0de6aaa1e51b620125129ff323268c92f6d96..bd6fa6e39196e6ffd798760bc8546e96887694f2 100644 --- a/src/main/java/model/EntitySpawner.java +++ b/src/main/java/model/EntitySpawner.java @@ -12,6 +12,7 @@ import java.util.Set; import util.Direction; import util.Position; +import util.PositionUtil; public class EntitySpawner { private final Board<Square> board; @@ -120,7 +121,7 @@ public class EntitySpawner { int roadLength = 1; // Déterminer la direction interdite (opposée à la direction initiale) - Direction forbiddenDirection = getOppositeDirection(initialDirection); + Direction forbiddenDirection = PositionUtil.getOppositeDirection(initialDirection); // Initialiser la direction courante Direction currentDirection = initialDirection; @@ -163,7 +164,7 @@ public class EntitySpawner { // Mettre à jour la direction courante currentDirection = newDirection; - forbiddenDirection = getOppositeDirection(currentDirection); + forbiddenDirection = PositionUtil.getOppositeDirection(currentDirection); stepsInCurrentDirection = 0; continue; // Recommencer avec la nouvelle direction } else { @@ -185,7 +186,7 @@ public class EntitySpawner { // Mettre à jour la direction courante currentDirection = newDirection; - forbiddenDirection = getOppositeDirection(currentDirection); + forbiddenDirection = PositionUtil.getOppositeDirection(currentDirection); stepsInCurrentDirection = 0; } } @@ -249,15 +250,7 @@ public class EntitySpawner { } } - private static Direction getOppositeDirection(Direction direction) { - switch (direction) { - case NORTH: return Direction.SOUTH; - case SOUTH: return Direction.NORTH; - case EAST: return Direction.WEST; - case WEST: return Direction.EAST; - default: throw new IllegalArgumentException("Direction non supportée : " + direction); - } - } + diff --git a/src/main/java/model/Model.java b/src/main/java/model/Model.java new file mode 100644 index 0000000000000000000000000000000000000000..64bd75a7a9d95ae0a82f2fdfc0cc90e7034dec88 --- /dev/null +++ b/src/main/java/model/Model.java @@ -0,0 +1,10 @@ +package model; + +import java.util.List; + +import util.Position; + +public interface Model { + public List<Position> updateToNextGeneration(); + public Board<Square> getBoard(); +} diff --git a/src/main/java/model/firefighterscenario/Road.java b/src/main/java/model/Road.java similarity index 67% rename from src/main/java/model/firefighterscenario/Road.java rename to src/main/java/model/Road.java index fa90dc7d64b4995d5271810209395ab11c45547c..e208d99a8f20bfbec11d75ae327f055f06472099 100644 --- a/src/main/java/model/firefighterscenario/Road.java +++ b/src/main/java/model/Road.java @@ -1,18 +1,26 @@ -package model.firefighterscenario; +package model; import java.util.List; import javafx.scene.paint.Color; -import model.Board; -import model.Entity; -import model.Square; +import model.firefighterscenario.Cloud; import util.Position; +import view.ViewElement; public class Road implements Entity{ private int age; private final int PRIORITY = 0; private final Color VIEW_COLOR = Color.BLACK; private Position position; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/route.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public Road(Position position){ this.position = position; @@ -56,5 +64,10 @@ public class Road implements Entity{ public int getPriority() { return this.PRIORITY; } - + + @Override + public ViewElement getViewElement(){ + return new ViewElement(cloudImage); + } + } diff --git a/src/main/java/model/Scenario.java b/src/main/java/model/Scenario.java index 03d319a9325df2547e011ba58d5243e34f116b13..912f7fbb89abb070eab0b2c42cd202b5727c60f2 100644 --- a/src/main/java/model/Scenario.java +++ b/src/main/java/model/Scenario.java @@ -1,8 +1,165 @@ package model; + +import java.util.List; +import java.util.Map; + +import app.SimulatorApplication; import util.Matrix; +import util.Position; +import util.PositionUtil; + +public class Scenario implements Board<Square>{ + + private Matrix<Square> matrix; + protected int step; + protected int turnsToSpawnAirTanker; + + protected Map<EntityFactory, Integer> initialMap; + + public Scenario(int columns, int rows, Map<EntityFactory, Integer> initialMap) { + this.matrix = new Matrix<Square>(columns, rows); + initScenario(matrix); + this.turnsToSpawnAirTanker = SimulatorApplication.TURNS_FOR_SPAWNING_AIRTANKER; + this.step = 0; + this.initialMap = initialMap; + placeInitialEntities(initialMap); + } + public void initScenario(Matrix<Square> matrix){ + for(int x = 0; x < matrix.getRows(); x++){ + for(int y = 0; y < matrix.getColumns(); y++){ + Square s = new Square(new Position(x, y), new EmptySquare(new Position(x,y))); + matrix.set(x,y, s); + } + } +} + protected Matrix<Square> getMatrix(){ + return this.matrix; + } + + public void placeInitialEntities(Map<EntityFactory, Integer> initialMap) { + EntitySpawner spawner = new EntitySpawner(this); + spawner.spawnEntities(initialMap); + + } + + public Square getStates(Position position) { + if (position.x() > matrix.size() || position.y() > matrix.size()) { + throw new IllegalArgumentException( + "The position x:" + position.x() + " y:" + position.y() + " is out of the board."); + } + return matrix.get(position.x(), position.y()); + } + + public void setSquare(Square square) { + Position position = square.getPosition(); + if (!(getStates(position).isEmpty())) { + return; + } + if (doesPositionExist(position)) { + matrix.set(position.x(), position.y(), square); + } + } + + public void setSquare(Square square, boolean replaceStates) { + Position position = square.getPosition(); + if (!(getStates(position).isEmpty()) && !replaceStates) { + return; + } + matrix.set(position.x(), position.y(), square); + } + + public void addEntityAtSquare(Entity entity, Position position) { + if (doesPositionExist(position)) { + matrix.get(position.x(), position.y()).addEntity(entity); + } + } + + public int rowCount() { + return matrix.getRows(); + } + + public int columnCount() { + return matrix.getColumns(); + } + + @Override + public void clearCaseFrom(Entity entity, Position position) { + if(!matrix.get(position.x(), position.y()).getEntities().removeIf(element -> element.equals(entity))){ + for(Entity e : getStates(position).getEntities()){ + System.out.println(e); + } + } + } + + public Position getNearestEntity(Position fromPos, Class<?> entityType, List<Entity> exclusionList) { + int rows = matrix.getRows(); + int cols = matrix.getColumns(); + if(exclusionList == null){ + exclusionList = List.of(); + } + // Définir la distance maximale possible + int maxDistance = rows + cols; + // Parcourir les distances croissantes à partir de 1 + for (int distance = 1; distance < maxDistance; distance++) { + List<Position> positionsAtDistance = PositionUtil.getPositionsAtManhattanDistance(fromPos, distance, rows, cols); + + for (Position currentPos : positionsAtDistance) { + if(isPositionEmpty(currentPos))continue; + Square currentSquare = matrix.get(currentPos.x(), currentPos.y()); + for (Entity currentEntity : currentSquare.getEntities()) { + if (entityType.isInstance(currentEntity) && exclusionList != null && !exclusionList.contains(currentEntity)) { + // Vérifie si l'entité actuelle n'est pas dans la liste des exclusions + // Dès qu'une entité éligible est trouvée à cette distance, elle est la plus proche possible + return currentPos; + } + } + } + } + return null; // Retourne null si aucune entité éligible n'est trouvée +} + + + public void reset() { + step = 0; + matrix.clear(); + initScenario(matrix); + placeInitialEntities(initialMap); + } + + public int stepNumber() { + return this.step; + } + + @Override + public boolean doesPositionExist(Position position) { + return matrix.validateIndex(position); + } + + @Override + public int getStepNumber() { + return step; + } + + @Override + public boolean doesSquareContainEntity(Position squarePos, Class<?> entityType) { + return getStates(squarePos).getEntities().stream().anyMatch(entityType::isInstance); + } + + @Override + public boolean isPositionEmpty(Position position) { + return getStates(position).isEmpty(); + } -public interface Scenario { - public void initScenario(Matrix<Square> matrix); + @Override + public boolean isPositionFree(Position position, int priority) { + List<Entity> entities = matrix.get(position.x(), position.y()).getEntities(); + for (Entity e : entities) { + if (e.getPriority() == priority) { + return false; + } + } + return true; + } -} \ No newline at end of file +} diff --git a/src/main/java/model/doctorviruspatient/Doctor.java b/src/main/java/model/doctorviruspatient/Doctor.java new file mode 100644 index 0000000000000000000000000000000000000000..cb2d809abc762d4db9990b7d15f2c90d15e1b390 --- /dev/null +++ b/src/main/java/model/doctorviruspatient/Doctor.java @@ -0,0 +1,172 @@ +package model.doctorviruspatient; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Doctor implements Entity { + private final int priority = 1; + private Position position; + private int age; + private final Color viewColor = Color.RED; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/virus/docteur.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Statique car les médecins partagent les connaissances et les recherches + private static List<Integer> knownVirusVariant = new ArrayList<Integer>(); + private static Map<Integer, Double> currentResearch = new HashMap<>(); // Map<variantId, % de recherche> + + public Doctor(Position p) { + this.position = p; + } + + public Doctor(Position p, int age) { + this.position = p; + this.age = age; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + // Mettre à jour les recherches en cours + updateCurrentResearch(); + + // Interagir avec les positions adjacentes + interactWithAdjacentPositions(PositionUtil.generateAllAdjacentPositions(position, board), board); + + return List.of(); + } + + /** + * Met à jour toutes les recherches en cours en augmentant leur avancement de x%. + * Si une recherche atteint ou dépasse 100%, elle est terminée. + */ + private void updateCurrentResearch() { + List<Integer> completedResearch = new ArrayList<>(); + + for (Map.Entry<Integer, Double> entry : currentResearch.entrySet()) { + int variantId = entry.getKey(); + double progress = entry.getValue() + 2.0; + if (progress >= 100.0) { + progress = 100.0; + completedResearch.add(variantId); + } + currentResearch.put(variantId, progress); + } + + // Traiter les recherches complétées + for (int variantId : completedResearch) { + currentResearch.remove(variantId); + knownVirusVariant.add(variantId); + System.out.println("Recherche terminée pour le variant ID: " + variantId); + } + } + + private List<Position> interactWithAdjacentPositions(List<Position> adjacentPositions, Board<Square> board) { + List<Position> result = new ArrayList<>(); + for (Position p : adjacentPositions) { + if (board.doesSquareContainEntity(p, Patient.class)) { + handleEncounterWithPatient(p, board); + } + } + return result; + } + + private void handleEncounterWithPatient(Position p, Board<Square> board) { + if (board.doesSquareContainEntity(p, Patient.class)) { + Patient patient = (Patient) board.getStates(p).getEntities().stream() + .filter(e -> e instanceof Patient) + .findFirst() + .orElse(null); + if (patient != null && patient.isInfected()) { + Virus virus = patient.getVirus(); + if (virus != null) { + int variantId = virus.getVariantId(); + if (knownVirusVariant.contains(variantId)) { + patient.cure(); + } else { + // Si la variante n'est pas connue et pas en cours de recherche, l'ajouter à la recherche + if (!currentResearch.containsKey(variantId)) { + currentResearch.put(variantId, 0.0); + System.out.println("Nouvelle variante détectée! Variant ID: " + variantId + ". Recherche commencée."); + } + } + } + } + } + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Doctor) { + Doctor other = (Doctor) obj; + return this.position.equals(other.getPosition()); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hash(position); + } + + @Override + public ViewElement getViewElement() { + return new ViewElement (cloudImage); + } + + +} diff --git a/src/main/java/model/doctorviruspatient/DoctorVirusPatientScenario.java b/src/main/java/model/doctorviruspatient/DoctorVirusPatientScenario.java new file mode 100644 index 0000000000000000000000000000000000000000..16e82608ee3584dc79aee63cc21369615de748dd --- /dev/null +++ b/src/main/java/model/doctorviruspatient/DoctorVirusPatientScenario.java @@ -0,0 +1,60 @@ +package model.doctorviruspatient; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import model.Board; +import model.Entity; +import model.EntityFactory; +import model.Model; +import model.Scenario; +import model.Square; +import util.Position; + + + +public class DoctorVirusPatientScenario extends Scenario implements Model{ + public DoctorVirusPatientScenario(int columns, int rows, Map<EntityFactory, Integer> initialMap) { + super(columns, rows, initialMap); + } + + public List<Position> updateToNextGeneration() { + ArrayList<Position> changedPositions = new ArrayList<>(); + Iterator<Square> iterator = getMatrix().iterator(); + while (iterator.hasNext()) { + Square s = iterator.next(); + if (s.isEmpty()) + continue; + if (s.getMaxAge() == 0) { + s.incrementAllAges(); + continue; + } + if(s.getMaxAge()>stepNumber()+1){ + continue; + } + List<Entity> entities = new ArrayList<>(s.getEntities()); + for (Entity e : entities) { + e.incrementAge(); + changedPositions.addAll(e.nextTurn(this)); + } + } + + // Increment the step counter + this.step = this.step + 1; + return changedPositions; + } + + + + @Override + public Board<Square> getBoard() { + return this; + } + + + + + +} diff --git a/src/main/java/model/doctorviruspatient/Patient.java b/src/main/java/model/doctorviruspatient/Patient.java new file mode 100644 index 0000000000000000000000000000000000000000..8e1387910f29240fffba163eec35593673304747 --- /dev/null +++ b/src/main/java/model/doctorviruspatient/Patient.java @@ -0,0 +1,358 @@ +package model.doctorviruspatient; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Random; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.PathGenerator; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Patient implements Entity { + private final int priority = 1; + private Position position; + private int age; + private final Color viewColor = Color.BLUE; + private Virus carriedVirus; + private List<Entity> visitedPatients; + private static int patientsCount = 0; + private int patientID; + private Position ennemy; + private boolean isAsymptomatic; + private boolean wandering; + + + + private static javafx.scene.image.Image healthyImage; + private static javafx.scene.image.Image infectedImage; + + static { + try { + healthyImage = new javafx.scene.image.Image(Patient.class.getResource("/view/icons/virus/humain.png").toExternalForm()); + infectedImage = new javafx.scene.image.Image(Patient.class.getResource("/view/icons/virus/patient.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + // Attributs pour le chemin + private List<Position> path; + private int pathIndex; + private static final int MAX_STEPS_IN_DIRECTION = 5; + private static final int MINIMUM_ROAD_LENGTH = 10; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/virus/humain.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Patient(Position p) { + this.wandering = true; + patientID = patientsCount; + patientsCount += 1; + this.visitedPatients = new ArrayList<>(); + this.position = p; + Random r = new Random(); + int randomNumber = r.nextInt(10); + this.isAsymptomatic = randomNumber == 1; + // Initialiser le chemin + this.path = new ArrayList<>(); + this.pathIndex = 0; + } + + public Patient(Position p, int age) { + this.wandering = true; + patientID = patientsCount; + patientsCount += 1; + this.visitedPatients = new ArrayList<>(); + this.position = p; + this.age = age; + Random r = new Random(); + int randomNumber = r.nextInt(10); + this.isAsymptomatic = randomNumber == 1; + // Initialiser le chemin + this.path = new ArrayList<>(); + this.pathIndex = 0; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + if (isInfected() && !isAsymptomatic) { + return moveToDoctor(board); + } + updateWanderingStatus(board); + + if (wandering) { + return performWandering(board); + } + + resetVisitedPatientsIfNecessary(); + + Position target = determineTarget(board); + + if (target == null) { + visitedPatients.clear(); + return List.of(); + } + + Position nextPos = determineNextPosition(target, board); + + if (nextPos != null && board.doesPositionExist(nextPos)) { + + List<Position> adjacentPositions = PositionUtil.generateAllAdjacentPositions(nextPos, board); + List<Position> result = interactWithAdjacentPositions(adjacentPositions, board); + result.addAll(moveToPosition(nextPos, board)); + result.addAll(adjacentPositions); + result.add(position); + return result; + } + + return List.of(); + } + + private void updateWanderingStatus(Board<Square> board) { + if (board.getStepNumber() % 8 == 0) { + wandering = false; + // Réinitialiser le chemin lorsque le patient arrête d'errer + this.path.clear(); + this.pathIndex = 0; + } + } + + private List<Position> moveToDoctor(Board<Square> board) { + for (Position p : PositionUtil.generateAllAdjacentPositions(position, board)) { + if (!board.doesPositionExist(p)) continue; + if (board.doesSquareContainEntity(p, Doctor.class)) return List.of(); + } + Position nearestDoctor = board.getNearestEntity(position, Doctor.class, null); + Position nextPos = PositionUtil.getNextPositionTowards(position, nearestDoctor, board); + if (nextPos == null) return List.of(); + + List<Position> changedPositions = new ArrayList<>(); + changedPositions.addAll(moveToPosition(nextPos, board)); + return changedPositions; + } + + private List<Position> performWandering(Board<Square> board) { + if (path == null || path.isEmpty() || pathIndex >= path.size()) { + generateNewPath(board); + if (path.isEmpty()) { + return List.of(); + } + } + + Position nextPosition = path.get(pathIndex); + + if (board.doesPositionExist(nextPosition) && board.isPositionFree(nextPosition, priority)) { + List<Position> changedPositions = moveSelfOnBoard(nextPosition, board); + pathIndex++; + return changedPositions; + } else { + // Si la position n'est pas libre ou n'existe pas, générer un nouveau chemin + generateNewPath(board); + return List.of(); + } + } + + private void generateNewPath(Board<Square> board) { + PathGenerator pathGenerator = new PathGenerator(board, position, MAX_STEPS_IN_DIRECTION, MINIMUM_ROAD_LENGTH); + this.path = pathGenerator.generate(); + // Supprimer la position actuelle du chemin si elle est présente + if (!path.isEmpty() && path.get(0).equals(position)) { + path.remove(0); + } + this.pathIndex = 0; + } + + private void resetVisitedPatientsIfNecessary() { + if (visitedPatients.size() - 1 >= patientsCount) { + visitedPatients.clear(); + } + } + + private Position determineTarget(Board<Square> board) { + return board.getNearestEntity(position, Patient.class, getVisitedPatients()); + } + + private Position determineNextPosition(Position target, Board<Square> board) { + int enemyDistance = PositionUtil.getManhattanDistance(target, position); + + if (ennemy != null && enemyDistance < 2) { + return PositionUtil.getNextPositionAwayFrom(position, target, board); + } else if (target != null) { + return PositionUtil.getNextPositionTowards(position, target, board); + } + return null; + } + + private List<Position> moveToPosition(Position nextPos, Board<Square> board) { + List<Position> changedPosition = new ArrayList<>(); + if (!board.isPositionFree(nextPos, priority)) { + nextPos = findAlternativePosition(nextPos, board); + } + + if (nextPos != null) { + changedPosition.addAll(moveSelfOnBoard(nextPos, board)); + } + + return changedPosition; + } + + private Position findAlternativePosition(Position currentPos, Board<Square> board) { + List<Position> adjacentPositions = PositionUtil.generateAdjacentPositions(position, board); + for (Position p : adjacentPositions) { + if (ennemy != null) { + Position awayPos = PositionUtil.getNextPositionAwayFrom(p, ennemy, board); + if (p.equals(awayPos)) { + continue; + } + } + if (board.isPositionFree(p, priority)) { + return p; + } + } + return null; + } + + private List<Position> moveSelfOnBoard(Position newPosition, Board<Square> board) { + if(!board.isPositionFree(newPosition, priority))return List.of(); + Position oldPosition = new Position(this.position.x(), this.position.y()); + board.clearCaseFrom(this, oldPosition); + board.addEntityAtSquare(this, newPosition); + this.position = newPosition; + return List.of(oldPosition, this.position); + } + + private List<Position> interactWithAdjacentPositions(List<Position> adjacentPositions, Board<Square> board) { + List<Position> result = new ArrayList<>(); + for (Position p : adjacentPositions) { + if (board.doesSquareContainEntity(p, Patient.class)) { + handleEncounterWithPatient(p, board); + if (isInfected()) { + result.addAll(adjacentPositions); + } + } + } + return result; + } + + private void handleEncounterWithPatient(Position p, Board<Square> board) { + this.wandering = true; + // Réinitialiser le chemin lorsqu'un patient est rencontré + this.path.clear(); + this.pathIndex = 0; + Patient patient = (Patient) board.getStates(p).getEntities().stream() + .filter(entity -> entity instanceof Patient) + .findFirst() + .orElse(null); + if (isInfected()) { + patient.infect(carriedVirus); + } + if (patient != null) { + this.ennemy = patient.getPosition(); + visitedPatients.add(patient); + } + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return isInfected() ? Color.CYAN : this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + public boolean isInfected() { + return this.carriedVirus != null; + } + + public void infect(Virus virus) { + if (this.carriedVirus != null) return; + this.carriedVirus = virus; + } + + public Virus getVirus() { + return this.carriedVirus; + } + + public List<Entity> getVisitedPatients() { + return this.visitedPatients; + } + + public boolean hasVisited(Patient patient) { + return this.getVisitedPatients().contains(patient); + } + + public int getPatientId() { + return this.patientID; + } + + public void cure() { + if (this.carriedVirus.tryToKill()) { + this.carriedVirus = null; + } + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Patient) { + Patient other = (Patient) obj; + return this.patientID == other.getPatientId(); + } else { + return false; + } + + } + + @Override + public int hashCode() { + return Objects.hash(patientID); + } + + @Override + public ViewElement getViewElement() { + return isInfected() ? new ViewElement(infectedImage) : new ViewElement(healthyImage); + } + + +} diff --git a/src/main/java/model/doctorviruspatient/Virus.java b/src/main/java/model/doctorviruspatient/Virus.java new file mode 100644 index 0000000000000000000000000000000000000000..632b4258afba963d57cd1fc1d06262ae36f96e0e --- /dev/null +++ b/src/main/java/model/doctorviruspatient/Virus.java @@ -0,0 +1,167 @@ +package model.doctorviruspatient; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.PathGenerator; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Virus implements Entity { + private final int priority = 2; + private Position position; + private int age; + private final Color viewColor = Color.LIMEGREEN; + private List<Position> path; + private int pathIndex; + private static final int MAX_STEPS_IN_DIRECTION = 5; + private static final int MINIMUM_ROAD_LENGTH = 10; + private int health; + private int variantId; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/virus/virus.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Virus(Position p) { + this.variantId = 0; + this.health = 50; + this.position = p; + this.path = new ArrayList<>(); + this.age = 0; + this.pathIndex = 0; + } + + public Virus(Position p, int age) { + this.health = 8; + this.position = p; + this.age = age; + this.path = new ArrayList<>(); + this.pathIndex = 0; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + if(board.getStepNumber() % 100 == 0){ + evolve(); + } + // Génère un nouveau chemin si nécessaire + if (path == null || path.isEmpty() || pathIndex >= path.size()) { + generateNewPath(board); + if (path.isEmpty()) { + return List.of(); + } + } + List<Position> adjacentPosition = PositionUtil.generateAllAdjacentPositions(position, board); + for(Position p : adjacentPosition){ + if(board.doesSquareContainEntity(p, Patient.class)){ + Patient patient = (Patient) board.getStates(p).getEntities().stream().filter(e -> e instanceof Patient).findFirst().get(); + patient.infect(this); + } + } + // Se déplace vers la prochaine position du chemin + Position nextPosition = path.get(pathIndex); + if (board.doesPositionExist(nextPosition)) { + // Vérifier si la position est libre + if (board.isPositionFree(nextPosition, priority)) { + Position oldPosition = position; + position = nextPosition; + board.clearCaseFrom(this, oldPosition); + board.addEntityAtSquare(this, position); + pathIndex = pathIndex + 1; + return List.of(oldPosition, position); + } else { + // Si la position n'est pas libre, génère un nouveau chemin + generateNewPath(board); + return List.of(); + } + } else { + // Si la prochaine position n'existe pas, génère un nouveau chemin + generateNewPath(board); + return List.of(); + } + } + + private void generateNewPath(Board<Square> board) { + PathGenerator pathGenerator = new PathGenerator(board, position, MAX_STEPS_IN_DIRECTION, MINIMUM_ROAD_LENGTH); + this.path = pathGenerator.generate(); + // Supprime la position actuelle du chemin si elle est présente au début + if (!path.isEmpty() && path.get(0).equals(position)) { + path.remove(0); + } + this.pathIndex = 0; // Réinitialise l'index du chemin + } + + // Les autres méthodes restent inchangées + private void evolve(){ + this.variantId++; + Random r = new Random(); + this.health = r.nextInt(100); + } + + public int getVariantId(){ + return this.variantId; + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + public boolean tryToKill(){ + if(health <= 0){ + return true; + } + health--; + return false; + } + + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } + +} diff --git a/src/main/java/model/firefighterscenario/AirTanker.java b/src/main/java/model/firefighterscenario/AirTanker.java index a80fdb66bfae4e2c565b1406f12c8afe4e7bda70..130850ac5509eca671da995d13c77c4d07d78cfc 100644 --- a/src/main/java/model/firefighterscenario/AirTanker.java +++ b/src/main/java/model/firefighterscenario/AirTanker.java @@ -11,6 +11,7 @@ import model.Square; import util.Direction; import util.Position; import util.PositionUtil; +import view.ViewElement; public class AirTanker implements Entity{ private final Color viewColor = Color.GOLD; @@ -18,6 +19,15 @@ public class AirTanker implements Entity{ private int age; private Position position; private int priority = 3; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/avion.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public AirTanker(Position position, Board<Square> b, int age) { this.age = age; @@ -163,5 +173,8 @@ public class AirTanker implements Entity{ return Objects.hash(position, age); } - + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } diff --git a/src/main/java/model/firefighterscenario/Cloud.java b/src/main/java/model/firefighterscenario/Cloud.java index 3a587b5594531ee34f995f4840a82fdfa3bdefcb..99caef1fe965b3093cf7f4b04bb520d18193ab85 100644 --- a/src/main/java/model/firefighterscenario/Cloud.java +++ b/src/main/java/model/firefighterscenario/Cloud.java @@ -10,6 +10,7 @@ import model.Entity; import model.Square; import util.Position; import util.PositionUtil; +import view.ViewElement; public class Cloud implements Entity{ private int age; @@ -17,8 +18,15 @@ public class Cloud implements Entity{ private final Color viewColor = Color.GRAY; private final int priority = 2; - - + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/nuage.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public Cloud(Position position, Board<Square> b){ this.age = 0; this.position = position; @@ -108,5 +116,11 @@ public class Cloud implements Entity{ return this.priority; } + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } + + } diff --git a/src/main/java/model/firefighterscenario/Fire.java b/src/main/java/model/firefighterscenario/Fire.java index 0d79d7a5a8a0de817dac0f192711f547627a6a4a..05f4b9874df8e830646f680d08b8c4696ff96b61 100644 --- a/src/main/java/model/firefighterscenario/Fire.java +++ b/src/main/java/model/firefighterscenario/Fire.java @@ -8,9 +8,11 @@ import java.util.Optional; import javafx.scene.paint.Color; import model.Board; import model.Entity; +import model.Road; import model.Square; import util.Position; import util.PositionUtil; +import view.ViewElement; public class Fire implements Entity { @@ -18,6 +20,15 @@ public class Fire implements Entity { private final Color viewColor = Color.RED; private int age; private final int priority = 1; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/flamme.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public Fire(Position position) { this.position = position; @@ -132,4 +143,9 @@ public class Fire implements Entity { return Objects.hash(position, age); } + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } + } diff --git a/src/main/java/model/firefighterscenario/FireFighter.java b/src/main/java/model/firefighterscenario/FireFighter.java index 8adfeba28784f7462854258e4315bd6d0129ae07..7403803f0ea2731ded1113656b0c62b6ffd5cd00 100644 --- a/src/main/java/model/firefighterscenario/FireFighter.java +++ b/src/main/java/model/firefighterscenario/FireFighter.java @@ -10,6 +10,7 @@ import model.Entity; import model.Square; import util.Position; import util.PositionUtil; +import view.ViewElement; @@ -19,6 +20,15 @@ public class FireFighter implements Entity { private final Color viewColor = Color.BLUE; private final int priority = 1; protected List<Position> lastThreePosition; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/sapeur-pompier.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public FireFighter(Position position, Board<Square> b) { this.position = position; @@ -107,7 +117,12 @@ public class FireFighter implements Entity { List<Position> positions = new ArrayList<>(); // Find the nearest fire - Position nearestFirePos = b.getNearestEntity(position, Fire.class); + Position nearestFirePos; + try { + nearestFirePos = b.getNearestEntity(position, Fire.class, null); + } catch (Exception e) { + return List.of(); + } if (nearestFirePos != null) { // Get the next position towards the fire Position nextPos = getNextPositionTowards(position, nearestFirePos, b); @@ -220,4 +235,8 @@ public class FireFighter implements Entity { } public int getPriority(){ return this.priority;} + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } diff --git a/src/main/java/model/firefighterscenario/FireFighterScenario.java b/src/main/java/model/firefighterscenario/FireFighterScenario.java index 658e958f83b44936128658603b802895a69197a7..05167eaa47d815d2d26e8384bd36cdb59495160d 100644 --- a/src/main/java/model/firefighterscenario/FireFighterScenario.java +++ b/src/main/java/model/firefighterscenario/FireFighterScenario.java @@ -6,89 +6,26 @@ import java.util.List; import java.util.Map; import java.util.Random; -import app.SimulatorApplication; import model.Board; import model.Entity; import model.EntityFactory; -import model.EntityScenario; -import model.EntitySpawner; +import model.Model; +import model.Road; +import model.Scenario; import model.Square; -import util.Matrix; import util.PathGenerator; import util.Position; -import util.PositionUtil; -public class FireFighterScenario extends EntityScenario implements Board<Square> { - - private Matrix<Square> matrix; - private int step; - private int turnsToSpawnAirTanker; - - private Map<EntityFactory, Integer> initialMap; - - public FireFighterScenario(int columns, int rows) { - this.matrix = new Matrix<Square>(columns, rows); - initScenario(matrix); - this.turnsToSpawnAirTanker = SimulatorApplication.TURNS_FOR_SPAWNING_AIRTANKER; - this.step = 0; - } - - public void placeInitialEntities(Map<EntityFactory, Integer> entityCounts) { - EntitySpawner spawner = new EntitySpawner(this); - spawner.spawnEntities(entityCounts); +public class FireFighterScenario extends Scenario implements Model{ + public FireFighterScenario(int columns, int rows, Map<EntityFactory, Integer> initialMap) { + super(columns, rows, initialMap); generateRoads(); - this.initialMap = entityCounts; - } - - public Square getStates(Position position) { - if (position.x() > matrix.size() || position.y() > matrix.size()) { - throw new IllegalArgumentException( - "The position x:" + position.x() + " y:" + position.y() + " is out of the board."); - } - return matrix.get(position.x(), position.y()); - } - - public void setSquare(Square square) { - Position position = square.getPosition(); - if (!(getStates(position).isEmpty())) { - return; - } - if (doesPositionExist(position)) { - matrix.set(position.x(), position.y(), square); - } - } - - public void setSquare(Square square, boolean replaceStates) { - Position position = square.getPosition(); - if (!(getStates(position).isEmpty()) && !replaceStates) { - return; - } - matrix.set(position.x(), position.y(), square); - } - - public void addEntityAtSquare(Entity entity, Position position) { - if (doesPositionExist(position)) { - matrix.get(position.x(), position.y()).addEntity(entity); - } - } - - public int rowCount() { - return matrix.getRows(); - } - - public int columnCount() { - return matrix.getColumns(); - } - - @Override - public void clearCaseFrom(Entity entity, Position position) { - matrix.get(position.x(), position.y()).getEntities().removeIf(element -> element.equals(entity)); } public List<Position> updateToNextGeneration() { ArrayList<Position> changedPositions = new ArrayList<>(); - Iterator<Square> iterator = matrix.iterator(); - + Iterator<Square> iterator = getMatrix().iterator(); + List<Entity> updatedEntities = new ArrayList<Entity>(); while (iterator.hasNext()) { Square s = iterator.next(); if (s.isEmpty()) @@ -102,10 +39,12 @@ public class FireFighterScenario extends EntityScenario implements Board<Square> } List<Entity> entities = new ArrayList<>(s.getEntities()); for (Entity e : entities) { + if(updatedEntities.contains(e))continue; if (e.getAge() >= stepNumber() - 1) { continue; } e.incrementAge(); + updatedEntities.add(e); changedPositions.addAll(e.nextTurn(this)); } } @@ -115,7 +54,6 @@ public class FireFighterScenario extends EntityScenario implements Board<Square> // Check if it's time to spawn an AirTanker if (this.step % this.turnsToSpawnAirTanker == 0) { - System.out.println("apparation"); // Spawn an AirTanker at a random edge position spawnAirTanker(changedPositions); } @@ -156,74 +94,6 @@ public class FireFighterScenario extends EntityScenario implements Board<Square> changedPositions.add(position); } - public Position getNearestEntity(Position fromPos, Class<?> entityType) { - int rows = matrix.getRows(); - int cols = matrix.getColumns(); - Position nearestPosition = fromPos; - - // Définir la distance maximale possible - int maxDistance = rows + cols; - // Parcourir les distances croissantes à partir de 1 - for (int distance = 1; distance < maxDistance; distance++) { - List<Position> positionsAtDistance = PositionUtil.getPositionsAtManhattanDistance(fromPos, distance, rows, cols); - - for (Position currentPos : positionsAtDistance) { - Square currentSquare = matrix.get(currentPos.x(), currentPos.y()); - for (Entity currentEntity : currentSquare.getEntities()) { - if (entityType.isInstance(currentEntity)) { - // Dès qu'une entité est trouvée à cette distance, elle est la plus proche - // possible - return currentPos; - } - } - } - } - - return nearestPosition; // Retourne null si aucune entité n'est trouvée - } - - public void reset() { - step = 0; - matrix.clear(); - initScenario(matrix); - placeInitialEntities(initialMap); - } - - public int stepNumber() { - return this.step; - } - - @Override - public boolean doesPositionExist(Position position) { - return matrix.validateIndex(position); - } - - @Override - public int getStepNumber() { - return step; - } - - @Override - public boolean doesSquareContainEntity(Position squarePos, Class<?> entityType) { - return getStates(squarePos).getEntities().stream().anyMatch(entityType::isInstance); - } - - @Override - public boolean isPositionEmpty(Position position) { - return getStates(position).isEmpty(); - } - - @Override - public boolean isPositionFree(Position position, int priority) { - List<Entity> entities = matrix.get(position.x(), position.y()).getEntities(); - for (Entity e : entities) { - if (e.getPriority() == priority) { - return false; - } - } - return true; - } - private void generateRoads() { if(columnCount() < 10 || rowCount() < 10){ return; @@ -265,4 +135,17 @@ public class FireFighterScenario extends EntityScenario implements Board<Square> } } + @Override + public Board<Square> getBoard() { + return this; + } + + public void reset() { + step = 0; + super.getMatrix().clear(); + initScenario(super.getMatrix()); + placeInitialEntities(initialMap); + generateRoads(); + } + } diff --git a/src/main/java/model/firefighterscenario/MotorizedFireFighter.java b/src/main/java/model/firefighterscenario/MotorizedFireFighter.java index 3564d384fe27f81e247b438324e3cbf86b5b6767..904a3387a1b86b46d03ddea6b7d48eb6c5fc5da5 100644 --- a/src/main/java/model/firefighterscenario/MotorizedFireFighter.java +++ b/src/main/java/model/firefighterscenario/MotorizedFireFighter.java @@ -8,9 +8,20 @@ import model.Board; import model.Square; import util.Position; import util.PositionUtil; +import view.ViewElement; public class MotorizedFireFighter extends FireFighter { private final Color viewColor = Color.CYAN; + private static javafx.scene.image.Image cloudImage; + + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/camion.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public MotorizedFireFighter(Position position, Board<Square> b) { super(position, b); @@ -54,7 +65,12 @@ public class MotorizedFireFighter extends FireFighter { List<Position> positions = new ArrayList<>(); // Find the nearest fire - Position nearestFirePos = b.getNearestEntity(getPosition(), Fire.class); + Position nearestFirePos; + try { + nearestFirePos = b.getNearestEntity(getPosition(), Fire.class, null); + } catch (Exception e) { + return List.of(); + } if (nearestFirePos != null) { // Get the next position after moving up to two steps towards the fire Position nextPos = getNextPositionTowards(getPosition(), nearestFirePos, b, 2); @@ -109,4 +125,8 @@ public class MotorizedFireFighter extends FireFighter { lastThreePosition.add(this.getPosition()); } + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } \ No newline at end of file diff --git a/src/main/java/model/firefighterscenario/Mountain.java b/src/main/java/model/firefighterscenario/Mountain.java index e229c30a0f9d35af7e80c7c8e28a8da1bcf72db4..f8bd49c0f4a94c4c3f2deb1db85fc82670ec3f15 100644 --- a/src/main/java/model/firefighterscenario/Mountain.java +++ b/src/main/java/model/firefighterscenario/Mountain.java @@ -7,12 +7,22 @@ import model.Board; import model.Entity; import model.Square; import util.Position; +import view.ViewElement; public class Mountain implements Entity{ private final int priority = 0; Position position; private int age; private final Color viewColor = Color.CHOCOLATE; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/montagne.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public Mountain(Position p ){ this.position = p; @@ -64,4 +74,9 @@ public class Mountain implements Entity{ public int getPriority() { return this.priority; } + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } diff --git a/src/main/java/model/firefighterscenario/Rockery.java b/src/main/java/model/firefighterscenario/Rockery.java index 9b64db33ec04539cdbc3d5bd428992455292d7f9..26b0856a4089a35b61e36e4032292ea5a1c5b08f 100644 --- a/src/main/java/model/firefighterscenario/Rockery.java +++ b/src/main/java/model/firefighterscenario/Rockery.java @@ -7,6 +7,7 @@ import model.Board; import model.Entity; import model.Square; import util.Position; +import view.ViewElement; public class Rockery implements Entity{ private final int priority = 0; @@ -14,6 +15,16 @@ public class Rockery implements Entity{ private int age; private int burn; private final Color viewColor = Color.LIMEGREEN; + private static javafx.scene.image.Image cloudImage; + + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/fire/rochers.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } public Rockery(Position p ){ this.position = p; @@ -78,4 +89,9 @@ public class Rockery implements Entity{ public void resetBurn() { this.burn = 0; } + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } } diff --git a/src/main/java/model/rockpapercisor/Cisor.java b/src/main/java/model/rockpapercisor/Cisor.java new file mode 100644 index 0000000000000000000000000000000000000000..0ab152ea50dc664b7054bb91c221051570bd675d --- /dev/null +++ b/src/main/java/model/rockpapercisor/Cisor.java @@ -0,0 +1,141 @@ +package model.rockpapercisor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Cisor implements Entity { + private final int priority = 0; + Position position; + private int age; + private final Color viewColor = Color.RED; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/pfc/cis.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Cisor(Position p) { + this.position = p; + } + + public Cisor(Position p, int age) { + this.position = p; + this.age = age; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + Position target = null; + target = board.getNearestEntity(position, Paper.class, null); + + Position ennemy = null; + + ennemy = board.getNearestEntity(position, Rock.class, null); + if(ennemy == null && target == null){ + return List.of(); + } + Position nextPos = null; + // Vérifier la proximité d'un ennemi avant de choisir la direction. + if (ennemy != null && PositionUtil.getManhattanDistance(position, ennemy) < 5) { + nextPos = PositionUtil.getNextPositionAwayFrom(position, ennemy, board); + } else if(target != null){ + nextPos = PositionUtil.getNextPositionTowards(position, target, board); + } + + if (nextPos != null && board.doesPositionExist(nextPos)) { + board.addEntityAtSquare(this, nextPos); + board.clearCaseFrom(this, position); + Position oldPosition = new Position(position.x(), position.y()); + this.position = nextPos; + if (board.doesSquareContainEntity(nextPos, Paper.class)) { + List<Entity> entities = board.getStates(nextPos).getEntities(); + entities.removeIf(p -> p instanceof Paper); + } + + List<Position> result = new ArrayList<>(); + if (target != null) + result.add(target); + if (oldPosition != null) + result.add(oldPosition); + if (position != null) + result.add(position); + if (ennemy != null) + result.add(ennemy); + return result; + + } + return List.of(); + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + Cisor cisor = (Cisor) obj; + return age == cisor.age && + Objects.equals(position, cisor.position); + } + + @Override + public int hashCode() { + return Objects.hash(position, age); + } + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } + +} diff --git a/src/main/java/model/rockpapercisor/Paper.java b/src/main/java/model/rockpapercisor/Paper.java new file mode 100644 index 0000000000000000000000000000000000000000..9f972a30e2e18fcf11ab89700ae7798cc19aa01e --- /dev/null +++ b/src/main/java/model/rockpapercisor/Paper.java @@ -0,0 +1,123 @@ +package model.rockpapercisor; + +import java.util.ArrayList; +import java.util.List; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Paper implements Entity { + private final int priority = 0; + Position position; + private int age; + private final Color viewColor = Color.GRAY; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/pfc/paper.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Paper(Position p) { + this.position = p; + } + + public Paper(Position p, int age) { + this.position = p; + this.age = age; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + Position target = null; + target = board.getNearestEntity(position, Rock.class, null); + + Position ennemy = null; + ennemy = board.getNearestEntity(position, Cisor.class, null); + if(ennemy == null && target == null){ + return List.of(); + } + Position nextPos = null; + // Vérifier la proximité d'un ennemi avant de choisir la direction. + if (ennemy != null && PositionUtil.getManhattanDistance(position, ennemy) < 5) { + nextPos = PositionUtil.getNextPositionAwayFrom(position, ennemy, board); + } else if(target != null){ + nextPos = PositionUtil.getNextPositionTowards(position, target, board); + } + + if (nextPos != null && board.doesPositionExist(nextPos)) { + board.addEntityAtSquare(this, nextPos); + board.clearCaseFrom(this, position); + Position oldPosition = new Position(position.x(), position.y()); + this.position = nextPos; + if (board.doesSquareContainEntity(nextPos, Rock.class)) { + List<Entity> entities = board.getStates(nextPos).getEntities(); + entities.removeIf(p -> p instanceof Rock); + } + + List<Position> result = new ArrayList<>(); + if (target != null) + result.add(target); + if (oldPosition != null) + result.add(oldPosition); + if (position != null) + result.add(position); + if (ennemy != null) + result.add(ennemy); + return result; + + } + return List.of(); + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public ViewElement getViewElement() { + return new ViewElement(cloudImage); + } + +} diff --git a/src/main/java/model/rockpapercisor/Rock.java b/src/main/java/model/rockpapercisor/Rock.java new file mode 100644 index 0000000000000000000000000000000000000000..459c0e6895594f1f2b296f31483c487c5939d18f --- /dev/null +++ b/src/main/java/model/rockpapercisor/Rock.java @@ -0,0 +1,124 @@ +package model.rockpapercisor; + +import java.util.ArrayList; +import java.util.List; + +import javafx.scene.paint.Color; +import model.Board; +import model.Entity; +import model.Square; +import model.firefighterscenario.Cloud; +import util.Position; +import util.PositionUtil; +import view.ViewElement; + +public class Rock implements Entity { + private final int priority = 0; + Position position; + private int age; + private final Color viewColor = Color.CHOCOLATE; + private static javafx.scene.image.Image cloudImage; + + static { + try { + cloudImage = new javafx.scene.image.Image(Cloud.class.getResource("/view/icons/pfc/rock.png").toExternalForm()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Rock(Position p) { + this.position = p; + } + + public Rock(Position p, int age) { + this.position = p; + this.age = age; + } + + @Override + public List<Position> nextTurn(Board<Square> board) { + Position target = null; + target = board.getNearestEntity(position, Cisor.class, null); + + Position ennemy = null; + ennemy = board.getNearestEntity(position, Paper.class, null); + + if(ennemy == null && target == null){ + return List.of(); + } + Position nextPos = null; + // Vérifier la proximité d'un ennemi avant de choisir la direction. + if (ennemy != null && PositionUtil.getManhattanDistance(position, ennemy) < 5) { + nextPos = PositionUtil.getNextPositionAwayFrom(position, ennemy, board); + } else if(target != null){ + nextPos = PositionUtil.getNextPositionTowards(position, target, board); + } + + if (nextPos != null && board.doesPositionExist(nextPos)) { + board.addEntityAtSquare(this, nextPos); + board.clearCaseFrom(this, position); + Position oldPosition = new Position(position.x(), position.y()); + this.position = nextPos; + if (board.doesSquareContainEntity(nextPos, Cisor.class)) { + List<Entity> entities = board.getStates(nextPos).getEntities(); + entities.removeIf(p -> p instanceof Cisor); + } + + List<Position> result = new ArrayList<>(); + if (target != null) + result.add(target); + if (oldPosition != null) + result.add(oldPosition); + if (position != null) + result.add(position); + if (ennemy != null) + result.add(ennemy); + return result; + + } + return List.of(); + } + + @Override + public Position getPosition() { + return this.position; + } + + @Override + public void setPosition(Position p) { + this.position = p; + + } + + @Override + public int getAge() { + return this.age; + } + + @Override + public void setAge(int age) { + this.age = age; + } + + @Override + public void incrementAge() { + this.age += 1; + } + + @Override + public Color getViewColor() { + return this.viewColor; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public ViewElement getViewElement(){ + return new ViewElement(cloudImage); + } + +} diff --git a/src/main/java/model/rockpapercisor/RockPaperCisorScenario.java b/src/main/java/model/rockpapercisor/RockPaperCisorScenario.java new file mode 100644 index 0000000000000000000000000000000000000000..40207fddbd23605e56252ac9113341c9b7df4217 --- /dev/null +++ b/src/main/java/model/rockpapercisor/RockPaperCisorScenario.java @@ -0,0 +1,55 @@ +package model.rockpapercisor; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import model.Board; +import model.Entity; +import model.EntityFactory; +import model.Model; +import model.Scenario; +import model.Square; +import util.Position; + +public class RockPaperCisorScenario extends Scenario implements Model{ + public RockPaperCisorScenario(int columns, int rows, Map<EntityFactory, Integer> initialMap) { + super(columns, rows, initialMap); + } + + public List<Position> updateToNextGeneration() { + ArrayList<Position> changedPositions = new ArrayList<>(); + Iterator<Square> iterator = getMatrix().iterator(); + while (iterator.hasNext()) { + Square s = iterator.next(); + if (s.isEmpty()) + continue; + if (s.getMaxAge() == 0) { + s.incrementAllAges(); + continue; + } + if(s.getMaxAge()>stepNumber()+1){ + continue; + } + List<Entity> entities = new ArrayList<>(s.getEntities()); + for (Entity e : entities) { + e.incrementAge(); + changedPositions.addAll(e.nextTurn(this)); + } + } + + // Increment the step counter + this.step = this.step + 1; + return changedPositions; + } + + @Override + public Board<Square> getBoard() { + return this; + } + + + + +} diff --git a/src/main/java/util/Matrix.java b/src/main/java/util/Matrix.java index 36a06da1550e9d89446c4f936d695a8bdab698fe..5ed290f0c31f3134d241fb49e3d716fb3bd0f874 100644 --- a/src/main/java/util/Matrix.java +++ b/src/main/java/util/Matrix.java @@ -6,6 +6,7 @@ import java.util.Iterator; import java.util.NoSuchElementException; import model.Square; +import model.doctorviruspatient.Patient; import model.firefighterscenario.Fire; import model.firefighterscenario.FireFighter; @@ -83,8 +84,11 @@ public class Matrix<E> implements Iterable<E> { else if(s.getEntities().stream().anyMatch(p -> p instanceof FireFighter)){ System.out.print(" ff | "); } - else if(s.getEntities().stream().anyMatch(p -> p instanceof FireFighter)){ - System.out.print(" A | "); + else if(s.getEntities().stream().anyMatch(p -> p instanceof Patient)){ + System.out.print(" P | "); + } + else if(s.getEntities().stream().anyMatch(p -> p instanceof model.doctorviruspatient.Virus)){ + System.out.print(" V | "); }else{ System.out.print(" | "); } diff --git a/src/main/java/util/PathGenerator.java b/src/main/java/util/PathGenerator.java index 149c4ca1633a286e84915cf3c75c7405607470da..148116237eb0cc1ac4c04c91d23be3b5cb836543 100644 --- a/src/main/java/util/PathGenerator.java +++ b/src/main/java/util/PathGenerator.java @@ -10,7 +10,7 @@ import java.util.Set; import model.Board; public class PathGenerator { - private final Board<?> board; + private Board<?> board; private final Random random = new Random(); private final int maxStepsInDirection; private final int minimumRoadLength; @@ -59,7 +59,9 @@ public class PathGenerator { } return roadLength >= minimumRoadLength ? path : regeneratePath(); } - + public void setBoard(Board<?> board){ + this.board = board; + } /** Initialise le chemin avec l'ancre et choisit la première direction. */ private void initializePath() { path.clear(); diff --git a/src/main/java/util/PositionUtil.java b/src/main/java/util/PositionUtil.java index 0a3f9011468dbeb11e6b8b2f4fb3549f0f083328..096c290d4560c1edbf0d73da67370422515e64da 100644 --- a/src/main/java/util/PositionUtil.java +++ b/src/main/java/util/PositionUtil.java @@ -2,11 +2,14 @@ package util; import java.util.ArrayList; import java.util.List; +import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import model.Board; import model.Square; +import model.firefighterscenario.FireFighter; +import model.firefighterscenario.Mountain; public class PositionUtil { /** @@ -153,4 +156,169 @@ public class PositionUtil { return positions; } + + public static Position getNextPositionTowards(Position currentPos, Position targetPos, Board<Square> b) { + // Generate adjacent positions + List<Position> possibleMoves = PositionUtil.generateAllAdjacentPositions(currentPos, b); + + // Filter out positions that are not empty or contain obstacles + possibleMoves.removeIf(p -> b.doesSquareContainEntity(p, Mountain.class)); + + // If no possible moves, return null + if (possibleMoves.isEmpty()) { + return null; + } + + // Calculate the current distance to the target + int currentDistance = PositionUtil.getManhattanDistance(currentPos, targetPos); + + // Initialize variables to find the best moves + int minDistance = Integer.MAX_VALUE; + List<Position> bestMoves = new ArrayList<>(); + + for (Position move : possibleMoves) { + int distance = PositionUtil.getManhattanDistance(move, targetPos); + + // Skip positions occupied by other firefighters + if (b.doesSquareContainEntity(move, FireFighter.class)) { + continue; + } + + // Find positions that minimize the distance + if (distance < minDistance) { + minDistance = distance; + bestMoves.clear(); + bestMoves.add(move); + } else if (distance == minDistance) { + bestMoves.add(move); + } + } + + // If no better move is found, consider moves that maintain the same distance + if (bestMoves.isEmpty()) { + minDistance = currentDistance; + for (Position move : possibleMoves) { + int distance = PositionUtil.getManhattanDistance(move, targetPos); + if (distance == minDistance) { + bestMoves.add(move); + } + } + } + + // If still no move is found, stay in the current position + if (bestMoves.isEmpty()) { + return currentPos; + } + + // Select a move from the best moves (e.g., randomly or based on additional criteria) + Random r = new Random(); + + Position nextMove = bestMoves.get(r.nextInt(bestMoves.size())); + + return nextMove; + } + + public static Position getNextPositionAwayFrom(Position currentPos, Position targetPos, Board<Square> b) { + // Générer les positions adjacentes + List<Position> possibleMoves = PositionUtil.generateAllAdjacentPositions(currentPos, b); + + // Filtrer les positions qui ne sont pas vides ou contiennent des obstacles + possibleMoves.removeIf(p -> b.doesSquareContainEntity(p, Mountain.class)); + + // Si aucune possibilité de déplacement, retourner null + if (possibleMoves.isEmpty()) { + return null; + } + + // Calculer la distance actuelle par rapport à la cible + int currentDistance = PositionUtil.getManhattanDistance(currentPos, targetPos); + + // Initialiser les variables pour trouver les meilleurs déplacements + int maxDistance = Integer.MIN_VALUE; + List<Position> bestMoves = new ArrayList<>(); + + for (Position move : possibleMoves) { + int distance = PositionUtil.getManhattanDistance(move, targetPos); + + // Ignorer les positions occupées par d'autres entités, comme les pompiers + if (b.doesSquareContainEntity(move, FireFighter.class)) { + continue; + } + + // Trouver les positions qui maximisent la distance + if (distance > maxDistance) { + maxDistance = distance; + bestMoves.clear(); + bestMoves.add(move); + } else if (distance == maxDistance) { + bestMoves.add(move); + } + } + + // Si aucun meilleur déplacement n'est trouvé, considérer les mouvements qui maintiennent la même distance + if (bestMoves.isEmpty()) { + maxDistance = currentDistance; + for (Position move : possibleMoves) { + int distance = PositionUtil.getManhattanDistance(move, targetPos); + if (distance == maxDistance) { + bestMoves.add(move); + } + } + } + + // Si toujours aucun mouvement n'est trouvé, rester à la position actuelle + if (bestMoves.isEmpty()) { + return currentPos; + } + + // Sélectionner un mouvement parmi les meilleurs mouvements (par exemple aléatoirement ou selon des critères supplémentaires) + Random r = new Random(); + + Position nextMove = bestMoves.get(r.nextInt(bestMoves.size())); + + return nextMove; + } + public static Direction getOppositeDirection(Direction direction) { + switch (direction) { + case NORTH: return Direction.SOUTH; + case SOUTH: return Direction.NORTH; + case EAST: return Direction.WEST; + case WEST: return Direction.EAST; + default: throw new IllegalArgumentException("Direction non supportée : " + direction); + } + } + + /** + * Détermine la direction principale (NORTH, SOUTH, EAST, WEST) de toPos par rapport à fromPos. + * + * @param fromPos la position de départ. + * @param toPos la position de destination. + * @return la direction principale de toPos par rapport à fromPos. + */ +public static Direction getDirectionFromTwoPoints(Position fromPos, Position toPos) { + int deltaX = toPos.x() - fromPos.x(); + int deltaY = toPos.y() - fromPos.y(); + + if (deltaX == 0 && deltaY == 0) { + return null; // Les positions sont identiques + } + + if (Math.abs(deltaX) > Math.abs(deltaY)) { + // Mouvement principalement vers l'Est ou l'Ouest + if (deltaX > 0) { + return Direction.EAST; + } else { + return Direction.WEST; + } + } else { + // Mouvement principalement vers le Nord ou le Sud + if (deltaY > 0) { + return Direction.SOUTH; + } else { + return Direction.NORTH; + } + } +} + + } \ No newline at end of file diff --git a/src/main/java/view/FirefighterGrid.java b/src/main/java/view/FirefighterGrid.java index ecc8129c023c3a84787bb12b7db4de3bbb7cde95..99f055607051383a5f7fedf73a91849818306cbd 100644 --- a/src/main/java/view/FirefighterGrid.java +++ b/src/main/java/view/FirefighterGrid.java @@ -1,17 +1,32 @@ package view; - import java.util.List; import javafx.scene.canvas.Canvas; +import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.util.Pair; import util.Position; public class FirefighterGrid extends Canvas implements Grid<ViewElement>{ + //private void paintElementAtPosition(ViewElement element, Position position) { + // paintBox(position.x(), position.y(), element.getColor()); + //} + + private void paintElementAtPosition(ViewElement element, Position position) { - paintBox(position.x(), position.y(), element.getColor()); + // Efface la case pour éviter les superpositions + clearBox(position.x(), position.y()); + + // Vérifie si une image est définie dans l'élément + if (element.getImage() != null) { + Image image = element.getImage(); + getGraphicsContext2D().drawImage(image, position.y() * boxWidth, position.x() * boxHeight, boxWidth, boxHeight); + } else { + paintBox(position.x(), position.y(), element.getColor()); + } } + private int boxWidth; private int boxHeight; private int columnCount; diff --git a/src/main/java/view/Grid.java b/src/main/java/view/Grid.java index b95d59f622a86b41f2a41261b8b27aaf2e911dfb..c0754aedc8933a5f2a4b2983d680aa56150a87ef 100644 --- a/src/main/java/view/Grid.java +++ b/src/main/java/view/Grid.java @@ -12,44 +12,44 @@ import java.util.List; */ public interface Grid<E> { - /** - * Repaint the grid with a list of elements, each associated with their respective positions. - * - * @param elements A list of pairs, each containing a position and the element to be displayed at that position. - */ - void repaint(List<Pair<Position, E>> elements); - - /** - * Repaint the grid with a two-dimensional array of elements. The array's dimensions should match - * the row and column count of the grid. - * - * @param elements A two-dimensional array of elements to be displayed on the grid. - */ - void repaint(E[][] elements); - - /** - * Set the dimensions of the grid to the specified number of columns, number of rows, square width, - * and square height. - * - * @param columnCount The new number of columns in the grid. - * @param rowCount The new number of rows in the grid. - * @param squareWidth The width of each square within the grid. - * @param squareHeight The height of each square within the grid. - */ - void setDimensions(int columnCount, int rowCount, int squareWidth, int squareHeight); - - /** - * Get the number of columns in the grid. - * - * @return The number of columns in the grid. - */ - int columnCount(); - - /** - * Get the number of rows in the grid. - * - * @return The number of rows in the grid. - */ - int rowCount(); + /** + * Repaint the grid with a list of elements, each associated with their respective positions. + * + * @param elements A list of pairs, each containing a position and the element to be displayed at that position. + */ + void repaint(List<Pair<Position, E>> elements); + + /** + * Repaint the grid with a two-dimensional array of elements. The array's dimensions should match + * the row and column count of the grid. + * + * @param elements A two-dimensional array of elements to be displayed on the grid. + */ + void repaint(E[][] elements); + + /** + * Set the dimensions of the grid to the specified number of columns, number of rows, square width, + * and square height. + * + * @param columnCount The new number of columns in the grid. + * @param rowCount The new number of rows in the grid. + * @param squareWidth The width of each square within the grid. + * @param squareHeight The height of each square within the grid. + */ + void setDimensions(int columnCount, int rowCount, int squareWidth, int squareHeight); + + /** + * Get the number of columns in the grid. + * + * @return The number of columns in the grid. + */ + int columnCount(); + + /** + * Get the number of rows in the grid. + * + * @return The number of rows in the grid. + */ + int rowCount(); } diff --git a/src/main/java/view/ViewElement.java b/src/main/java/view/ViewElement.java index 5043644547213f648760eba9e4bb0693411e527b..3059a474eba08dc25e8e0e9cb8a186344a5c85c1 100644 --- a/src/main/java/view/ViewElement.java +++ b/src/main/java/view/ViewElement.java @@ -1,15 +1,29 @@ package view; +import javafx.scene.image.Image; import javafx.scene.paint.Color; public class ViewElement { private final Color color; + private final Image image; + // Constructeur avec couleur uniquement public ViewElement(Color color) { this.color = color; + this.image = null; + } + + // Constructeur avec image + public ViewElement(Image image) { + this.color = null; + this.image = image; } public Color getColor() { return color; } + + public Image getImage() { + return image; + } } diff --git a/src/main/resources/view/icons/fire/avion.png b/src/main/resources/view/icons/fire/avion.png new file mode 100644 index 0000000000000000000000000000000000000000..6a5d9a690230ddb0a55e5f4050faf69af578341b Binary files /dev/null and b/src/main/resources/view/icons/fire/avion.png differ diff --git a/src/main/resources/view/icons/fire/camion.png b/src/main/resources/view/icons/fire/camion.png new file mode 100644 index 0000000000000000000000000000000000000000..b3a361c84dc686238486079ae477cf346214528f Binary files /dev/null and b/src/main/resources/view/icons/fire/camion.png differ diff --git a/src/main/resources/view/icons/fire/flamme.png b/src/main/resources/view/icons/fire/flamme.png new file mode 100644 index 0000000000000000000000000000000000000000..0784e111e8761e9c2bacc9102eecc62b97bbf58b Binary files /dev/null and b/src/main/resources/view/icons/fire/flamme.png differ diff --git a/src/main/resources/view/icons/fire/img.png b/src/main/resources/view/icons/fire/img.png new file mode 100644 index 0000000000000000000000000000000000000000..f765539c06aafd59b0c2fc1a09fc389f9996410c Binary files /dev/null and b/src/main/resources/view/icons/fire/img.png differ diff --git a/src/main/resources/view/icons/fire/montagne.png b/src/main/resources/view/icons/fire/montagne.png new file mode 100644 index 0000000000000000000000000000000000000000..cf970e54796b833d6e28678344d48b48bf02f2ad Binary files /dev/null and b/src/main/resources/view/icons/fire/montagne.png differ diff --git a/src/main/resources/view/icons/fire/nuage.png b/src/main/resources/view/icons/fire/nuage.png new file mode 100644 index 0000000000000000000000000000000000000000..308714e9a1c1acafcf230fef7f7e4a79ccc0e49d Binary files /dev/null and b/src/main/resources/view/icons/fire/nuage.png differ diff --git a/src/main/resources/view/icons/fire/rochers.png b/src/main/resources/view/icons/fire/rochers.png new file mode 100644 index 0000000000000000000000000000000000000000..3c43a47397f45827363ed17e2bdbf1e651a3c864 Binary files /dev/null and b/src/main/resources/view/icons/fire/rochers.png differ diff --git a/src/main/resources/view/icons/fire/route.png b/src/main/resources/view/icons/fire/route.png new file mode 100644 index 0000000000000000000000000000000000000000..fb3ba6dc051837260312bc0d168c2a9952788a32 Binary files /dev/null and b/src/main/resources/view/icons/fire/route.png differ diff --git a/src/main/resources/view/icons/fire/sapeur-pompier.png b/src/main/resources/view/icons/fire/sapeur-pompier.png new file mode 100644 index 0000000000000000000000000000000000000000..b2e592c7475ce7f1b4747300ee9e8f4f1fd1d345 Binary files /dev/null and b/src/main/resources/view/icons/fire/sapeur-pompier.png differ diff --git a/src/main/resources/view/icons/pfc/cis.png b/src/main/resources/view/icons/pfc/cis.png new file mode 100644 index 0000000000000000000000000000000000000000..646b9f7b984a658b64051266f3aaf4b26fa13b21 Binary files /dev/null and b/src/main/resources/view/icons/pfc/cis.png differ diff --git a/src/main/resources/view/icons/pfc/paper.png b/src/main/resources/view/icons/pfc/paper.png new file mode 100644 index 0000000000000000000000000000000000000000..4c3f80c1ccdd8709ac1240f2bc9d36705500efc3 Binary files /dev/null and b/src/main/resources/view/icons/pfc/paper.png differ diff --git a/src/main/resources/view/icons/pfc/rock.png b/src/main/resources/view/icons/pfc/rock.png new file mode 100644 index 0000000000000000000000000000000000000000..9e0bc082f7231fad12300e0cabf87a988e4aa33e Binary files /dev/null and b/src/main/resources/view/icons/pfc/rock.png differ diff --git a/src/main/resources/view/icons/virus/docteur.png b/src/main/resources/view/icons/virus/docteur.png new file mode 100644 index 0000000000000000000000000000000000000000..902a90c30e5eea76c075246b2573f4480704ed64 Binary files /dev/null and b/src/main/resources/view/icons/virus/docteur.png differ diff --git a/src/main/resources/view/icons/virus/humain.png b/src/main/resources/view/icons/virus/humain.png new file mode 100644 index 0000000000000000000000000000000000000000..d88de16c2b701a823f7bceccc5629562cab05a56 Binary files /dev/null and b/src/main/resources/view/icons/virus/humain.png differ diff --git a/src/main/resources/view/icons/virus/patient.png b/src/main/resources/view/icons/virus/patient.png new file mode 100644 index 0000000000000000000000000000000000000000..9aa4113c8fd5ad39ee4592877058c27e2d2e52e0 Binary files /dev/null and b/src/main/resources/view/icons/virus/patient.png differ diff --git a/src/main/resources/view/icons/virus/virus.png b/src/main/resources/view/icons/virus/virus.png new file mode 100644 index 0000000000000000000000000000000000000000..a4d6b7c5e10766a9fe5ce085a1da41486ce22716 Binary files /dev/null and b/src/main/resources/view/icons/virus/virus.png differ