From 0720699f10bd88e86dab84ee9fd6421d8196de5a Mon Sep 17 00:00:00 2001 From: Moncef STITI Date: Fri, 6 Dec 2024 19:31:34 +0100 Subject: [PATCH] =?UTF-8?q?R=C3=A9paration=20du=20score=20gr=C3=A2ce=20?= =?UTF-8?q?=C3=A0=20Luc=20(the=20goat)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dorfromantik/game/BiomeGroup.java | 29 ---- src/fr/monkhanny/dorfromantik/game/Board.java | 106 +++--------- .../monkhanny/dorfromantik/game/Pocket.java | 32 ++-- .../dorfromantik/game/ScoreDisplay.java | 4 +- .../dorfromantik/game/ScoreManager.java | 161 ++++++++++++++---- src/fr/monkhanny/dorfromantik/game/Tile.java | 66 +++++-- 6 files changed, 225 insertions(+), 173 deletions(-) delete mode 100644 src/fr/monkhanny/dorfromantik/game/BiomeGroup.java diff --git a/src/fr/monkhanny/dorfromantik/game/BiomeGroup.java b/src/fr/monkhanny/dorfromantik/game/BiomeGroup.java deleted file mode 100644 index f381031..0000000 --- a/src/fr/monkhanny/dorfromantik/game/BiomeGroup.java +++ /dev/null @@ -1,29 +0,0 @@ -package fr.monkhanny.dorfromantik.game; - -import java.util.ArrayList; -import java.util.List; - -public class BiomeGroup { - private List pockets; - - public BiomeGroup() { - pockets = new ArrayList<>(); - } - - public void addPocket(Pocket pocket) { - pockets.add(pocket); - } - - public List getPockets() { - return pockets; - } - - public int calculateTotalScore() { - int totalScore = 0; - for (Pocket pocket : pockets) { - totalScore += pocket.calculateScore(); - } - return totalScore; - } -} - diff --git a/src/fr/monkhanny/dorfromantik/game/Board.java b/src/fr/monkhanny/dorfromantik/game/Board.java index ba08993..f5e4660 100644 --- a/src/fr/monkhanny/dorfromantik/game/Board.java +++ b/src/fr/monkhanny/dorfromantik/game/Board.java @@ -6,9 +6,7 @@ import fr.monkhanny.dorfromantik.listeners.GameSpaceKeyListener; import fr.monkhanny.dorfromantik.listeners.GameMouseClickListener; import fr.monkhanny.dorfromantik.listeners.GameMouseWheelListener; import fr.monkhanny.dorfromantik.Options; -import fr.monkhanny.dorfromantik.enums.Biome; import fr.monkhanny.dorfromantik.enums.Fonts; -import fr.monkhanny.dorfromantik.enums.TileOrientation; import fr.monkhanny.dorfromantik.gui.GameControlsMenu; import fr.monkhanny.dorfromantik.gui.GameOver; import fr.monkhanny.dorfromantik.utils.Database; @@ -34,33 +32,26 @@ public class Board extends JPanel{ private int offsetX = 0; // Décalage horizontal du plateau private int offsetY = 0; // Décalage vertical du plateau private Tile nextTile; - private Map biomeGroups; private Point mousePosition; - private ScoreManager scoreManager; private int currentScore; private Database database; private RemainingTilesIndicator remainingTilesIndicator; - private ScoreDisplay scoreDisplay; private GameControlsMenu controlsMenu; - + private ScoreManager scoreManager; + private ScoreDisplay scoreDisplay; // Constructeur avec seed public Board(JFrame gameFrame, long seed) { this.gameFrame = gameFrame; this.tiles = new ArrayList<>(); - this.biomeGroups = new HashMap<>(); this.availablePositions = new ArrayList<>(); this.random = new Random(seed); this.game = new Game(seed); + scoreManager = new ScoreManager(); - this.scoreManager = new ScoreManager(biomeGroups); Font scoreFont = Fonts.SCORE.getFont(30f); // Remplacez par votre logique de chargement de police scoreDisplay = new ScoreDisplay(scoreFont, 0, 40); // Position fixe - for (Biome biome : Biome.values()) { - biomeGroups.put(biome, new BiomeGroup()); - } - // Placer une tuile centrale au démarrage initializeCentralTile(); @@ -188,24 +179,27 @@ public class Board extends JPanel{ if (Options.isPaused) { return; } - - // Récupérer les coordonnées du clic + Point clickedPoint = e.getPoint(); - - // Ajuster les coordonnées du clic en tenant compte du zoom et des déplacements - // Annuler l'effet du zoom et du déplacement int adjustedX = (int)((clickedPoint.x - offsetX) / zoomFactor); int adjustedY = (int)((clickedPoint.y - offsetY) / zoomFactor); - - // Vérifiez si la position ajustée est dans la liste des positions disponibles et si la distance est suffisante + + Point nearestPosition = null; + double minDistance = Double.MAX_VALUE; + for (Point position : availablePositions) { - // Vérifiez la distance entre le clic ajusté et la position - if (new Point(adjustedX, adjustedY).distance(position) < 20) { - placeTileAtPosition(position); // Place une tuile à cette position - break; // Si une tuile est ajoutée, on peut sortir de la boucle + double distance = new Point(adjustedX, adjustedY).distance(position); + if (distance < minDistance) { + minDistance = distance; + nearestPosition = position; } } + + if (nearestPosition != null && minDistance < 20) { + placeTileAtPosition(nearestPosition); + } } + private void initializeCentralTile() { @@ -215,6 +209,7 @@ public class Board extends JPanel{ this.centralTile = new Tile(this, centerX, centerY, 50); addTile(centralTile); + // Calculer les positions disponibles autour de la tuile centrale calculateAvailablePositions(centralTile); initializeNextTile(); @@ -222,67 +217,19 @@ public class Board extends JPanel{ public void addTile(Tile tile) { tiles.add(tile); - updatePockets(tile); - calculateCurrentScore(); + scoreManager.addTile(tile); + currentScore = scoreManager.getCurrentScore(); + scoreDisplay.setScore(currentScore); } - private void updatePockets(Tile newTile) { - for (TileOrientation orientation : TileOrientation.values()) { - Biome biome = newTile.getBiome(orientation); - BiomeGroup biomeGroup = biomeGroups.get(biome); - // Vérifier si la nouvelle tuile peut être connectée à une poche existante - Pocket connectedPocket = null; - for (Pocket pocket : biomeGroup.getPockets()) { - if (isConnectedToPocket(newTile, pocket)) { - connectedPocket = pocket; - break; - } - } - - if (connectedPocket != null) { - // Connecte la tuile à une poche existante - connectedPocket.addTile(newTile); - } else { - // Crée une nouvelle poche pour ce biome - Pocket newPocket = new Pocket(biome); - newPocket.addTile(newTile); - biomeGroup.addPocket(newPocket); + public Tile getTileAt(int x, int y) { + for (Tile tile : tiles) { + if (Math.abs(tile.getXCoord() - x) < 5 && Math.abs(tile.getYCoord() - y) < 5) { + return tile; } } - } - - // Méthode pour vérifier si une tuile est connectée à une poche existante - private boolean isConnectedToPocket(Tile tile, Pocket pocket) { - for (Tile connectedTile : pocket.getTiles()) { - if (areTilesConnected(tile, connectedTile)) { - return true; - } - } - return false; - } - - - // Vérifie si deux tuiles sont connectées par un même biome - private boolean areTilesConnected(Tile tile1, Tile tile2) { - for (TileOrientation orientation : TileOrientation.values()) { - if (tile1.getBiome(orientation).equals(tile2.getBiome(orientation.oppositeOrientation()))) { - // Vérifier si les tuiles sont adjacentes (logique à adapter selon vos besoins) - // Exemple : si elles partagent un côté commun - return tile1.isAdjacentTo(tile2); - } - } - return false; - } - - private void calculateCurrentScore() { - scoreManager.updateScore(); // Met à jour le score - currentScore = scoreManager.getCurrentScore(); // Récupère le score actuel - scoreDisplay.setScore(currentScore); // Met à jour l'affichage du score - } - - public int getCurrentScore() { - return currentScore; + return null; } public Random getRandom() { return random; } @@ -435,6 +382,7 @@ public class Board extends JPanel{ scoreDisplay.draw(g); + // Appliquer l'échelle de zoom et le déplacement g2d.scale(zoomFactor, zoomFactor); // Appliquer le zoom g2d.translate(offsetX / zoomFactor, offsetY / zoomFactor); // Appliquer le déplacement (en tenant compte du zoom) diff --git a/src/fr/monkhanny/dorfromantik/game/Pocket.java b/src/fr/monkhanny/dorfromantik/game/Pocket.java index 114bd3f..95ad266 100644 --- a/src/fr/monkhanny/dorfromantik/game/Pocket.java +++ b/src/fr/monkhanny/dorfromantik/game/Pocket.java @@ -1,15 +1,16 @@ package fr.monkhanny.dorfromantik.game; import fr.monkhanny.dorfromantik.enums.Biome; +import fr.monkhanny.dorfromantik.enums.TileOrientation; +import java.awt.Point; +import java.util.*; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - +/** + * Represents a connected pocket of tiles with the same biome. + */ public class Pocket { private Biome biome; - private Set tiles; // Ensemble des tuiles de la poche + private Set tiles; public Pocket(Biome biome) { this.biome = biome; @@ -20,24 +21,15 @@ public class Pocket { tiles.add(tile); } - public boolean containsTile(Tile tile) { - return tiles.contains(tile); + public int getSize() { + return tiles.size(); } public Biome getBiome() { return biome; } - public int getSize() { - return tiles.size(); + public Set getTiles() { + return tiles; } - - public int calculateScore() { - // Calcul du score basé sur la taille de la poche - return getSize() * getSize(); - } - - public List getTiles() { - return new ArrayList<>(tiles); - } -} \ No newline at end of file +} diff --git a/src/fr/monkhanny/dorfromantik/game/ScoreDisplay.java b/src/fr/monkhanny/dorfromantik/game/ScoreDisplay.java index 777abbe..b25caf8 100644 --- a/src/fr/monkhanny/dorfromantik/game/ScoreDisplay.java +++ b/src/fr/monkhanny/dorfromantik/game/ScoreDisplay.java @@ -7,7 +7,7 @@ import java.awt.Graphics; public class ScoreDisplay { private int score; private Font font; - private int x, y; // Position du score + private int x, y; // Position du texte public ScoreDisplay(Font font, int x, int y) { this.font = font; @@ -29,4 +29,4 @@ public class ScoreDisplay { g.setColor(Color.BLACK); g.drawString("Score: " + score, x, y); } -} +} \ No newline at end of file diff --git a/src/fr/monkhanny/dorfromantik/game/ScoreManager.java b/src/fr/monkhanny/dorfromantik/game/ScoreManager.java index 14785d2..433d2ff 100644 --- a/src/fr/monkhanny/dorfromantik/game/ScoreManager.java +++ b/src/fr/monkhanny/dorfromantik/game/ScoreManager.java @@ -1,44 +1,139 @@ package fr.monkhanny.dorfromantik.game; -import java.util.Map; import fr.monkhanny.dorfromantik.enums.Biome; +import fr.monkhanny.dorfromantik.enums.TileOrientation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** - * Classe responsable du calcul et de la gestion du score. + * Manages the score of the game, keeping track of biome pockets. */ public class ScoreManager { - private int currentScore = 0; - private Map biomeGroups; + private List pockets; + private int currentScore; - // Constructeur avec la référence aux groupes de biomes - public ScoreManager(Map biomeGroups) { - this.biomeGroups = biomeGroups; - } - - // Méthode pour calculer le score en fonction des groupes de biomes - public void calculateScore() { - int totalScore = 0; - - for (BiomeGroup group : biomeGroups.values()) { - totalScore += group.calculateTotalScore(); - } - - currentScore = totalScore; - } - - // Récupérer le score actuel - public int getCurrentScore() { - return currentScore; - } - - // Mettre à jour le score (si nécessaire) - public void updateScore() { - calculateScore(); - } - - // Réinitialiser le score - public void resetScore() { + public ScoreManager() { + pockets = new ArrayList<>(); currentScore = 0; } -} + /** + * Adds a tile to the appropriate pocket or creates a new one if necessary. + * + * @param tile The tile to add. + */ + public void addTile(Tile tile) { + Map biomeToPocketMap = new HashMap<>(); + + // Trouver les poches existantes auxquelles cette tuile peut être connectée, en vérifiant les voisins directs + for (TileOrientation orientation : TileOrientation.values()) { + Biome biome = tile.getBiome(orientation); + if (biome != null) { + // Trouver la tuile voisine dans la direction donnée + Tile neighborTile = tile.getNeighbor(orientation); + if (neighborTile != null && neighborTile.getBiome(orientation.oppositeOrientation()) == biome) { + Pocket connectedPocket = findPocketForTile(neighborTile, biome); + if (connectedPocket != null && !biomeToPocketMap.containsKey(biome)) { + biomeToPocketMap.put(biome, connectedPocket); + } + } + } + } + + // Ajouter la tuile aux poches existantes ou créer une nouvelle poche si aucune n'est trouvée + for (TileOrientation orientation : TileOrientation.values()) { + Biome biome = tile.getBiome(orientation); + if (biome != null) { + if (biomeToPocketMap.containsKey(biome)) { + // Ajouter la tuile à la poche existante pour ce biome + biomeToPocketMap.get(biome).addTile(tile); + } else { + // Créer une nouvelle poche pour ce biome + Pocket newPocket = new Pocket(biome); + newPocket.addTile(tile); + pockets.add(newPocket); + biomeToPocketMap.put(biome, newPocket); + System.out.println("New pocket created with biome: " + biome); + } + } + } + + // Recalculer le score après avoir ajouté la tuile + recalculateScore(); + System.out.println("Current Score: " + currentScore); + } + + /** + * Finds the pocket associated with the given tile and biome. + * + * @param tile The tile to check. + * @param biome The biome to match. + * @return The connected pocket, or null if none found. + */ + private Pocket findPocketForTile(Tile tile, Biome biome) { + for (Pocket pocket : pockets) { + if (pocket.getBiome() == biome && pocket.getTiles().contains(tile)) { + return pocket; + } + } + return null; + } + + + + + /** + * Finds a pocket connected to the given tile with the specified biome. + * + * @param tile The tile to check connections for. + * @param biome The biome to match. + * @return The connected pocket, or null if none found. + */ + private Pocket findConnectedPocket(Tile tile, Biome biome) { + for (Pocket pocket : pockets) { + if (pocket.getBiome() == biome) { + for (Tile pocketTile : pocket.getTiles()) { + if (pocketTile.isAdjacentTo(tile) && sharesBiome(tile, pocketTile, biome)) { + return pocket; + } + } + } + } + return null; + } + + /** + * Checks if two tiles share a biome on any of their sides. + * + * @param tile1 The first tile. + * @param tile2 The second tile. + * @param biome The biome to match. + * @return True if the tiles share the given biome on a connecting side. + */ + private boolean sharesBiome(Tile tile1, Tile tile2, Biome biome) { + for (TileOrientation orientation : TileOrientation.values()) { + if (tile1.getBiome(orientation) == biome && tile2.getBiome(orientation.oppositeOrientation()) == biome) { + return true; + } + } + return false; + } + + /** + * Recalculates the score based on the current pockets. + */ + private void recalculateScore() { + currentScore = 0; + for (Pocket pocket : pockets) { + currentScore += Math.pow(pocket.getSize(), 2); + } + } + + public int getCurrentScore() { + return currentScore; + } +} \ No newline at end of file diff --git a/src/fr/monkhanny/dorfromantik/game/Tile.java b/src/fr/monkhanny/dorfromantik/game/Tile.java index 386da67..bba0a14 100644 --- a/src/fr/monkhanny/dorfromantik/game/Tile.java +++ b/src/fr/monkhanny/dorfromantik/game/Tile.java @@ -139,21 +139,67 @@ public class Tile extends Cell { return false; } + public boolean isAdjacentTo(Tile otherTile) { - // Obtenir le rayon de la tuile - int tileRadius = this.getRadius(); + + int radius = this.getRadius(); // Utilisation du rayon pour la distance correcte - // Compute the distance between the center of this tile and the other tile - int deltaX = this.getX() - otherTile.getX(); - int deltaY = this.getY() - otherTile.getY(); - - // Calculate the Euclidean distance between the two tiles - double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + // Calculer les différences de position + int deltaX = otherTile.getXCoord() - this.getXCoord(); + int deltaY = otherTile.getYCoord() - this.getYCoord(); - // In a hexagonal grid, two tiles are adjacent if their distance is equal to the diameter (2 * radius) - return distance <= (2 * tileRadius); + // Calculer la distance euclidienne entre les deux tuiles + double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + + // Distance attendue pour des tuiles adjacentes dans une grille hexagonale + double expectedDistance = (int) (1.5 * radius); // ou une autre valeur calculée correctement + + // Définir une tolérance pour la précision + double epsilon = 15.0; + + // Vérifier si la différence de distance est dans la tolérance + if (Math.abs(distance - expectedDistance) < epsilon) { + return true; + } + return false; +} + + +public Tile getNeighbor(TileOrientation orientation) { + int radius = this.getRadius(); + int neighborX = this.getXCoord(); + int neighborY = this.getYCoord(); + + switch (orientation) { + case NORTH: + neighborY -= (int) (Math.sqrt(3) * radius); + break; + case NORTH_EAST: + neighborX += (int) (1.5 * radius); + neighborY -= (int) (Math.sqrt(3) / 2 * radius); + break; + case SOUTH_EAST: + neighborX += (int) (1.5 * radius); + neighborY += (int) (Math.sqrt(3) / 2 * radius); + break; + case SOUTH: + neighborY += (int) (Math.sqrt(3) * radius); + break; + case SOUTH_WEST: + neighborX -= (int) (1.5 * radius); + neighborY += (int) (Math.sqrt(3) / 2 * radius); + break; + case NORTH_WEST: + neighborX -= (int) (1.5 * radius); + neighborY -= (int) (Math.sqrt(3) / 2 * radius); + break; } + // Rechercher la tuile à la position calculée + return this.getBoard().getTileAt(neighborX, neighborY); +} + + private TileOrientation determineSide(int x, int y) { int radius = this.getRadius(); TileOrientation[] sides = TileOrientation.values();