From db66faa557805581e367bb61ebef31ce4c8f7add Mon Sep 17 00:00:00 2001 From: p20006624 <linh.PHAM-THI-NGOC.1@etu.univ-amu.fr> Date: Thu, 23 Nov 2023 09:47:31 +0100 Subject: [PATCH] upgrade --- src/main/java/model/Fire.java | 75 ++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/src/main/java/model/Fire.java b/src/main/java/model/Fire.java index 595a266..0e26689 100644 --- a/src/main/java/model/Fire.java +++ b/src/main/java/model/Fire.java @@ -5,11 +5,74 @@ import util.Position; import java.util.Random; import java.util.Set; -public class Fire { - private final int initialFireCount; - private Set<Position> firePositions; - private final Random randomGenerator = new Random(); - private Position randomPosition() { - return new Position(randomGenerator.nextInt(rowCount), randomGenerator.nextInt(columnCount)); +import java.util.Random; + +public class Fire extends Element implements State { + private boolean onFire; + private int propagationDelay; // Number of turns before the fire can spread + private int propagationCounter; // Counter to track the remaining turns for propagation + private Random random = new Random(); + + // Constructor + public Fire(Position position, int propagationDelay) { + super(position); + this.onFire = true; + this.propagationDelay = propagationDelay; + this.propagationCounter = propagationDelay; + } + + // Implementing State interface method + @Override + public boolean isOnFire() { + return onFire; + } + + // Implementing Element class method + @Override + public void update() { + if (canSpread()) { + spreadFire(); + } + } + + // Method to check if the fire can spread + private boolean canSpread() { + return onFire && propagationCounter <= 0; + } + + // Method to spread the fire randomly to adjacent positions + private void spreadFire() { + Position[] adjacentPositions = getAdjacentPositions(); + if (adjacentPositions.length > 0) { + int randomIndex = random.nextInt(adjacentPositions.length); + Position randomAdjacentPosition = adjacentPositions[randomIndex]; + Element element = getGrid().getElementAt(randomAdjacentPosition); + + // Check if the adjacent position is not occupied by another fire + if (element == null || !(element instanceof Fire)) { + // Spread the fire to the adjacent position + getGrid().addElement(new Fire(randomAdjacentPosition, propagationDelay), randomAdjacentPosition); + } + } + + // Reset the propagation counter + propagationCounter = propagationDelay; + } + + // Method to get adjacent positions + private Position[] getAdjacentPositions() { + int x = position.getX(); + int y = position.getY(); + + // Define adjacent positions + Position[] adjacentPositions = { + new Position(x - 1, y - 1), new Position(x - 1, y), new Position(x - 1, y + 1), + new Position(x, y - 1), new Position(x, y + 1), + new Position(x + 1, y - 1), new Position(x + 1, y), new Position(x + 1, y + 1) + }; + + return adjacentPositions; } } + + -- GitLab