From 0f063e49b946b1f13f8ec9d567437a6a51f35c2d Mon Sep 17 00:00:00 2001 From: Radaelli Lorenzo Date: Wed, 21 Feb 2024 17:50:57 +0100 Subject: [PATCH 01/15] implementazion EndGameState e EndTurnState --- .../app/src/component/mappa/BattleState.js | 91 +++--- src/main/app/src/component/mappa/Console.js | 263 +++++++++--------- .../app/src/component/mappa/EndGameState.js | 16 ++ .../app/src/component/mappa/EndTurnState.js | 30 ++ .../maven/eclipse/states/BattleStateTest.java | 14 + 5 files changed, 239 insertions(+), 175 deletions(-) create mode 100644 src/main/app/src/component/mappa/EndGameState.js create mode 100644 src/main/app/src/component/mappa/EndTurnState.js create mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java diff --git a/src/main/app/src/component/mappa/BattleState.js b/src/main/app/src/component/mappa/BattleState.js index 7a9aa49..c9662f9 100644 --- a/src/main/app/src/component/mappa/BattleState.js +++ b/src/main/app/src/component/mappa/BattleState.js @@ -5,7 +5,6 @@ import Console from "../mappa/Console"; import { Alert, Modal, Button } from "react-bootstrap"; import PartitaObserverSingleton from "../../application/PartitaObserverSingleton"; - function BattleState({ idPlayer, game }) { const [mappa, setMappa] = useState([]); const [player, setPlayer] = useState(); @@ -21,17 +20,16 @@ function BattleState({ idPlayer, game }) { const [showAlert, setShowAlert] = useState(true); const [esiti, setEsiti] = useState({}); const [showEsiti, setShowEsiti] = useState(false); - - + const handleClose = () => setShowEsiti(false); useEffect(() => { - function updateEsiti(esiti) { + function updateEsiti(esiti) { console.log("Esiti in console: ", esiti); setEsiti(esiti); setShowEsiti(true); } - + PartitaObserverSingleton.addListenerEsiti(updateEsiti); const pathD = []; @@ -58,7 +56,7 @@ function BattleState({ idPlayer, game }) { return () => { PartitaObserverSingleton.removeListenerEsiti(updateEsiti); }; - }, [idPlayer, game,]); + }, [idPlayer, game]); console.log("mappa battle state", mappa); console.log("truppe assegnate", troopAssignments); @@ -67,9 +65,11 @@ function BattleState({ idPlayer, game }) { console.log("tipo di evento on click", event); if (event === "add") { - const territorio = player.territories.find((t) => t.name === territoryName) - const continenteTrovato = territorio.continent; - console.log("Continente trovato", continenteTrovato); + const territorio = player.territories.find( + (t) => t.name === territoryName + ); + const continenteTrovato = territorio.continent; + console.log("Continente trovato", continenteTrovato); console.log("Click sinistro"); setTerritorioAttacante(territoryName); console.log("Clicked territory attaccante:", territorioAttacante); @@ -77,22 +77,27 @@ function BattleState({ idPlayer, game }) { console.log("Clicked armate territory:", armateDelTerritorio); setArmateTerritorio(armateDelTerritorio); setSxSelected(true); - setTerritorioDifensore(""); + setTerritorioDifensore(""); const neighbors = game.continents - .find((c) => c.continentId === continenteTrovato) - .territories.find((t) => t.name === territoryName).neighbors; + .find((c) => c.continentId === continenteTrovato) + .territories.find((t) => t.name === territoryName).neighbors; console.log("neighbors", neighbors); const territoriGiocatore = player.territories.map((t) => t.name); - const attackableTerritory = neighbors.filter(neighbor => !territoriGiocatore.includes(neighbor)); + const attackableTerritory = neighbors.filter( + (neighbor) => !territoriGiocatore.includes(neighbor) + ); setTerritoriAttaccabili(attackableTerritory); console.log("territori attaccabili", territoriAttaccabili); - - }else if (event === "addNonOwned" && sxSelected && territoriAttaccabili.includes(territoryName)) { + } else if ( + event === "addNonOwned" && + sxSelected && + territoriAttaccabili.includes(territoryName) + ) { console.log("Click destro"); setTerritorioDifensore(territoryName); console.log("Clicked territory difensore:", territorioDifensore); setSxSelected(false); - } + } }; return (
@@ -115,8 +120,8 @@ function BattleState({ idPlayer, game }) { carriTerritorio={armateTerritorio} territoryAttack={territorioAttacante} territoryDefense={territorioDifensore} - game = {game} - player = {player} + game={game} + player={player} /> ) : ( @@ -131,32 +136,34 @@ function BattleState({ idPlayer, game }) { onTerritoryClick={() => {}} truppeAssegnate={troopAssignments} /> - + )} - { - - Esito dell'Attacco - - - {esiti.isConquered ? ( -

Il territorio è stato conquistato.

- ) : ( -

Il territorio non è stato conquistato.

- )} -

Truppe perse dall'attaccante: {esiti.lostAttTroops}

-

Truppe perse dal difensore: {esiti.lostDefTroops}

-
- - - -
} + { + + + Esito dell'Attacco + + + {esiti.isConquered ? ( +

Il territorio è stato conquistato.

+ ) : ( +

Il territorio non è stato conquistato.

+ )} +

Truppe perse dall'attaccante: {esiti.lostAttTroops}

+

Truppe perse dal difensore: {esiti.lostDefTroops}

+
+ + + +
+ }
); } diff --git a/src/main/app/src/component/mappa/Console.js b/src/main/app/src/component/mappa/Console.js index a21d768..948a286 100644 --- a/src/main/app/src/component/mappa/Console.js +++ b/src/main/app/src/component/mappa/Console.js @@ -1,61 +1,56 @@ - import { useState, useEffect } from "react"; - import { Container, Button, Nav, Navbar} from "react-bootstrap"; - import { GiInvertedDice3 } from "react-icons/gi"; - import AppController from "../../application/AppController"; - - - function Console({ carriTerritorio, territoryAttack, territoryDefense, game, player}) { - const [dadiSelezionati, setDadiSelezionati] = useState([]); - - /*const handleDiceClick = (numDadi) => { - setDadiSelezionati((prevDadiSelezionati) => prevDadiSelezionati + numDadi); - };*/ - - useEffect(() => { - }, []); - - const handleAttack = () => { - - // Find the player who owns the defender territory - const defenderUsername = game.players.find(player => - player.territories.some(territory => territory.name === territoryDefense) - )?.userName; - // Construct the attack request body - const attackBody = { - - attackerTerritory: { - nameTerritory: territoryAttack, - username : player.userName - }, - defenderTerritory: { - nameTerritory: territoryDefense, - username : defenderUsername }, - numAttDice: dadiSelezionati.length - }; - - // Call the AppController method, replace 'performAttack' with your method name - AppController.attack(game.id, attackBody) - console.log("Attacco effettuato"); - - }; - - // const handleShowAlert = () => setShowAlert(true); - - const handleDiceClick = (numDadi) => { - setDadiSelezionati(prevState => { - // Controlla se il dado è già stato selezionato - if (prevState.includes(numDadi)) { - // Rimuove il dado dai selezionati - return prevState.filter(dado => dado !== numDadi); - } else { - // Aggiunge il dado ai selezionati - return [...prevState, numDadi]; - } - }); - }; - - const renderDefendButton = () => { - /* if(game.currentTurn){ +import { useState, useEffect } from "react"; +import { Container, Button, Nav, Navbar } from "react-bootstrap"; +import { GiInvertedDice3 } from "react-icons/gi"; +import AppController from "../../application/AppController"; + +function Console({ + carriTerritorio, + territoryAttack, + territoryDefense, + game, + player, +}) { + const [dadiSelezionati, setDadiSelezionati] = useState([]); + + const handleAttack = () => { + const defenderUsername = game.players.find((player) => + player.territories.some( + (territory) => territory.name === territoryDefense + ) + )?.userName; + // Construct the attack request body + const attackBody = { + attackerTerritory: { + nameTerritory: territoryAttack, + username: player.userName, + }, + defenderTerritory: { + nameTerritory: territoryDefense, + username: defenderUsername, + }, + numAttDice: dadiSelezionati.length, + }; + + // Call the AppController method, replace 'performAttack' with your method name + AppController.attack(game.id, attackBody); + console.log("Attacco effettuato"); + }; + + const handleDiceClick = (numDadi) => { + setDadiSelezionati((prevState) => { + // Controlla se il dado è già stato selezionato + if (prevState.includes(numDadi)) { + // Rimuove il dado dai selezionati + return prevState.filter((dado) => dado !== numDadi); + } else { + // Aggiunge il dado ai selezionati + return [...prevState, numDadi]; + } + }); + }; + + const renderDefendButton = () => { + /* if(game.currentTurn){ const isDefender = game.currentTurn.defenseTerritory?.idOwner === player.userName; const shouldShowDefendButton = !territoryAttack && !territoryDefense && isDefender; @@ -65,78 +60,80 @@ return null; }*/ - }; - - const renderDadi = () => { - if (!territoryAttack || !territoryDefense) { - return null; - } - - let numDadi = 0; - - if (carriTerritorio === 1) { - // Messaggio per non poter attaccare con un solo carro armato - return

Non puoi attaccare con una truppa sul territorio.

; - } - if (carriTerritorio === 2) { - numDadi = 1; - } - - if (carriTerritorio == 3) { - numDadi = 2; - } else { - numDadi = 3; - } - - - // Determina il numero massimo di dadi basato sul numero di carriTerritorio - return ( - <> - {[...Array(numDadi)].map((_, index) => ( - - ))} - - ); - }; - - return ( - - - - - - - - - - - {renderDadi()} - - - {territoryAttack && {territoryAttack}} - {territoryDefense && attacca {territoryDefense}} - {territoryAttack && territoryDefense && dadiSelezionati.length > 0 && ( -
- Attacchi con {dadiSelezionati.length} dadi -
-

Sei sicuro di voler lanciare l'attacco?

- -
-
- )} - {renderDefendButton()} -
- - -
- ); - } - export default Console; + }; + + const renderDadi = () => { + if (!territoryAttack || !territoryDefense) { + return null; + } + + let numDadi = 0; + + if (carriTerritorio === 1) { + // Messaggio per non poter attaccare con un solo carro armato + return

Non puoi attaccare con una truppa sul territorio.

; + } + if (carriTerritorio === 2) { + numDadi = 1; + } + + if (carriTerritorio == 3) { + numDadi = 2; + } else { + numDadi = 3; + } + + return ( + <> + {[...Array(numDadi)].map((_, index) => ( + + ))} + + ); + }; + + return ( + + + + + + + + + + {renderDadi()} + + {territoryAttack && {territoryAttack}} + {territoryDefense && attacca {territoryDefense}} + {territoryAttack && territoryDefense && dadiSelezionati.length > 0 && ( +
+ Attacchi con {dadiSelezionati.length} dadi +
+

Sei sicuro di voler lanciare l'attacco?

+ +
+
+ )} + {renderDefendButton()} +
+
+ ); +} +export default Console; diff --git a/src/main/app/src/component/mappa/EndGameState.js b/src/main/app/src/component/mappa/EndGameState.js new file mode 100644 index 0000000..d4c1e93 --- /dev/null +++ b/src/main/app/src/component/mappa/EndGameState.js @@ -0,0 +1,16 @@ +import React from "react"; +import { Button } from "react-bootstrap"; +import { useNavigate } from "react-router-dom"; + +function EndGameState() { + const { navigate } = useNavigate(); + return ( +
+

Gioco Terminato

+

torna alla Home

+ +
+ ); +} + +export default EndGameState; diff --git a/src/main/app/src/component/mappa/EndTurnState.js b/src/main/app/src/component/mappa/EndTurnState.js new file mode 100644 index 0000000..f7e203d --- /dev/null +++ b/src/main/app/src/component/mappa/EndTurnState.js @@ -0,0 +1,30 @@ +import React from "react"; +import { Button } from "react-bootstrap"; +import { useNavigate } from "react-router-dom"; +import SvgMap from "./SvgMap"; +import Console from "./Console"; + +function EndTurnState({ game }) { + console.log("game in EndTurn", game); + + const handleTerritoryClick = (territoryName, event) => { + console.log("tipo di evento on click", event); + + if (event === "add") { + console.log("Click sinistro"); + } else if (event === "addNonOwned") { + console.log("Click destro"); + } + }; + + // qua logica per passare lo spostamento + + return ( +
+ + +
+ ); +} + +export default EndTurnState; diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java new file mode 100644 index 0000000..bcb968d --- /dev/null +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java @@ -0,0 +1,14 @@ +package com.mvcguru.risiko.maven.eclipse.states; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class BattleStateTest { + + @Test + void test() { + fail("Not yet implemented"); + } + +} From d532edc8cfe2dec0b9f640ea1fc461e5971a57f6 Mon Sep 17 00:00:00 2001 From: Roberto Negro Date: Wed, 21 Feb 2024 18:44:04 +0100 Subject: [PATCH 02/15] Commit cambiamento objectives_medium.json --- src/main/resources/objectives_medium.json | 64 ++++++++++++++++++----- 1 file changed, 51 insertions(+), 13 deletions(-) diff --git a/src/main/resources/objectives_medium.json b/src/main/resources/objectives_medium.json index 4d31caf..1ce799e 100644 --- a/src/main/resources/objectives_medium.json +++ b/src/main/resources/objectives_medium.json @@ -3,42 +3,80 @@ "objective": "Conquistare 12 territori presidiandoli con almeno due armate ciascuno." }, { - "objective": "Conquistare 18 territori." + "objective": "Conquistare 17 territori." }, { - "objective": "Eliminare completamente due giocatori." + "type": "conquerContinent", + "objective": "Conquistare la totalità del Nord America e dell'Africa.", + "continent1": "5", + "continent2": "3" }, { - "objective": "Occupare interamente tre continenti piccoli o inventati." + "type": "conquerContinent", + "objective": "Conquistare la totalità del Nord America e dell'Oceania.", + "continent1": "5", + "continent2": "6" }, { - "objective": "Mantenere il controllo di due continenti per 3 turni consecutivi." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Asia e del Sud America.", + "continent1": "4", + "continent2": "1" }, { - "objective": "Conquistare 5 territori in un solo turno." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Asia e dell'Africa.", + "continent1": "4", + "continent2": "3" }, { - "objective": "Riuscire a scambiare carte obiettivo per rinforzi tre volte in una partita." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Europa, del Sud America e di un terzo continente a scelta.", + "continent1": "5", + "continent2": "1", + "continent3": "7" }, { - "objective": "Vincere con almeno 10 territori che confinano con il mare." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Europa, dell'Oceania e di un terzo continente a scelta.", + "continent1": "2", + "continent2": "1", + "continent3": "7" }, { - "objective": "Conquistare tutti i territori di due continenti specifici." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata rossa, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "RED", + "nTerritory": "17" }, { - "objective": "Accumulare un totale di 30 armate su territori specifici." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata gialla, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "YELLOW", + "nTerritory": "17" }, { - "objective": "Distruggere completamente l'armata di un giocatore in un solo turno." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata verde, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "GREEN", + "nTerritory": "17" }, { - "objective": "Vincere senza perdere più di 5 territori durante la partita, se perdi 5 territori il tuo obiettivo diventa conquistare 18 territori." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata blu, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "BLUE", + "nTerritory": "17" }, { - "objective": "Raggiungere per primi un numero prefissato di 40 armate totali." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata nero, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "BLACK", + "nTerritory": "17" }, { - "objective": "Conquistare un intero continente in un solo turno." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata viola, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "PURPLE", + "nTerritory": "17" } ] From 69fe07c5a6cab4cb5953039ce738a26484ec55ce Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Wed, 21 Feb 2024 20:06:27 +0100 Subject: [PATCH 03/15] Commit continuo classe Test partita --- .../maven/eclipse/actions/AttackRequest.java | 5 +++- .../card/objectives/DestroyArmyObjective.java | 3 ++- .../maven/eclipse/model/player/Player.java | 23 +++++++++++----- .../maven/eclipse/service/FactoryGame.java | 1 + .../maven/eclipse/states/BattleState.java | 27 ++++--------------- .../maven/eclipse/states/GameSetupState.java | 3 ++- .../maven/eclipse/states/GameState.java | 2 +- .../maven/eclipse/states/LobbyStateTest.java | 24 ++++++++++++++++- 8 files changed, 54 insertions(+), 34 deletions(-) diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/AttackRequest.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/AttackRequest.java index 7707f0d..51dd68b 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/AttackRequest.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/AttackRequest.java @@ -2,7 +2,10 @@ import java.io.IOException; import com.mvcguru.risiko.maven.eclipse.controller.body_request.AttackRequestBody; +import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; +import com.mvcguru.risiko.maven.eclipse.exception.GameException; +import com.mvcguru.risiko.maven.eclipse.exception.UserException; import com.mvcguru.risiko.maven.eclipse.states.GameState; import lombok.Data; @@ -16,7 +19,7 @@ public class AttackRequest extends ActionPlayer{ private AttackRequestBody requestAttackBody; @Override - public void accept(GameState gameState) throws FullGameException, IOException { + public void accept(GameState gameState) throws FullGameException, IOException, GameException, DatabaseConnectionException, UserException { gameState.onActionPlayer(this); } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java index 82d40e5..b9f03a3 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java @@ -35,7 +35,8 @@ public boolean isComplete(IGame game, String unsernameDefender) { if (defender.getTerritories().size() == 0 && defender.getColor() == colorArmy) { return true; } - if (attacker.getColor() == colorArmy || colorOwner.getTerritories().size() == 0) { +// if (attacker.getColor() == colorArmy || colorOwner.getTerritories().size() == 0) { + if (attacker.getColor() == colorArmy) { if (attacker.getTerritories().size() >= nTerritory) { return true; } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java index 0d1197e..31b794e 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java @@ -2,11 +2,19 @@ import java.io.Serializable; import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.fasterxml.jackson.annotation.JsonIgnore; +import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; +import com.mvcguru.risiko.maven.eclipse.exception.GameException; +import com.mvcguru.risiko.maven.eclipse.exception.UserException; import com.mvcguru.risiko.maven.eclipse.model.IGame; import com.mvcguru.risiko.maven.eclipse.model.Territory; import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard; +import com.mvcguru.risiko.maven.eclipse.service.GameRepository; import lombok.AllArgsConstructor; import lombok.Data; @@ -17,7 +25,8 @@ @SuperBuilder @AllArgsConstructor @NoArgsConstructor -public class Player implements Serializable{ +public class Player implements Serializable{ + Logger LOGGER = LoggerFactory.getLogger(Player.class); private String userName; @@ -41,12 +50,12 @@ public enum PlayerColor { } public Territory getTerritoryByName(String name) { - for (Territory territory : territories) { - if (territory.getName().equalsIgnoreCase(name)) { - return territory; - } - } - return null; + try { + return GameRepository.getInstance().getTerritory(userName, gameId, name); + } catch (GameException | DatabaseConnectionException | UserException e) { + LOGGER.error(e.getMessage()); + } + return null; } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java index b642100..8cb80b1 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java @@ -19,6 +19,7 @@ import com.mvcguru.risiko.maven.eclipse.model.Game; import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration; import com.mvcguru.risiko.maven.eclipse.model.IGame; +import com.mvcguru.risiko.maven.eclipse.model.Turn; import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration.GameMode; import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java index a058cbf..721c2b8 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java @@ -22,38 +22,21 @@ public class BattleState extends GameState{ private static final Logger LOGGER = LoggerFactory.getLogger(BattleState.class); @Override - public void onActionPlayer(AttackRequest attackRequest) { - LOGGER.info("attackRequest.getRequestAttackBody()", attackRequest.getRequestAttackBody()); - LOGGER.info("Numero dadi attacco: {}", attackRequest.getRequestAttackBody().getNumAttDice()); + public void onActionPlayer(AttackRequest attackRequest) throws GameException, DatabaseConnectionException, UserException { - LOGGER.info("Territorio attaccante: {}", attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory()); - for (Territory t : attackRequest.getPlayer().getTerritories()) { - LOGGER.info("Territorio action player: {}", t.getName()); - } game.getCurrentTurn().setNumAttDice(attackRequest.getRequestAttackBody().getNumAttDice()); - LOGGER.info("Numero dadi attacco: {}", game.getCurrentTurn().getNumAttDice()); - LOGGER.info("Turno corrente: {}", game.getCurrentTurn().getAttackerTerritory()); game.getCurrentTurn().setAttackerTerritory( attackRequest.getPlayer().getTerritoryByName(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory())); - LOGGER.info("Turno corrente: {}", game.getCurrentTurn().getAttackerTerritory()); game.getCurrentTurn().setDefenderTerritory( game.findPlayerByUsername(attackRequest.getRequestAttackBody().getDefenderTerritory().getUsername()).getTerritoryByName( attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory())); - LOGGER.info("Territorio attaccante: {}", game.getCurrentTurn().getAttackerTerritory().getName()); - LOGGER.info("Territorio difensore: {}", game.getCurrentTurn().getDefenderTerritory().getName()); - try { - GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), game.getCurrentTurn().getNumAttDice()); - LOGGER.info("Numero dadi attacco aggiornato nel database"); - GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), game.getCurrentTurn().getAttackerTerritory()); - LOGGER.info("Territorio attaccante aggiornato nel database"); - GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), game.getCurrentTurn().getDefenderTerritory()); - LOGGER.info("Territorio difensore aggiornato nel database"); - } catch (GameException | DatabaseConnectionException | UserException e) { - LOGGER.error("Errore nell'aggiornamento dei dadi dell'attacco"); - } + + GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), game.getCurrentTurn().getNumAttDice()); + GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), game.getCurrentTurn().getAttackerTerritory()); + GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), game.getCurrentTurn().getDefenderTerritory()); } @Override diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupState.java index ed320c7..ef03f05 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupState.java @@ -59,9 +59,10 @@ public void onActionPlayer(TerritorySetup action) throws GameException, Database return; } } + game.startGame(); game.setState(StartTurnState.builder().game(game).build()); GameRepository.getInstance().updateState(game.getId(), game.getState()); - game.startGame(); + } @Override diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java index b32cf8b..53f6a4f 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java @@ -55,7 +55,7 @@ public void onActionPlayer(TerritorySetup territorySetup) throws GameException, public void onActionPlayer(ComboRequest comboRequest) {} - public void onActionPlayer(AttackRequest attackRequest) {} + public void onActionPlayer(AttackRequest attackRequest) throws GameException, DatabaseConnectionException, UserException {} public void setUpGame() throws GameException, DatabaseConnectionException, UserException {} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java index 4f534ae..6a357d0 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java @@ -13,10 +13,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.mvcguru.risiko.maven.eclipse.actions.AttackRequest; import com.mvcguru.risiko.maven.eclipse.actions.ComboRequest; import com.mvcguru.risiko.maven.eclipse.actions.GameEntry; import com.mvcguru.risiko.maven.eclipse.actions.GameExit; import com.mvcguru.risiko.maven.eclipse.actions.TerritorySetup; +import com.mvcguru.risiko.maven.eclipse.actions.TurnSetUp; +import com.mvcguru.risiko.maven.eclipse.controller.body_request.AttackRequestBody; +import com.mvcguru.risiko.maven.eclipse.controller.body_request.BattleBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.ComboRequestBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.SetUpBody; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; @@ -181,11 +185,29 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep } SetUpBody setUpBody3 = SetUpBody.builder().territories(territoryBodies3).build(); - TerritorySetup territorySetup3 = TerritorySetup.builder().player(player1).setUpBody(setUpBody3).build(); + TurnSetUp territorySetup3 = TurnSetUp.builder().player(player1).setUpBody(setUpBody3).build(); game.getState().onActionPlayer(territorySetup3); + assertEquals(game.getState().getClass().toString(), BattleState.class.toString()); + // BattleState + BattleBody battleBodyAttacker = BattleBody.builder().nameTerritory("Brasile").username(player1.getUserName()).build(); + BattleBody battleBody2Difender = BattleBody.builder().nameTerritory("Argentina").username(player2.getUserName()).build(); + + + + AttackRequestBody attackRequestBody = AttackRequestBody.builder().attackerTerritory(battleBodyAttacker).defenderTerritory(battleBody2Difender).numAttDice(1).build(); + AttackRequest attackRequest = AttackRequest.builder().player(player1).requestAttackBody(attackRequestBody).build(); + game.getState().onActionPlayer(attackRequest); + + LOGGER.info("Attacker: {}", game.getCurrentTurn()); + + assertEquals(game.getCurrentTurn().getAttackerTerritory().getName(), "Brasile"); + assertEquals(game.getCurrentTurn().getDefenderTerritory().getName(), "Argentina"); + assertEquals(game.getCurrentTurn().getNumAttDice(), 1); + + } From 4dcf7f020213b360a84f710225ec7266b324929d Mon Sep 17 00:00:00 2001 From: Andrea Malnati Date: Wed, 21 Feb 2024 21:40:33 +0100 Subject: [PATCH 04/15] Continuo test partita --- .../maven/eclipse/model/player/Player.java | 7 +++---- .../risiko/maven/eclipse/states/BattleState.java | 16 +++++++++------- .../maven/eclipse/states/LobbyStateTest.java | 7 +++++++ 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java index 31b794e..99d7cb3 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java @@ -50,10 +50,9 @@ public enum PlayerColor { } public Territory getTerritoryByName(String name) { - try { - return GameRepository.getInstance().getTerritory(userName, gameId, name); - } catch (GameException | DatabaseConnectionException | UserException e) { - LOGGER.error(e.getMessage()); + for (Territory t : territories) { + if (t.getName().equals(name)) + return t; } return null; } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java index 721c2b8..a87117d 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java @@ -25,22 +25,24 @@ public class BattleState extends GameState{ public void onActionPlayer(AttackRequest attackRequest) throws GameException, DatabaseConnectionException, UserException { game.getCurrentTurn().setNumAttDice(attackRequest.getRequestAttackBody().getNumAttDice()); - game.getCurrentTurn().setAttackerTerritory( - attackRequest.getPlayer().getTerritoryByName(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory())); - - game.getCurrentTurn().setDefenderTerritory( - - game.findPlayerByUsername(attackRequest.getRequestAttackBody().getDefenderTerritory().getUsername()).getTerritoryByName( - attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory())); + + game.getCurrentTurn().setAttackerTerritory(attackRequest.getPlayer() + .getTerritoryByName(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory())); + + game.getCurrentTurn().setDefenderTerritory(game.findPlayerByUsername(attackRequest.getRequestAttackBody().getDefenderTerritory() + .getUsername()).getTerritoryByName(attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory())); GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), game.getCurrentTurn().getNumAttDice()); + GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), game.getCurrentTurn().getAttackerTerritory()); + GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), game.getCurrentTurn().getDefenderTerritory()); } @Override public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException { + System.out.println("DEFENCE REQUEST -------------------------------------------"); game.getCurrentTurn().setNumDefDice(defenceRequest.getDefenderRequestBody().getNumDefDice()); GameRepository.getInstance().updateNumDefenseDice(game.getCurrentTurn(), game.getCurrentTurn().getNumDefDice()); game.getCurrentTurn().attack(); diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java index 6a357d0..5edd6c6 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java @@ -15,6 +15,7 @@ import com.mvcguru.risiko.maven.eclipse.actions.AttackRequest; import com.mvcguru.risiko.maven.eclipse.actions.ComboRequest; +import com.mvcguru.risiko.maven.eclipse.actions.DefenceRequest; import com.mvcguru.risiko.maven.eclipse.actions.GameEntry; import com.mvcguru.risiko.maven.eclipse.actions.GameExit; import com.mvcguru.risiko.maven.eclipse.actions.TerritorySetup; @@ -22,6 +23,7 @@ import com.mvcguru.risiko.maven.eclipse.controller.body_request.AttackRequestBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.BattleBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.ComboRequestBody; +import com.mvcguru.risiko.maven.eclipse.controller.body_request.DefenceRequestBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.SetUpBody; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; @@ -207,6 +209,11 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep assertEquals(game.getCurrentTurn().getDefenderTerritory().getName(), "Argentina"); assertEquals(game.getCurrentTurn().getNumAttDice(), 1); + DefenceRequestBody defenceRequestBody = DefenceRequestBody.builder().username(player2.getUserName()).numDefDice(1).build(); + + DefenceRequest defenceRequest = DefenceRequest.builder().defenderRequestBody(defenceRequestBody).build(); + + game.getState().onActionPlayer(defenceRequest); } From 5d760486e13c19a9116fefc4cc625613aa32ccdb Mon Sep 17 00:00:00 2001 From: Radaelli Lorenzo Date: Wed, 21 Feb 2024 22:40:46 +0100 Subject: [PATCH 05/15] continuo implementazione battle state e implementazione console di difesa --- src/main/app/src/application/AppController.js | 152 ++++++++++-------- .../app/src/component/mappa/BattleState.js | 66 +++++--- .../app/src/component/mappa/ConsoleDifesa.js | 37 +++++ .../app/src/component/mappa/SetupStateMap.js | 43 ++--- .../app/src/component/mappa/StartTurnState.js | 12 +- .../eclipse/controller/EventController.java | 1 + .../maven/eclipse/states/LobbyStateTest.java | 2 +- 7 files changed, 196 insertions(+), 117 deletions(-) create mode 100644 src/main/app/src/component/mappa/ConsoleDifesa.js diff --git a/src/main/app/src/application/AppController.js b/src/main/app/src/application/AppController.js index b5ebea5..1a11577 100644 --- a/src/main/app/src/application/AppController.js +++ b/src/main/app/src/application/AppController.js @@ -10,7 +10,7 @@ class AppController { // Aggiungi le sottoscrizioni ai topic qui, se necessario }, onDisconnect: () => { - console.log("Disconnected from STOMP"); + console.log("Disconnected from STOMP"); }, // Altri eventi e configurazioni... }); @@ -125,75 +125,93 @@ class AppController { console.error("Client STOMP non connesso"); } } - - subscribeToEsitiPartita(idPartita, nickname) { - if (!this.client || !this.client.connected) { - console.error("Client STOMP non connesso"); - return; - } - this.client.subscribe(`/topic/partite/${idPartita}/${nickname}`, (message) => { - PartitaObserverSingleton.notifyListenersEsiti(JSON.parse(message.body)); - console.log("Esito attacco ricevuto:", JSON.parse(message.body)); - }); - } - - unsubscribeToEsitiPartita(idPartita, nickname) { - if (this.client && this.client.connected) { - this.client.unsubscribe(`/topic/partite/${idPartita}/${nickname}`); - } else { - console.error("Client STOMP non connesso"); - } - } - - setUpPartita(idPartita, territoriAssegnati) { - if (!this.client || !this.client.connected) { - console.error("Client STOMP non connesso"); - return; - } - console.log("territoriAssegnatinellotomp", territoriAssegnati); - // Assicurati che territoriAssegnati sia un array di oggetti che corrispondono - // alla struttura di TerritoryBody, ovvero con i campi `name` e `troops`. - - console.log("setUpBodystomp", territoriAssegnati); - - // Pubblicazione del messaggio al topic di setup della partita - this.client.publish({ - destination: `/app/partite/${idPartita}/confermaSetup`, - body: JSON.stringify(territoriAssegnati), - }); - - console.log(`Setup per la partita ${idPartita} inviato:`, territoriAssegnati); -} - setUpTurno(idPartita, territoriAssegnati) { - if (!this.client || !this.client.connected) { - console.error("Client STOMP non connesso"); - return; - } - console.log("territoriAssegnati", territoriAssegnati); - this.client.publish({ - destination: `/app/partite/${idPartita}/turnAssignation`, - body: JSON.stringify(territoriAssegnati), - }); - console.log(`Setup per il turno della partita: ${idPartita} inviato:`, territoriAssegnati); - } - - attack(idPartita, attackBody) { - if (!this.client || !this.client.connected) { - console.error("Client STOMP non connesso"); - return; - } - console.log("attackBody", attackBody); - this.client.publish({ - destination: `/app/partite/${idPartita}/attack`, - body: JSON.stringify(attackBody), - }); - console.log(`Attacco per la partita ${idPartita} inviato:`, attackBody); - } + subscribeToEsitiPartita(idPartita, nickname) { + if (!this.client || !this.client.connected) { + console.error("Client STOMP non connesso"); + return; + } + this.client.subscribe( + `/topic/partite/${idPartita}/${nickname}`, + (message) => { + PartitaObserverSingleton.notifyListenersEsiti(JSON.parse(message.body)); + console.log("Esito attacco ricevuto:", JSON.parse(message.body)); + } + ); + } -} + unsubscribeToEsitiPartita(idPartita, nickname) { + if (this.client && this.client.connected) { + this.client.unsubscribe(`/topic/partite/${idPartita}/${nickname}`); + } else { + console.error("Client STOMP non connesso"); + } + } + + setUpPartita(idPartita, territoriAssegnati) { + if (!this.client || !this.client.connected) { + console.error("Client STOMP non connesso"); + return; + } + console.log("territoriAssegnatinellotomp", territoriAssegnati); + // Assicurati che territoriAssegnati sia un array di oggetti che corrispondono + // alla struttura di TerritoryBody, ovvero con i campi `name` e `troops`. + + console.log("setUpBodystomp", territoriAssegnati); + + // Pubblicazione del messaggio al topic di setup della partita + this.client.publish({ + destination: `/app/partite/${idPartita}/confermaSetup`, + body: JSON.stringify(territoriAssegnati), + }); + + console.log( + `Setup per la partita ${idPartita} inviato:`, + territoriAssegnati + ); + } - + setUpTurno(idPartita, territoriAssegnati) { + if (!this.client || !this.client.connected) { + console.error("Client STOMP non connesso"); + return; + } + console.log("territoriAssegnati", territoriAssegnati); + this.client.publish({ + destination: `/app/partite/${idPartita}/turnAssignation`, + body: JSON.stringify(territoriAssegnati), + }); + console.log( + `Setup per il turno della partita: ${idPartita} inviato:`, + territoriAssegnati + ); + } + + attack(idPartita, attackBody) { + if (!this.client || !this.client.connected) { + console.error("Client STOMP non connesso"); + return; + } + console.log("attackBody", attackBody); + this.client.publish({ + destination: `/app/partite/${idPartita}/attack`, + body: JSON.stringify(attackBody), + }); + console.log(`Attacco per la partita ${idPartita} inviato:`, attackBody); + } + + defend(idPartita, defenceBody) { + if (!this.client || !this.client.connected) { + console.error("Client STOMP non connesso"); + return; + } + this.client.publish({ + destination: `/app/partite/${idPartita}/defence`, + body: JSON.stringify(defenceBody), + }); + console.log("controller difesa"); + } +} // Esporta l'istanza per utilizzarla nell'app const appController = new AppController(); diff --git a/src/main/app/src/component/mappa/BattleState.js b/src/main/app/src/component/mappa/BattleState.js index c9662f9..edaa958 100644 --- a/src/main/app/src/component/mappa/BattleState.js +++ b/src/main/app/src/component/mappa/BattleState.js @@ -4,6 +4,7 @@ import SvgMap from "./SvgMap"; import Console from "../mappa/Console"; import { Alert, Modal, Button } from "react-bootstrap"; import PartitaObserverSingleton from "../../application/PartitaObserverSingleton"; +import ConsoleDifesa from "./ConsoleDifesa"; function BattleState({ idPlayer, game }) { const [mappa, setMappa] = useState([]); @@ -20,8 +21,12 @@ function BattleState({ idPlayer, game }) { const [showAlert, setShowAlert] = useState(true); const [esiti, setEsiti] = useState({}); const [showEsiti, setShowEsiti] = useState(false); + const [isDefenderTerritory, setIsDefenderTerritory] = useState(null); + const [playerUnderAttack, setPlayerUnderAttack] = useState(); + const [countryUnderAttack, setCountryUnderAttack] = useState(""); + const [IdGioco, setIdGioco] = useState(); - const handleClose = () => setShowEsiti(false); + // const handleClose = () => setShowEsiti(false); useEffect(() => { function updateEsiti(esiti) { @@ -30,12 +35,17 @@ function BattleState({ idPlayer, game }) { setShowEsiti(true); } + setIdGioco(game.id); + PartitaObserverSingleton.addListenerEsiti(updateEsiti); const pathD = []; const newTroopAssignments = {}; setIsPlayersTurn(game.currentTurn.player.userName === idPlayer); + const isDifTerr = game.currentTurn.defenderTerritory; + setIsDefenderTerritory(isDifTerr); + console.log("isDifTerr", isDifTerr); game.players.forEach((player) => { player.territories.forEach((territory) => { @@ -53,13 +63,30 @@ function BattleState({ idPlayer, game }) { const currentPlayer = game.players.find((p) => p.userName === idPlayer); setPlayer(currentPlayer); + + if (isDefenderTerritory) { + const sottoAttacco = game.currentTurn.defenderTerritory.idOwner; + setPlayerUnderAttack(sottoAttacco); + console.log("player sottoAttacco", sottoAttacco); + + const CountrysottoAttacco = game.currentTurn.defenderTerritory.idOwner; + setCountryUnderAttack(CountrysottoAttacco); + console.log("country Under Attack", CountrysottoAttacco); + } + return () => { PartitaObserverSingleton.removeListenerEsiti(updateEsiti); }; }, [idPlayer, game]); - console.log("mappa battle state", mappa); - console.log("truppe assegnate", troopAssignments); + console.log("playerUnderAttack", playerUnderAttack); + + { + player && console.log("player in battleState", player); + } + { + player && console.log("game in battleState", game); + } const handleTerritoryClick = (territoryName, event) => { console.log("tipo di evento on click", event); @@ -143,27 +170,18 @@ function BattleState({ idPlayer, game }) { /> )} - { - - - Esito dell'Attacco - - - {esiti.isConquered ? ( -

Il territorio è stato conquistato.

- ) : ( -

Il territorio non è stato conquistato.

- )} -

Truppe perse dall'attaccante: {esiti.lostAttTroops}

-

Truppe perse dal difensore: {esiti.lostDefTroops}

-
- - - -
- } + + {isDefenderTerritory && + player.userName === playerUnderAttack && + console.log( + "sei tu sotto attacco", + player.userName === playerUnderAttack + )} + {isDefenderTerritory && player.userName === playerUnderAttack && ( +
+ +
+ )} ); } diff --git a/src/main/app/src/component/mappa/ConsoleDifesa.js b/src/main/app/src/component/mappa/ConsoleDifesa.js new file mode 100644 index 0000000..21dd48e --- /dev/null +++ b/src/main/app/src/component/mappa/ConsoleDifesa.js @@ -0,0 +1,37 @@ +import React, { useState } from "react"; +import { Alert, Button, Container } from "react-bootstrap"; +import appController from "../../application/AppController"; + +function ConsoleDifesa({ idPartita, difendente }) { + const [numeroDadi, setNumeroDadi] = useState(0); + + const handleDice = () => { + setNumeroDadi(numeroDadi + 1); + + console.log("numeroDadi", numeroDadi); + }; + const handleDefense = () => { + const oggettoDifesa = { + numDefDice: numeroDadi, + username: difendente, + }; + + appController.defend(idPartita, oggettoDifesa); + }; + + return ( + + Sei sotto attacco +
+ + + +
+
+ +
+
+ ); +} + +export default ConsoleDifesa; diff --git a/src/main/app/src/component/mappa/SetupStateMap.js b/src/main/app/src/component/mappa/SetupStateMap.js index e285f8b..03e8fb2 100644 --- a/src/main/app/src/component/mappa/SetupStateMap.js +++ b/src/main/app/src/component/mappa/SetupStateMap.js @@ -109,26 +109,31 @@ function SetUpStateMap({ idPlayer, giocatori, game }) { {console.log("player in setup", player)} {console.log("player name in setup", player.userName)} {console.log("player color in setup", player.color)} - {player && {player.objective.objective}} {console.log("player objective in setup", player.objective.objective)} - -
- Il colore delle tue truppe è il -
-
- -

- posiziona le truppe in base al tuo obbiettivo, utilizza il click - sinistro per aggiungere delle truppe al territorio e utilizza il click - destro per rimuoverle -

+ {troopsToAssign && ( + +
+ Il colore delle tue truppe è il +
+
+ +

+ posiziona le truppe in base al tuo obbiettivo, utilizza il click + sinistro per aggiungere delle truppe al territorio e utilizza il + click destro per rimuoverle +

+ ti rimangono da posizionare + {troopsToAssign} + truppe +
+ )} p.userName === idPlayer); setObjective(isPlayer.objective.objective); - // setObjective(game.deckObjective.cards[0].objective); }, [game, idPlayer]); console.log("objective", objective); @@ -145,13 +144,14 @@ function StartTurnState({ idPlayer, game }) { ) : (
- {objective && ( - Obiettivo del Gioco: {objective} + {troopsToAdd && ( + + hai ricevuto + {troopsToAdd} + truppe + )} - posiziona: - {troopsToAdd} - truppe sulla mappa Date: Wed, 21 Feb 2024 22:42:27 +0100 Subject: [PATCH 06/15] continuo implementazione battleState e implementazione console di difesa --- .../component/partita/CarouselComponent.js | 100 ------- .../app/src/component/partita/CreaPartita.js | 141 ---------- src/main/app/src/pages/NewPartita.js | 256 ----------------- src/main/app/src/pages/Partita.js | 261 +++++++++++++++--- src/main/app/src/router/Root.js | 7 +- 5 files changed, 229 insertions(+), 536 deletions(-) delete mode 100644 src/main/app/src/component/partita/CarouselComponent.js delete mode 100644 src/main/app/src/component/partita/CreaPartita.js delete mode 100644 src/main/app/src/pages/NewPartita.js diff --git a/src/main/app/src/component/partita/CarouselComponent.js b/src/main/app/src/component/partita/CarouselComponent.js deleted file mode 100644 index 0b06ac5..0000000 --- a/src/main/app/src/component/partita/CarouselComponent.js +++ /dev/null @@ -1,100 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { Card, Container, Carousel, Button } from "react-bootstrap"; -import AppController from "../../application/AppController"; -import "../../styles/carouselStyle.css"; -import { useNavigate, useParams } from "react-router-dom"; -import PartitaObserverSingleton from "../../application/PartitaObserverSingleton"; - -function CarouselComponent() { - const [index, setIndex] = useState(0); - const [lobbies, setLobbies] = useState([]); - const navigate = useNavigate(); - const { id } = useParams(); - - const uniscitiAllaLobby = (idPartita) => { - let effectiveNickname = id; - if (!effectiveNickname || effectiveNickname === "null") { - effectiveNickname = `Ospite_${Date.now()}`; - } - try { - AppController.entraInPartita(idPartita, effectiveNickname); - navigate(`/lobby/${idPartita}?nickname=${effectiveNickname}`); - } catch (error) { - alert("Errore: " + error.message); // Mostra un popup con l'errore - console.error("Errore durante l'entrata nella partita:", error); - } - }; - - useEffect(() => { - const fetchData = async () => { - try { - const data = await AppController.getPartite(); - setLobbies(data); - console.log("Lobby creata con successo!", data); - } catch (error) { - console.error("Error:", error); - console.log("Creazione lobby fallita. Per favore, riprova."); - } - }; - - fetchData(); - - // Funzione di callback per aggiornare le lobbies quando una nuova partita viene creata - const updatePartita = () => { - console.log("Rilevata nuova partita, aggiornamento lobbies..."); - fetchData(); // Richiama fetchData per ottenere l'elenco aggiornato delle lobbies - }; - - // Registra l'oggetto listener in PartitaObserverSingleton - PartitaObserverSingleton.addListener({ updatePartita }); - }, []); // Dipendenze vuote indicano che questo effetto viene eseguito solo al montaggio e smontaggio - - const handleSelect = (selectedIndex) => { - setIndex(selectedIndex); - }; - - return ( - - {lobbies.length > 0 ? ( - - {console.log("lobby in carousel", lobbies)} - {lobbies.map((lobby) => ( - - - - -
Partita ID: {lobby.id}
-
- -

- Difficoltà: {lobby.configuration.difficolta} -

-

- Mappa: {lobby.configuration.nomeMappa} -

-

- Giocatori: {lobby.players.length}/ - {lobby.configuration.players} -

- -
-
-
-
- ))} -
- ) : ( -

Nessuna partita disponibile

- )} -
- ); -} - -export default CarouselComponent; diff --git a/src/main/app/src/component/partita/CreaPartita.js b/src/main/app/src/component/partita/CreaPartita.js deleted file mode 100644 index 2c13340..0000000 --- a/src/main/app/src/component/partita/CreaPartita.js +++ /dev/null @@ -1,141 +0,0 @@ -import React, { useState } from "react"; -import { Button, Form, Container } from "react-bootstrap"; -import AppController from "../../application/AppController"; -import { useParams } from "react-router-dom"; - -function CreaPartita() { - const [difficolta, setDifficolta] = useState(""); - const [players, setPlayers] = useState(""); - const [nomeLobby, setNomeLobby] = useState(""); - const [isLobbyCreated, setIsLobbyCreated] = useState(""); - const { id } = useParams(); - - const handleDifficolta = (e) => { - setDifficolta(e.target.value); - }; - - const handlePlayersNumber = () => { - switch (difficolta) { - case "EASY": - return [ - , - , - , - ]; - case "MEDIUM": - return [ - , - , - , - , - , - ]; - case "HARD": - return [ - , - , - , - , - , - ]; - default: - return []; - } - }; - - const handleSubmit = async (e) => { - e.preventDefault(); - // Rimosso il riferimento a this.state, non necessario in un componente funzionale - const configuration = { - difficolta, - players: parseInt(players), - nomeLobby, - }; - try { - const result = await AppController.creaPartita(configuration); // Assicurati che questo sia il nome corretto del metodo - setIsLobbyCreated(`Lobby creata con successo! ID Lobby: ${result.id.id}`); // Presumendo che result.id sia l'oggetto che contiene l'id - } catch (error) { - setIsLobbyCreated(`Errore nella creazione della lobby: ${error.message}`); - } - }; - - return ( -
-

Crea la tua lobby

-
- - - - - - - - - - {difficolta && ( - - setPlayers(e.target.value)} - > - - {handlePlayersNumber()} - - - )} - - - setNomeLobby(e.target.value)} - /> - - - - - -
- {isLobbyCreated &&

{isLobbyCreated}

} -
- ); -} - -export default CreaPartita; diff --git a/src/main/app/src/pages/NewPartita.js b/src/main/app/src/pages/NewPartita.js deleted file mode 100644 index 662089c..0000000 --- a/src/main/app/src/pages/NewPartita.js +++ /dev/null @@ -1,256 +0,0 @@ -import React from "react"; -import { - Button, - Form, - Card, - Carousel, - Container, - Alert, -} from "react-bootstrap"; -import AppController from "../application/AppController"; -import { withAuth } from "../auth/AuthContext"; -import { useNavigate, useParams } from "react-router-dom"; -import "../styles/carouselStyle.css"; - -function NewPartitaPage() { - const params = useParams(); - const navigate = useNavigate(); - - return ; -} - -class NewPartita extends React.Component { - constructor(props) { - super(props); - this.state = { - difficolta: "", - players: "", - nomeMappa: "", - isLobbyCreated: "", - lobbies: [], - index: 0, - }; - } - - componentDidMount() { - this.fetchLobbies(); - } - - fetchLobbies = async () => { - try { - const data = await AppController.getPartite(); - console.log("data partita", data); - this.setState({ lobbies: data }); - } catch (error) { - console.error("Error:", error); - } - }; - - handleDifficolta = (e) => { - this.setState({ difficolta: e.target.value }); - }; - - handlePlayersNumber = (e) => { - this.setState({ players: e.target.value }); - }; - - handleNomeLobby = (e) => { - this.setState({ nomeMappa: e.target.value }); - }; - - handleSubmit = async (e) => { - e.preventDefault(); - const { difficolta, players, nomeMappa } = this.state; - - if (!difficolta || !players || !nomeMappa) { - this.setState({ - isLobbyCreated: "Per favore, completa tutti i campi richiesti.", - }); - return; - } - - const configuration = { - difficolta, - players: parseInt(players), - nomeMappa, - }; - try { - const result = await AppController.creaPartita(configuration); - this.setState({ - // isLobbyCreated: `Lobby creata con successo! ID Lobby: ${result.id}`, - isLobbyCreated: `Lobby creata con successo!`, - }); - - this.fetchLobbies(); - } catch (error) { - this.setState({ - isLobbyCreated: `Errore nella creazione della lobby: ${error.message}`, - }); - } - }; - - handleSelect = (selectedIndex) => { - this.setState({ index: selectedIndex }); - }; - - uniscitiAllaLobby = (idPartita) => { - let effectiveNickname = this.props.params.id; - if (!effectiveNickname || effectiveNickname === "null") { - effectiveNickname = `Ospite_${Date.now()}`; - } - try { - AppController.entraInPartita(idPartita, effectiveNickname); - //AppController.subscribeToEsitiPartita(idPartita, effectiveNickname); - this.props.navigate(`/lobby/${idPartita}?nickname=${effectiveNickname}`); - } catch (error) { - alert("Errore: " + error.message); // Mostra un popup con l'errore - console.error("Errore durante l'entrata nella partita:", error); - } - }; - - renderLobbyOptions = () => { - const { difficolta } = this.state; - switch (difficolta) { - case "EASY": - return [2, 3, 4].map((num) => ( - - )); - case "MEDIUM": - case "HARD": - return [2, 3, 4, 5, 6].map((num) => ( - - )); - default: - return []; - } - }; - - renderCarousel = () => { - const { lobbies, index } = this.state; -

..caricamento Lobby in corso..

; - return lobbies.length > 0 ? ( - - {lobbies.map((lobby) => ( - - - -
Partita ID: {lobby.id}
-
- -

Difficoltà: {lobby.configuration.difficolta}

-

Nome Lobby: {lobby.configuration.nomeMappa}

-

- Giocatori: {lobby.players.length}/ - {lobby.configuration.players} -

- {/* Implementa qui la funzione per unirsi alla lobby se necessario */} - -
-
-
- ))} -
- ) : ( -

Nessuna partita disponibile

- ); - }; - - render() { - const { difficolta, nomeMappa, isLobbyCreated } = this.state; - return ( -
- - - - Crea la tua Lobby personalizzata - -
- - Difficoltà - - - - - - - - - {difficolta && ( - - Numero di Giocatori - - - {this.renderLobbyOptions()} - - - )} - - - Nome Lobby - - - - -
-
-
- {isLobbyCreated && ( -

- {isLobbyCreated} -

- )} - - {this.renderCarousel()} - -
- ); - } -} - -export default withAuth(NewPartitaPage); diff --git a/src/main/app/src/pages/Partita.js b/src/main/app/src/pages/Partita.js index c06496b..0375d8f 100644 --- a/src/main/app/src/pages/Partita.js +++ b/src/main/app/src/pages/Partita.js @@ -1,56 +1,249 @@ import React from "react"; -import { Button, Container } from "react-bootstrap"; -import CreaPartita from "../component/partita/CreaPartita"; +import { Button, Form, Card, Carousel, Container } from "react-bootstrap"; +import AppController from "../application/AppController"; import { withAuth } from "../auth/AuthContext"; -import CarouselComponent from "../component/partita/CarouselComponent"; +import { useNavigate, useParams } from "react-router-dom"; +import "../styles/carouselStyle.css"; + +function PartitaPage() { + const params = useParams(); + const navigate = useNavigate(); + + return ; +} class Partita extends React.Component { constructor(props) { super(props); this.state = { - mostraCreaLobby: false, - mostraCarousel: false, + difficolta: "", + players: "", + nomeMappa: "", + isLobbyCreated: "", + lobbies: [], + index: 0, }; } - handleCreaLobby = () => { - this.setState({ mostraCreaLobby: true }); + componentDidMount() { + this.fetchLobbies(); + } + + fetchLobbies = async () => { + try { + const data = await AppController.getPartite(); + console.log("data partita", data); + this.setState({ lobbies: data }); + } catch (error) { + console.error("Error:", error); + } }; - render() { - const { user } = this.props; - console.log("user in partita", user); + handleDifficolta = (e) => { + this.setState({ difficolta: e.target.value }); + }; + + handlePlayersNumber = (e) => { + this.setState({ players: e.target.value }); + }; + + handleNomeLobby = (e) => { + this.setState({ nomeMappa: e.target.value }); + }; + + handleSubmit = async (e) => { + e.preventDefault(); + const { difficolta, players, nomeMappa } = this.state; + + if (!difficolta || !players || !nomeMappa) { + this.setState({ + isLobbyCreated: "Per favore, completa tutti i campi richiesti.", + }); + return; + } + + const configuration = { + difficolta, + players: parseInt(players), + nomeMappa, + }; + try { + const result = await AppController.creaPartita(configuration); + console.log(result); + this.setState({ + isLobbyCreated: `Lobby creata con successo!`, + }); + this.fetchLobbies(); + } catch (error) { + this.setState({ + isLobbyCreated: `Errore nella creazione della lobby: ${error.message}`, + }); + } + }; + + handleSelect = (selectedIndex) => { + this.setState({ index: selectedIndex }); + }; + + uniscitiAllaLobby = (idPartita) => { + let effectiveNickname = this.props.params.id; + if (!effectiveNickname || effectiveNickname === "null") { + effectiveNickname = `Ospite_${Date.now()}`; + } + try { + AppController.entraInPartita(idPartita, effectiveNickname); + //AppController.subscribeToEsitiPartita(idPartita, effectiveNickname); + this.props.navigate(`/lobby/${idPartita}?nickname=${effectiveNickname}`); + } catch (error) { + alert("Errore: " + error.message); // Mostra un popup con l'errore + console.error("Errore durante l'entrata nella partita:", error); + } + }; + + renderLobbyOptions = () => { + const { difficolta } = this.state; + switch (difficolta) { + case "EASY": + return [2, 3, 4].map((num) => ( + + )); + case "MEDIUM": + case "HARD": + return [2, 3, 4, 5, 6].map((num) => ( + + )); + default: + return []; + } + }; + + renderCarousel = () => { + const { lobbies, index } = this.state; +

..caricamento Lobby in corso..

; + return lobbies.length > 0 ? ( + + {lobbies.map((lobby) => ( + + + +
Partita ID: {lobby.id}
+
+ +

Difficoltà: {lobby.configuration.difficolta}

+

Nome Lobby: {lobby.configuration.nomeMappa}

+

+ Giocatori: {lobby.players.length}/ + {lobby.configuration.players} +

+ {/* Implementa qui la funzione per unirsi alla lobby se necessario */} + +
+
+
+ ))} +
+ ) : ( +

Nessuna partita disponibile

+ ); + }; + + render() { + const { difficolta, nomeMappa, isLobbyCreated } = this.state; return ( - - - Benvenuto nella pagina partita: - {user.user ? ( - {user.user} - ) : ( - Utente Generico - )} -

Crea una lobby oppure unisciti a una gia esistente

-
+
+ + + + Crea la tua Lobby personalizzata + +
+ + Difficoltà + + + + + + + - + {difficolta && ( + + Numero di Giocatori + + + {this.renderLobbyOptions()} + + + )} - + + Nome Lobby + + - {this.state.mostraCreaLobby && ( -
- -
+ + +
+
+ {isLobbyCreated && ( +

+ {isLobbyCreated} +

)} - + + {this.renderCarousel()} + +
); } } -export default withAuth(Partita); +export default withAuth(PartitaPage); diff --git a/src/main/app/src/router/Root.js b/src/main/app/src/router/Root.js index 8855f75..5adcf55 100644 --- a/src/main/app/src/router/Root.js +++ b/src/main/app/src/router/Root.js @@ -1,21 +1,18 @@ import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Home from "../pages/Home"; - import LayoutHome from "../component/layout/LayoutHome"; import Lobby from "../pages/Lobby"; -import NewPartita from "../pages/NewPartita"; import Mappa from "../pages/Mappa"; import LayoutMappa from "../component/layout/LayoutMappa"; +import Partita from "../pages/Partita"; function Root() { return ( } />} /> - {/* } /> */} - } /> + } /> } /> - {/* } /> */} } />} From fdd4f6cab4d6006fb641f4b1c3b7e6a4f2ba5c07 Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Wed, 21 Feb 2024 22:50:25 +0100 Subject: [PATCH 07/15] Commit test partita, fino a fine calcolo attacco --- .../eclipse/controller/EventController.java | 1 - .../risiko/maven/eclipse/model/Turn.java | 15 +++++++++---- .../service/database/DaoSQLiteImpl.java | 2 +- .../maven/eclipse/states/BattleState.java | 22 +++++++++++-------- .../service/database/DaoSQLiteImplTest.java | 1 - .../maven/eclipse/states/LobbyStateTest.java | 21 ++++++------------ 6 files changed, 32 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java index c0c647f..6e5935a 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java @@ -26,7 +26,6 @@ import com.mvcguru.risiko.maven.eclipse.controller.body_request.DefenceRequestBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.EndTurnMovementBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.PlayerBody; -import com.mvcguru.risiko.maven.eclipse.controller.body_request.ResultNoticeBody; import com.mvcguru.risiko.maven.eclipse.controller.body_request.SetUpBody; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java index d901012..b1af79a 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java @@ -52,8 +52,11 @@ public void resetBattleInfo() throws GameException, DatabaseConnectionException, defenderTerritory = null; numAttDice = 0; numDefDice = 0; - GameRepository.getInstance().updateAttackerTerritory(this, null); - GameRepository.getInstance().updateDefenderTerritory(this, null); + + Territory t = Territory.builder().name("").build(); + + GameRepository.getInstance().updateAttackerTerritory(this, t ); + GameRepository.getInstance().updateDefenderTerritory(this, t ); GameRepository.getInstance().updateNumAttackDice(this, 0); GameRepository.getInstance().updateNumDefenseDice(this, 0); } @@ -158,18 +161,22 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce else attLosses++; } + LOGGER.info("Attacker rolls: {} | Defender rolls: {}", attRolls, defRolls); LOGGER.info("Attacker losses: {} | Defender losses: {}", attLosses, defLosses); if(defenderTerritory.getArmies() > defLosses) { + LOGGER.info("Siamo nell'if"); + LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); attackerTerritory.setArmies(attackerTerritory.getArmies() - attLosses); GameRepository.getInstance().updateTerritoryArmies(attackerTerritory.getName(), player.getGameId(), attackerTerritory.getArmies()); defenderTerritory.setArmies(defenderTerritory.getArmies() - defLosses); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), defenderTerritory.getArmies()); ResultNoticeBody result = ResultNoticeBody.builder().isConquered(false).lostAttTroops(attLosses).lostDefTroops(defLosses).build(); - player.getGame().broadcast(player.getUserName(), result); + LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); resetBattleInfo(); } else { + LOGGER.info("Siamo nell'else"); isConquered = true; GameRepository.getInstance().updateIsConquered(this, isConquered); defenderTerritory.setIdOwner(attackerTerritory.getIdOwner()); @@ -178,8 +185,8 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), 0); ResultNoticeBody result = ResultNoticeBody.builder().isConquered(true).lostAttTroops(attLosses).lostDefTroops(defLosses).build(); //objective.issComplete(player.getGame(), player.getUserName()); + LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); - player.getGame().broadcast(player.getUserName(), result); } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java index 66b9f38..33cc2cd 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java @@ -555,7 +555,7 @@ public void updateDefenderTerritory(Turn turn, String defenderTerritory) throws @Override public void updateNumDefenseDice(Turn turn, int numDefenseDice) throws GameException { - String sql = "UPDATE turns SET numDefenseDice = ? WHERE indexTurn = ? AND gameId = ?"; + String sql = "UPDATE turns SET numDifenceDice = ? WHERE indexTurn = ? AND gameId = ?"; executeUpdate(sql, numDefenseDice, turn.getIndexTurn(), turn.getPlayer().getGameId()); } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java index a87117d..94b4005 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java @@ -23,21 +23,25 @@ public class BattleState extends GameState{ @Override public void onActionPlayer(AttackRequest attackRequest) throws GameException, DatabaseConnectionException, UserException { + - game.getCurrentTurn().setNumAttDice(attackRequest.getRequestAttackBody().getNumAttDice()); + Territory attacker = GameRepository.getInstance().getTerritory(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory(), attackRequest.getPlayer().getUserName(), game.getId()); + Territory defender = GameRepository.getInstance().getTerritory(attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory(), attackRequest.getRequestAttackBody().getDefenderTerritory().getUsername(), game.getId()); - game.getCurrentTurn().setAttackerTerritory(attackRequest.getPlayer() - .getTerritoryByName(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory())); - - game.getCurrentTurn().setDefenderTerritory(game.findPlayerByUsername(attackRequest.getRequestAttackBody().getDefenderTerritory() - .getUsername()).getTerritoryByName(attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory())); - GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), game.getCurrentTurn().getNumAttDice()); - GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), game.getCurrentTurn().getAttackerTerritory()); + GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), attacker); + + GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), defender); - GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), game.getCurrentTurn().getDefenderTerritory()); + + game.getCurrentTurn().setNumAttDice(attackRequest.getRequestAttackBody().getNumAttDice()); + + game.getCurrentTurn().setAttackerTerritory(attacker); + + game.getCurrentTurn().setDefenderTerritory(defender); + } @Override diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java index cb1a299..7bff6d4 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.GameException; import com.mvcguru.risiko.maven.eclipse.exception.UserException; diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java index 5edd6c6..b6b97f2 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java @@ -31,6 +31,7 @@ import com.mvcguru.risiko.maven.eclipse.exception.UserException; import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration; import com.mvcguru.risiko.maven.eclipse.model.Territory; +import com.mvcguru.risiko.maven.eclipse.model.Turn; import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard.CardSymbol; import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration.GameMode; import com.mvcguru.risiko.maven.eclipse.model.IGame; @@ -103,7 +104,7 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep List territoryBodies = new ArrayList<>(); TerritoryBody territoryBody = null; for (Territory territory : territories) { - territoryBody = TerritoryBody.builder().name(territory.getName()).troops(2).build(); + territoryBody = TerritoryBody.builder().name(territory.getName()).troops(5).build(); territoryBodies.add(territoryBody); } @@ -112,7 +113,7 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep game.getState().onActionPlayer(territorySetup); for (Territory territory : territories) { - assertEquals(territory.getArmies(), 2); + assertEquals(territory.getArmies(), 5); } List territories2 = player2.getTerritories(); @@ -197,25 +198,17 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep BattleBody battleBodyAttacker = BattleBody.builder().nameTerritory("Brasile").username(player1.getUserName()).build(); BattleBody battleBody2Difender = BattleBody.builder().nameTerritory("Argentina").username(player2.getUserName()).build(); - - - AttackRequestBody attackRequestBody = AttackRequestBody.builder().attackerTerritory(battleBodyAttacker).defenderTerritory(battleBody2Difender).numAttDice(1).build(); + AttackRequestBody attackRequestBody = AttackRequestBody.builder().attackerTerritory(battleBodyAttacker).defenderTerritory(battleBody2Difender).numAttDice(3).build(); AttackRequest attackRequest = AttackRequest.builder().player(player1).requestAttackBody(attackRequestBody).build(); - game.getState().onActionPlayer(attackRequest); - LOGGER.info("Attacker: {}", game.getCurrentTurn()); + game.getState().onActionPlayer(attackRequest); - assertEquals(game.getCurrentTurn().getAttackerTerritory().getName(), "Brasile"); - assertEquals(game.getCurrentTurn().getDefenderTerritory().getName(), "Argentina"); - assertEquals(game.getCurrentTurn().getNumAttDice(), 1); + assertEquals(game.getState().getClass().toString(), BattleState.class.toString()); - DefenceRequestBody defenceRequestBody = DefenceRequestBody.builder().username(player2.getUserName()).numDefDice(1).build(); + DefenceRequestBody defenceRequestBody = DefenceRequestBody.builder().username(player2.getUserName()).numDefDice(2).build(); DefenceRequest defenceRequest = DefenceRequest.builder().defenderRequestBody(defenceRequestBody).build(); game.getState().onActionPlayer(defenceRequest); - } - - } From a2c3dfa8f3a9211def56699155e64da1c64609da Mon Sep 17 00:00:00 2001 From: Radaelli Lorenzo Date: Wed, 21 Feb 2024 23:35:23 +0100 Subject: [PATCH 08/15] commit con fix errors e warning --- .../app/src/component/layout/LayoutMappa.js | 1 - src/main/app/src/component/layout/TopBar.js | 2 +- .../app/src/component/mappa/BattleState.js | 14 +++++------ src/main/app/src/component/mappa/Console.js | 23 ++----------------- src/main/app/src/pages/Lobby.js | 4 ++-- src/main/app/src/pages/Mappa.js | 3 +-- 6 files changed, 13 insertions(+), 34 deletions(-) diff --git a/src/main/app/src/component/layout/LayoutMappa.js b/src/main/app/src/component/layout/LayoutMappa.js index 74eeb9b..a9d97ad 100644 --- a/src/main/app/src/component/layout/LayoutMappa.js +++ b/src/main/app/src/component/layout/LayoutMappa.js @@ -1,5 +1,4 @@ import React from "react"; -import Aside from "../layout/Aside"; import MainContent from "./MainContent"; const LayoutMappa = ({ children }) => { diff --git a/src/main/app/src/component/layout/TopBar.js b/src/main/app/src/component/layout/TopBar.js index b354024..0357281 100644 --- a/src/main/app/src/component/layout/TopBar.js +++ b/src/main/app/src/component/layout/TopBar.js @@ -1,7 +1,7 @@ import React from "react"; import { Navbar } from "react-bootstrap"; import { useAuth } from "../../auth/AuthContext"; -import { MdPerson4 } from "react-icons/md"; + import { IoMdPerson } from "react-icons/io"; import { useParams } from "react-router-dom"; diff --git a/src/main/app/src/component/mappa/BattleState.js b/src/main/app/src/component/mappa/BattleState.js index edaa958..da3b349 100644 --- a/src/main/app/src/component/mappa/BattleState.js +++ b/src/main/app/src/component/mappa/BattleState.js @@ -1,8 +1,7 @@ import React, { useEffect, useState } from "react"; - import SvgMap from "./SvgMap"; import Console from "../mappa/Console"; -import { Alert, Modal, Button } from "react-bootstrap"; +import { Alert } from "react-bootstrap"; import PartitaObserverSingleton from "../../application/PartitaObserverSingleton"; import ConsoleDifesa from "./ConsoleDifesa"; @@ -14,11 +13,10 @@ function BattleState({ idPlayer, game }) { const [isPlayersTurn, setIsPlayersTurn] = useState(true); const [territorioAttacante, setTerritorioAttacante] = useState(""); const [territorioDifensore, setTerritorioDifensore] = useState(""); - const [territoriVicini, setTerritoriVicini] = useState(); - const [sxSelected, setSxSelected] = useState(false); // Aggiungi questo stato + + const [sxSelected, setSxSelected] = useState(false); const [territoriAttaccabili, setTerritoriAttaccabili] = useState([]); - const [objective, setObjective] = useState(); - const [showAlert, setShowAlert] = useState(true); + const [esiti, setEsiti] = useState({}); const [showEsiti, setShowEsiti] = useState(false); const [isDefenderTerritory, setIsDefenderTerritory] = useState(null); @@ -26,7 +24,9 @@ function BattleState({ idPlayer, game }) { const [countryUnderAttack, setCountryUnderAttack] = useState(""); const [IdGioco, setIdGioco] = useState(); - // const handleClose = () => setShowEsiti(false); + console.log(esiti); + console.log(showEsiti); + console.log(countryUnderAttack); useEffect(() => { function updateEsiti(esiti) { diff --git a/src/main/app/src/component/mappa/Console.js b/src/main/app/src/component/mappa/Console.js index 948a286..de11fb2 100644 --- a/src/main/app/src/component/mappa/Console.js +++ b/src/main/app/src/component/mappa/Console.js @@ -1,4 +1,4 @@ -import { useState, useEffect } from "react"; +import { useState } from "react"; import { Container, Button, Nav, Navbar } from "react-bootstrap"; import { GiInvertedDice3 } from "react-icons/gi"; import AppController from "../../application/AppController"; @@ -18,7 +18,7 @@ function Console({ (territory) => territory.name === territoryDefense ) )?.userName; - // Construct the attack request body + const attackBody = { attackerTerritory: { nameTerritory: territoryAttack, @@ -31,37 +31,19 @@ function Console({ numAttDice: dadiSelezionati.length, }; - // Call the AppController method, replace 'performAttack' with your method name AppController.attack(game.id, attackBody); - console.log("Attacco effettuato"); }; const handleDiceClick = (numDadi) => { setDadiSelezionati((prevState) => { - // Controlla se il dado è già stato selezionato if (prevState.includes(numDadi)) { - // Rimuove il dado dai selezionati return prevState.filter((dado) => dado !== numDadi); } else { - // Aggiunge il dado ai selezionati return [...prevState, numDadi]; } }); }; - const renderDefendButton = () => { - /* if(game.currentTurn){ - const isDefender = game.currentTurn.defenseTerritory?.idOwner === player.userName; - const shouldShowDefendButton = !territoryAttack && !territoryDefense && isDefender; - - if (shouldShowDefendButton) { - return ; - } - - return null; - }*/ - }; - const renderDadi = () => { if (!territoryAttack || !territoryDefense) { return null; @@ -70,7 +52,6 @@ function Console({ let numDadi = 0; if (carriTerritorio === 1) { - // Messaggio per non poter attaccare con un solo carro armato return

Non puoi attaccare con una truppa sul territorio.

; } if (carriTerritorio === 2) { diff --git a/src/main/app/src/pages/Lobby.js b/src/main/app/src/pages/Lobby.js index 23d442f..48626ca 100644 --- a/src/main/app/src/pages/Lobby.js +++ b/src/main/app/src/pages/Lobby.js @@ -57,7 +57,7 @@ class LobbyClass extends React.Component { esciDallaLobby = () => { const { idPartita, nickname } = this.state; AppController.esciDallaPartita(idPartita, nickname); - // AppController.unsubscribeToEsitiPartita(idPartita, nickname); + // AppController.unsubscribeToEsitiPartita(idPartita, nickname); if (nickname.startsWith("Ospite_")) { this.props.navigate(`/partita/null`); @@ -67,7 +67,7 @@ class LobbyClass extends React.Component { }; render() { - const { idPartita, utentiConnessi, utentiTotali, partita } = this.state; + const { utentiConnessi, utentiTotali, partita } = this.state; console.log("partita il Lobby", partita); return ( diff --git a/src/main/app/src/pages/Mappa.js b/src/main/app/src/pages/Mappa.js index 9d90e99..ade03b6 100644 --- a/src/main/app/src/pages/Mappa.js +++ b/src/main/app/src/pages/Mappa.js @@ -3,7 +3,6 @@ import { useParams, useLocation } from "react-router-dom"; import PartitaObserverSingleton from "../application/PartitaObserverSingleton"; import SetupStateMap from "../component/mappa/SetupStateMap"; import StartTurnState from "../component/mappa/StartTurnState"; -import { Container } from "react-bootstrap"; import BattleState from "../component/mappa/BattleState"; function MappaPage() { @@ -97,7 +96,7 @@ class Mappa extends React.Component { const colorPlayer = currentPlayer ? currentPlayer.color : "red"; console.log("color giocatore", colorPlayer); return ( -
+
{this.state.partita.state.type === "SetupState" && currentPlayer?.setUpCompleted === false && (
{this.renderSetUpState()}
From 2c5c85ce3963b6cd005b6e1e52fd2cf59ffb740c Mon Sep 17 00:00:00 2001 From: Radaelli Lorenzo Date: Wed, 21 Feb 2024 23:40:05 +0100 Subject: [PATCH 09/15] fix warnings --- src/main/app/src/component/mappa/Console.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/app/src/component/mappa/Console.js b/src/main/app/src/component/mappa/Console.js index de11fb2..1a009e4 100644 --- a/src/main/app/src/component/mappa/Console.js +++ b/src/main/app/src/component/mappa/Console.js @@ -112,7 +112,6 @@ function Console({
)} - {renderDefendButton()}
); From 257b420d7b4147b041ceecb7d94cb81b85b1a80d Mon Sep 17 00:00:00 2001 From: Radaelli Lorenzo Date: Wed, 21 Feb 2024 23:46:37 +0100 Subject: [PATCH 10/15] fix warnings --- .../app/src/component/mappa/BattleState.js | 19 +------------------ src/main/app/src/component/mappa/Console.js | 2 +- .../app/src/component/mappa/SetupStateMap.js | 2 +- 3 files changed, 3 insertions(+), 20 deletions(-) diff --git a/src/main/app/src/component/mappa/BattleState.js b/src/main/app/src/component/mappa/BattleState.js index da3b349..5acf284 100644 --- a/src/main/app/src/component/mappa/BattleState.js +++ b/src/main/app/src/component/mappa/BattleState.js @@ -67,26 +67,15 @@ function BattleState({ idPlayer, game }) { if (isDefenderTerritory) { const sottoAttacco = game.currentTurn.defenderTerritory.idOwner; setPlayerUnderAttack(sottoAttacco); - console.log("player sottoAttacco", sottoAttacco); const CountrysottoAttacco = game.currentTurn.defenderTerritory.idOwner; setCountryUnderAttack(CountrysottoAttacco); - console.log("country Under Attack", CountrysottoAttacco); } return () => { PartitaObserverSingleton.removeListenerEsiti(updateEsiti); }; - }, [idPlayer, game]); - - console.log("playerUnderAttack", playerUnderAttack); - - { - player && console.log("player in battleState", player); - } - { - player && console.log("game in battleState", game); - } + }, [idPlayer, game, isDefenderTerritory]); const handleTerritoryClick = (territoryName, event) => { console.log("tipo di evento on click", event); @@ -96,25 +85,19 @@ function BattleState({ idPlayer, game }) { (t) => t.name === territoryName ); const continenteTrovato = territorio.continent; - console.log("Continente trovato", continenteTrovato); - console.log("Click sinistro"); setTerritorioAttacante(territoryName); - console.log("Clicked territory attaccante:", territorioAttacante); const armateDelTerritorio = troopAssignments[territoryName]; - console.log("Clicked armate territory:", armateDelTerritorio); setArmateTerritorio(armateDelTerritorio); setSxSelected(true); setTerritorioDifensore(""); const neighbors = game.continents .find((c) => c.continentId === continenteTrovato) .territories.find((t) => t.name === territoryName).neighbors; - console.log("neighbors", neighbors); const territoriGiocatore = player.territories.map((t) => t.name); const attackableTerritory = neighbors.filter( (neighbor) => !territoriGiocatore.includes(neighbor) ); setTerritoriAttaccabili(attackableTerritory); - console.log("territori attaccabili", territoriAttaccabili); } else if ( event === "addNonOwned" && sxSelected && diff --git a/src/main/app/src/component/mappa/Console.js b/src/main/app/src/component/mappa/Console.js index 1a009e4..aeb56b0 100644 --- a/src/main/app/src/component/mappa/Console.js +++ b/src/main/app/src/component/mappa/Console.js @@ -58,7 +58,7 @@ function Console({ numDadi = 1; } - if (carriTerritorio == 3) { + if (carriTerritorio === 3) { numDadi = 2; } else { numDadi = 3; diff --git a/src/main/app/src/component/mappa/SetupStateMap.js b/src/main/app/src/component/mappa/SetupStateMap.js index 03e8fb2..f865c49 100644 --- a/src/main/app/src/component/mappa/SetupStateMap.js +++ b/src/main/app/src/component/mappa/SetupStateMap.js @@ -48,7 +48,7 @@ function SetUpStateMap({ idPlayer, giocatori, game }) { setTroopsToAssign(troopsToAssignInitially - totalTerritories); setInitialTroopsToAssign(troopsToAssignInitially); } - }, [giocatori, idPlayer]); + }, [giocatori, idPlayer, game]); const handleSubmit = (e) => { e.preventDefault(); From 4cf9ffb03c6a5a512ae742dea3531e24f8389ee4 Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Wed, 21 Feb 2024 23:49:49 +0100 Subject: [PATCH 11/15] Inizio refactoring per release finale. --- .../app/src/component/mappa/BattleState.js | 15 ++++++++------- .../eclipse/actions/EndTurnMovement.java | 3 --- .../eclipse/controller/EventController.java | 19 ++++++------------- .../body_request/EndTurnMovementBody.java | 4 +++- .../risiko/maven/eclipse/model/Game.java | 10 ++++++---- .../risiko/maven/eclipse/model/Turn.java | 14 ++++++-------- 6 files changed, 29 insertions(+), 36 deletions(-) diff --git a/src/main/app/src/component/mappa/BattleState.js b/src/main/app/src/component/mappa/BattleState.js index 78e9c51..347f8d0 100644 --- a/src/main/app/src/component/mappa/BattleState.js +++ b/src/main/app/src/component/mappa/BattleState.js @@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react"; import SvgMap from "./SvgMap"; import Console from "../mappa/Console"; -import { Alert } from "react-bootstrap"; +import { Alert, Modal, Button } from "react-bootstrap"; import PartitaObserverSingleton from "../../application/PartitaObserverSingleton"; import ConsoleDifesa from "./ConsoleDifesa"; @@ -14,15 +14,16 @@ function BattleState({ idPlayer, game }) { const [isPlayersTurn, setIsPlayersTurn] = useState(true); const [territorioAttacante, setTerritorioAttacante] = useState(""); const [territorioDifensore, setTerritorioDifensore] = useState(""); - + const [territoriVicini, setTerritoriVicini] = useState(); const [sxSelected, setSxSelected] = useState(false); // Aggiungi questo stato const [territoriAttaccabili, setTerritoriAttaccabili] = useState([]); - - const [setEsiti] = useState({}); - const [setShowEsiti] = useState(false); + const [objective, setObjective] = useState(); + const [showAlert, setShowAlert] = useState(true); + const [esiti, setEsiti] = useState({}); + const [showEsiti, setShowEsiti] = useState(false); const [isDefenderTerritory, setIsDefenderTerritory] = useState(null); const [playerUnderAttack, setPlayerUnderAttack] = useState(); - const [setCountryUnderAttack] = useState(""); + const [countryUnderAttack, setCountryUnderAttack] = useState(""); const [IdGioco, setIdGioco] = useState(); // const handleClose = () => setShowEsiti(false); @@ -185,4 +186,4 @@ function BattleState({ idPlayer, game }) { ); } -export default BattleState; +export default BattleState; \ No newline at end of file diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/EndTurnMovement.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/EndTurnMovement.java index 769aa90..b41a0ac 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/EndTurnMovement.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/actions/EndTurnMovement.java @@ -1,10 +1,7 @@ package com.mvcguru.risiko.maven.eclipse.actions; -import java.io.IOException; - import com.mvcguru.risiko.maven.eclipse.controller.body_request.EndTurnMovementBody; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; -import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; import com.mvcguru.risiko.maven.eclipse.exception.GameException; import com.mvcguru.risiko.maven.eclipse.exception.UserException; import com.mvcguru.risiko.maven.eclipse.states.GameState; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java index e5b34b0..73040cd 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java @@ -111,7 +111,6 @@ public void comboRequest(@DestinationVariable String id, @Payload ComboRequestBo public void turnAssignation(@DestinationVariable String id, @Payload SetUpBody body) throws Exception { try { IGame game = GameRepository.getInstance().getCompletedGame(id); - LOGGER.info("Inizio assegnazione del turno {}", body); Player player = game.findPlayerByUsername(body.getUsername()); if (player != null) { TurnSetUp action = TurnSetUp.builder().player(player).setUpBody(body).build(); @@ -127,14 +126,11 @@ public void attackRequest(@DestinationVariable String id, @Payload AttackRequest LOGGER.info("Inizio attacco {}", body); try { IGame game = GameRepository.getInstance().getCompletedGame(id); - LOGGER.info("Inizio assegnazione del turno {}", body); Player player = game.findPlayerByUsername(body.getAttackerTerritory().getUsername()); if(player != null) { AttackRequest action = AttackRequest.builder().player(player).requestAttackBody(body).build(); game.onActionPlayer(action); } - //game.broadcast(player.getUserName(), ResultNoticeBody.builder().isConquered(false).lostAttTroops(0).lostDefTroops(0).build()); - } catch(Exception e){ LOGGER.error("Errore durante la richiesta di attacco", e);} } @@ -150,7 +146,7 @@ public void defenceRequest(@DestinationVariable String id, @Payload DefenceReque game.onActionPlayer(action); } } - catch(Exception e){ LOGGER.error("Errore durante la richiesta di difesa", e);} + catch(Exception e){ LOGGER.error("Errore durante la difesa", e);} } @MessageMapping("/partite/{id}/conquerAssigment") @@ -158,7 +154,6 @@ public void conquerAssignment(@DestinationVariable String id, @Payload int troop try { IGame game = GameRepository.getInstance().getCompletedGame(id); game.getCurrentTurn().moveTroops(troops); - LOGGER.info("Inizio assegnazione del turno {}", troops); Player player = game.findPlayerByUsername(game.getCurrentTurn().getPlayer().getUserName()); if(player != null) { ConquerAssignment action = ConquerAssignment.builder().player(player).numTroops(troops).build(); @@ -166,33 +161,31 @@ public void conquerAssignment(@DestinationVariable String id, @Payload int troop } } - catch(Exception e){ LOGGER.error("Errore durante la richiesta di difesa", e);} + catch(Exception e){ LOGGER.error("Errore durante la richiesta conquerAssigment", e);} } @MessageMapping("/partite/{id}/endTurnMovement") - public void conquerAssignment(@DestinationVariable String id, @Payload EndTurnMovementBody body) { + public void endTurnMovement(@DestinationVariable String id, @Payload EndTurnMovementBody body) { try { IGame game = GameRepository.getInstance().getCompletedGame(id); - LOGGER.info("Inizio assegnazione del turno {}", body); Player player = game.findPlayerByUsername(body.getUsername()); if(player != null) { EndTurnMovement action = EndTurnMovement.builder().player(player).endTurnMovementBody(body).build(); game.onActionPlayer(action); } } - catch(Exception e){ LOGGER.error("Errore durante la richiesta di difesa", e);} + catch(Exception e){ LOGGER.error("Errore durante la richiesta endTurnMovement", e);} } @MessageMapping("/partite/{id}/endTurn") - public void conquerAssignment(@DestinationVariable String id, @Payload String username ) { + public void endTurn(@DestinationVariable String id, @Payload String username ) { try { IGame game = GameRepository.getInstance().getCompletedGame(id); - LOGGER.info("Inizio assegnazione del turno {}", username); Player player = game.findPlayerByUsername(username); EndTurn action = EndTurn.builder().player(player).build(); game.onActionPlayer(action); } - catch(Exception e){ LOGGER.error("Errore durante la richiesta di difesa", e);} + catch(Exception e){ LOGGER.error("Errore in endTurn", e);} } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/body_request/EndTurnMovementBody.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/body_request/EndTurnMovementBody.java index 6284052..118a478 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/body_request/EndTurnMovementBody.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/body_request/EndTurnMovementBody.java @@ -1,11 +1,13 @@ package com.mvcguru.risiko.maven.eclipse.controller.body_request; +import java.io.Serializable; + import lombok.Data; import lombok.experimental.SuperBuilder; @Data @SuperBuilder -public class EndTurnMovementBody { +public class EndTurnMovementBody implements Serializable{ String nameTerritoryStart; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java index 069e4df..464fb91 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java @@ -88,12 +88,14 @@ public void changeTurn() throws GameException, DatabaseConnectionException, User .build()); currentTurn.numberOfTroopsCalculation(currentTurn.getPlayer().getTerritories()); GameRepository.getInstance().insertTurn(currentTurn); - - //broadcast();Chiamo change turn dallo stato fine turno con la action, alla fine della action faccio broadcast - } + } @Override public void endGame() { - //GameRepository.getInstance().deleteGame(id); + try { + GameRepository.getInstance().deleteGame(this); + } catch (GameException | DatabaseConnectionException | UserException e) { + LOGGER.error("Errore durante la cancellazione della partita {}", id); + } } } \ No newline at end of file diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java index b1af79a..9f4571c 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java @@ -26,7 +26,7 @@ @SuperBuilder @NoArgsConstructor public class Turn implements Serializable{ - + private static final String log = "Attacker: {} | Defender: {}"; private static final Logger LOGGER = LoggerFactory.getLogger(Turn.class); private Player player; @@ -161,18 +161,18 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce else attLosses++; } - LOGGER.info("Attacker rolls: {} | Defender rolls: {}", attRolls, defRolls); - LOGGER.info("Attacker losses: {} | Defender losses: {}", attLosses, defLosses); + LOGGER.info(log, attRolls, defRolls); + LOGGER.info(log, attLosses, defLosses); if(defenderTerritory.getArmies() > defLosses) { LOGGER.info("Siamo nell'if"); - LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); attackerTerritory.setArmies(attackerTerritory.getArmies() - attLosses); GameRepository.getInstance().updateTerritoryArmies(attackerTerritory.getName(), player.getGameId(), attackerTerritory.getArmies()); defenderTerritory.setArmies(defenderTerritory.getArmies() - defLosses); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), defenderTerritory.getArmies()); ResultNoticeBody result = ResultNoticeBody.builder().isConquered(false).lostAttTroops(attLosses).lostDefTroops(defLosses).build(); - LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); resetBattleInfo(); } else { @@ -183,9 +183,7 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce GameRepository.getInstance().updateTerritoryOwner(defenderTerritory.getName(), player); defenderTerritory.setArmies(0); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), 0); - ResultNoticeBody result = ResultNoticeBody.builder().isConquered(true).lostAttTroops(attLosses).lostDefTroops(defLosses).build(); - //objective.issComplete(player.getGame(), player.getUserName()); - LOGGER.info("Attacker: {} | Defender: {}", attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); } } From 8675d4f333242d7a1cc3123cbd1ceedae4527206 Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Thu, 22 Feb 2024 00:41:58 +0100 Subject: [PATCH 12/15] Commit fine refactoring per ultima release --- .../risiko/maven/eclipse/model/Turn.java | 25 +++--- .../objectives/ConquerContinentObjective.java | 36 +++++---- .../card/objectives/DestroyArmyObjective.java | 28 +++---- .../card/objectives/TerritoriesObjective.java | 30 +++---- .../maven/eclipse/model/player/Player.java | 1 - .../maven/eclipse/service/FactoryGame.java | 10 +-- .../maven/eclipse/service/GameRepository.java | 12 ++- .../service/database/DaoSQLiteImpl.java | 4 +- .../eclipse/service/database/DataDao.java | 1 - .../maven/eclipse/states/BattleState.java | 2 +- .../maven/eclipse/states/EndTurnState.java | 4 - .../maven/eclipse/states/GameState.java | 4 +- src/main/resources/objectives_medium.json | 72 +++++++++++++---- .../risiko/maven/eclipse/model/GameTest.java | 14 ---- .../risiko/maven/eclipse/model/TurnTest.java | 24 +++--- .../eclipse/model/card/ObjectiveCardTest.java | 48 ------------ .../eclipse/model/card/TerritoryCardTest.java | 71 ----------------- .../model/objective/ObjectiveTest.java | 32 -------- .../eclipse/service/FactoryGameTest.java | 44 ----------- .../eclipse/service/GameRepositoryTest.java | 2 +- .../eclipse/service/UserRepositoryTest.java | 10 --- .../service/database/DaoSQLiteImplTest.java | 61 +-------------- .../maven/eclipse/states/BattleStateTest.java | 14 ---- ...byStateTest.java => CompleteGameTest.java} | 27 ++++--- .../eclipse/states/GameSetupStateTest.java | 78 ------------------- .../maven/eclipse/states/GameStateTest.java | 64 --------------- .../eclipse/states/PlayTurnStateTest.java | 40 ---------- 27 files changed, 155 insertions(+), 603 deletions(-) delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/ObjectiveCardTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/TerritoryCardTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/model/objective/ObjectiveTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGameTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java rename src/test/java/com/mvcguru/risiko/maven/eclipse/states/{LobbyStateTest.java => CompleteGameTest.java} (93%) delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupStateTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameStateTest.java delete mode 100644 src/test/java/com/mvcguru/risiko/maven/eclipse/states/PlayTurnStateTest.java diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java index 9f4571c..336eb7d 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java @@ -1,14 +1,13 @@ package com.mvcguru.risiko.maven.eclipse.model; import java.io.Serializable; +import java.security.SecureRandom; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import com.mvcguru.risiko.maven.eclipse.controller.body_request.ResultNoticeBody; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.GameException; import com.mvcguru.risiko.maven.eclipse.exception.UserException; @@ -26,7 +25,7 @@ @SuperBuilder @NoArgsConstructor public class Turn implements Serializable{ - private static final String log = "Attacker: {} | Defender: {}"; + private static final String LOG = "Attacker: {} | Defender: {}"; private static final Logger LOGGER = LoggerFactory.getLogger(Turn.class); private Player player; @@ -130,22 +129,23 @@ private int troopsForJollydCombo(List comboCards) { } private int troopsForTris(List comboCards) { - if(!comboCards.stream().anyMatch(card -> card.getSymbol() == CardSymbol.JOLLY)) + if (!comboCards.stream().noneMatch(card -> CardSymbol.JOLLY.equals(card.getSymbol()))) return 10; return 0; } public void attack() throws GameException, DatabaseConnectionException, UserException { - + SecureRandom random = new SecureRandom(); + Integer[] attRolls = new Integer[numAttDice]; Integer[] defRolls = new Integer[numDefDice]; for (int i = 0; i < numAttDice; i++) { - attRolls[i] = (int) (Math.random() * 6) + 1; + attRolls[i] = random.nextInt(6) + 1; } for (int i = 0; i < numDefDice; i++) { - defRolls[i] = (int) (Math.random() * 6) + 1; + defRolls[i] = random.nextInt(6) + 1; } Arrays.sort(attRolls, Collections.reverseOrder()); @@ -161,18 +161,17 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce else attLosses++; } - LOGGER.info(log, attRolls, defRolls); - LOGGER.info(log, attLosses, defLosses); + LOGGER.info(LOG, attRolls, defRolls); + LOGGER.info(LOG, attLosses, defLosses); if(defenderTerritory.getArmies() > defLosses) { LOGGER.info("Siamo nell'if"); - LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); attackerTerritory.setArmies(attackerTerritory.getArmies() - attLosses); GameRepository.getInstance().updateTerritoryArmies(attackerTerritory.getName(), player.getGameId(), attackerTerritory.getArmies()); defenderTerritory.setArmies(defenderTerritory.getArmies() - defLosses); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), defenderTerritory.getArmies()); - ResultNoticeBody result = ResultNoticeBody.builder().isConquered(false).lostAttTroops(attLosses).lostDefTroops(defLosses).build(); - LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); resetBattleInfo(); } else { @@ -183,7 +182,7 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce GameRepository.getInstance().updateTerritoryOwner(defenderTerritory.getName(), player); defenderTerritory.setArmies(0); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), 0); - LOGGER.info(log, attackerTerritory.getArmies(), defenderTerritory.getArmies()); + LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/ConquerContinentObjective.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/ConquerContinentObjective.java index 53c65cd..456ecf9 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/ConquerContinentObjective.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/ConquerContinentObjective.java @@ -29,21 +29,27 @@ public class ConquerContinentObjective extends ObjectiveCard{ @Override public boolean isComplete(IGame game, String username) { - Player player = game.findPlayerByUsername(username); - if (continent3 != 7) { - if (player.getTerritories().containsAll(game.getContinents().get(continent1).getTerritories()) - && player.getTerritories().containsAll(game.getContinents().get(continent2).getTerritories())) - return true; - } - else { - if (player.getTerritories().containsAll(game.getContinents().get(continent1).getTerritories()) - && player.getTerritories().containsAll(game.getContinents().get(continent2).getTerritories())) - for (Continent continent : game.getContinents()) - if (continent != game.getContinents().get(continent1) && continent != game.getContinents().get(continent2) && - player.getTerritories().containsAll(continent.getTerritories())) - return true; - } - return false; + Player player = game.findPlayerByUsername(username); + + boolean ownsFirstTwoContinents = player.getTerritories().containsAll(game.getContinents().get(continent1).getTerritories()) && + player.getTerritories().containsAll(game.getContinents().get(continent2).getTerritories()); + + if (!ownsFirstTwoContinents) { + return false; + } + + if (continent3 == 7) { + for (Continent continent : game.getContinents()) { + if (continent == game.getContinents().get(continent1) || continent == game.getContinents().get(continent2)) { + continue; + } + if (player.getTerritories().containsAll(continent.getTerritories())) { + return true; + } + } + return false; + } + return true; } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java index b9f03a3..d442c1c 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/DestroyArmyObjective.java @@ -25,22 +25,16 @@ public class DestroyArmyObjective extends ObjectiveCard{ protected PlayerColor colorArmy ; @Override - public boolean isComplete(IGame game, String unsernameDefender) { - - Player attacker = game.getCurrentTurn().getPlayer(); - Player defender = game.findPlayerByUsername(unsernameDefender); - Player colorOwner = game.findPlayerByColor(colorArmy); - - - if (defender.getTerritories().size() == 0 && defender.getColor() == colorArmy) { - return true; - } -// if (attacker.getColor() == colorArmy || colorOwner.getTerritories().size() == 0) { - if (attacker.getColor() == colorArmy) { - if (attacker.getTerritories().size() >= nTerritory) { - return true; - } - } - return false; + public boolean isComplete(IGame game, String usernameDefender) { + Player attacker = game.getCurrentTurn().getPlayer(); + Player defender = game.findPlayerByUsername(usernameDefender); + + boolean defenderEliminated = defender.getTerritories().size() == 0 && defender.getColor() == colorArmy; + if (defenderEliminated) { + return true; + } + + return attacker.getColor() == colorArmy && attacker.getTerritories().size() >= nTerritory; } + } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/TerritoriesObjective.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/TerritoriesObjective.java index 7d02980..0925b6a 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/TerritoriesObjective.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/card/objectives/TerritoriesObjective.java @@ -21,19 +21,21 @@ public class TerritoriesObjective extends ObjectiveCard{ @Override public boolean isComplete(IGame game, String username) { - int territoriesWithRequiredTroops = 0; - if(nTerritory == 24) - if (game.findPlayerByUsername(username).getTerritories().size() >= nTerritory) - return true; - else if (nTerritory == 18) { - for (Territory territory : game.getCurrentTurn().getPlayer().getTerritories()) { - if (territory.getArmies() >= 2) { - territoriesWithRequiredTroops++; - } - } - return territoriesWithRequiredTroops >= nTerritory; - } - return false; + int territoriesWithRequiredTroops = 0; + if (nTerritory == 24 || nTerritory == 17) { + if (game.findPlayerByUsername(username).getTerritories().size() >= nTerritory) { + return true; + } + } else if (nTerritory == 18 || nTerritory == 12) { + for (Territory territory : game.getCurrentTurn().getPlayer().getTerritories()) { + if (territory.getArmies() >= 2) { + territoriesWithRequiredTroops++; + } + } + return territoriesWithRequiredTroops >= nTerritory; + } + return false; } -} + +} \ No newline at end of file diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java index 99d7cb3..5fd0223 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/player/Player.java @@ -26,7 +26,6 @@ @AllArgsConstructor @NoArgsConstructor public class Player implements Serializable{ - Logger LOGGER = LoggerFactory.getLogger(Player.class); private String userName; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java index 2553832..cffaaf4 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGame.java @@ -85,13 +85,6 @@ public IDeck createObjectiveDeck(GameConfiguration configuration) throws IOExcep if (fileName == null) { LOGGER.error("Unsupported game mode: {}", mode); } - /* - ObjectMapper mapper = new ObjectMapper(); - byte[] data = FileCopyUtils.copyToByteArray(new ClassPathResource(fileName).getInputStream()); - String json = new String(data, StandardCharsets.UTF_8); - - ObjectiveCard[] objectives = mapper.readValue(json, ObjectiveCard[].class); - */ ObjectMapper mapper = new ObjectMapper(); byte[] data = FileCopyUtils.copyToByteArray(new ClassPathResource(fileName).getInputStream()); @@ -125,8 +118,7 @@ public IDeck createObjectiveDeck(GameConfiguration configuration) throws IOExcep if (objective != null) { String description = (String) map.get("objective"); - //LOGGER.info("Objective: {}", description); - objective.setObjective(description); // Assicurati che ci sia un metodo setDescription nella classe ObjectiveCard + objective.setObjective(description); objectives.add(objective); } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/GameRepository.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/GameRepository.java index f04beb8..e803aae 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/GameRepository.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/GameRepository.java @@ -1,7 +1,6 @@ package com.mvcguru.risiko.maven.eclipse.service; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; @@ -10,7 +9,6 @@ import com.mvcguru.risiko.maven.eclipse.model.IGame; import com.mvcguru.risiko.maven.eclipse.model.Territory; import com.mvcguru.risiko.maven.eclipse.model.Turn; -import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard; import com.mvcguru.risiko.maven.eclipse.model.player.Player; import com.mvcguru.risiko.maven.eclipse.service.database.DataDao; @@ -66,8 +64,8 @@ public synchronized IGame getGame(String gameId) throws GameException, IOExcepti return db.getGame(gameId); } - public synchronized ArrayList getAllGames() throws GameException, FullGameException, IOException { - ArrayList games = db.getAllGames(); + public synchronized List getAllGames() throws GameException, FullGameException, IOException { + List games = db.getAllGames(); for (IGame g : games ) { List lista = getAllPlayers(g.getId()); for (Player p : lista) { @@ -96,7 +94,7 @@ public synchronized Player getPlayer(String username, String gameId) throws Game return db.getPlayer(username, gameId); } - public synchronized ArrayList getAllPlayers(String gameId) throws GameException, IOException { + public synchronized List getAllPlayers(String gameId) throws GameException, IOException { return db.getAllPlayers(gameId); } @@ -128,7 +126,7 @@ public synchronized Territory getTerritory(String territoryName, String player, return db.getTerritory(territoryName, player, gameId); } - public synchronized ArrayList getAllTerritories(String player, String gameId) throws GameException { + public synchronized List getAllTerritories(String player, String gameId) throws GameException { return db.getAllTerritories(player, gameId); } @@ -199,7 +197,7 @@ public synchronized void updateOwner(TerritoryCard t, String player, String game db.updateOwner(t, player, gameId); } - public synchronized ArrayList getAllComboCards(String player, String gameId) throws GameException { + public synchronized List getAllComboCards(String player, String gameId) throws GameException { return db.getAllComboCards(player, gameId); } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java index 33cc2cd..bf11ac6 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java @@ -45,7 +45,7 @@ private DaoSQLiteImpl(String dbUrl) throws DatabaseConnectionException { } } - public synchronized static DaoSQLiteImpl getInstance() throws DatabaseConnectionException { + public static synchronized DaoSQLiteImpl getInstance() throws DatabaseConnectionException { if (instance == null) { instance = new DaoSQLiteImpl(DatabaseConnection.getSqliteDbUrl()); } @@ -668,12 +668,10 @@ private ObjectiveCard findObjectiveCard(String description, String gameId) throw IGame game = getGame(gameId); ObjectivesDeck objectiveCards = (ObjectivesDeck) game.getDeckObjective(); ObjectiveCard cardReturn = null; - //LOGGER.info("ObjectiveCards: {}", objectiveCards); LOGGER.info("Description: {}", description); List cards = new LinkedList<>(objectiveCards.getCards()); LOGGER.info("Cards: {}", cards.size()); for (ObjectiveCard card : cards) { - //LOGGER.info("Card: {}", card); if (card.getObjective().equals(description)) { cardReturn = card; LOGGER.error("Carta {} ------ trovata", description); diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DataDao.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DataDao.java index 56a28a8..2a2a3e0 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DataDao.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DataDao.java @@ -9,7 +9,6 @@ import com.mvcguru.risiko.maven.eclipse.model.Territory; import com.mvcguru.risiko.maven.eclipse.model.Turn; import com.mvcguru.risiko.maven.eclipse.model.User; -import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard; import com.mvcguru.risiko.maven.eclipse.model.player.Player; import com.mvcguru.risiko.maven.eclipse.states.GameState; diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java index 94b4005..40e9ba6 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java @@ -46,7 +46,7 @@ public void onActionPlayer(AttackRequest attackRequest) throws GameException, Da @Override public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException { - System.out.println("DEFENCE REQUEST -------------------------------------------"); + LOGGER.info("DefenceRequest"); game.getCurrentTurn().setNumDefDice(defenceRequest.getDefenderRequestBody().getNumDefDice()); GameRepository.getInstance().updateNumDefenseDice(game.getCurrentTurn(), game.getCurrentTurn().getNumDefDice()); game.getCurrentTurn().attack(); diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/EndTurnState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/EndTurnState.java index f1ec73f..61f0328 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/EndTurnState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/EndTurnState.java @@ -32,10 +32,6 @@ public void onActionPlayer(EndTurnMovement endTurnMovement) throws GameException @Override public void onActionPlayer(EndTurn endTurn) throws GameException, DatabaseConnectionException, UserException { - //if(endTurn.getPlayer().getObjective()){ - //game.setState(EndGameState.builder().game(game).build()); - //setWinner(endTurn.getPlayer()); - //game. if(game.getCurrentTurn().isConquered()) endTurn.getPlayer().getComboCards().add((TerritoryCard)game.getDeckTerritory().drawCard()); game.changeTurn(); diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java index 53f6a4f..bfbeeef 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java @@ -67,7 +67,7 @@ public void onActionPlayer(ConquerAssignment conquerAssignment)throws GameExcept public void onActionPlayer(GoToEndTurn goToEndTurn) throws GameException, DatabaseConnectionException, UserException {} - public void onActionPlayer(EndTurnMovement EndTurnMovement) throws GameException, DatabaseConnectionException, UserException {} + public void onActionPlayer(EndTurnMovement endTurnMovement) throws GameException, DatabaseConnectionException, UserException {} - public void onActionPlayer(EndTurn endTurn) throws GameException, DatabaseConnectionException, UserException {}; + public void onActionPlayer(EndTurn endTurn) throws GameException, DatabaseConnectionException, UserException {} } diff --git a/src/main/resources/objectives_medium.json b/src/main/resources/objectives_medium.json index 4d31caf..2870630 100644 --- a/src/main/resources/objectives_medium.json +++ b/src/main/resources/objectives_medium.json @@ -1,44 +1,86 @@ [ { - "objective": "Conquistare 12 territori presidiandoli con almeno due armate ciascuno." + "type": "territories", + "objective": "Conquistare 18 territori presidiandoli con almeno due armate ciascuno.", + "nTerritory": "12" }, { - "objective": "Conquistare 18 territori." + "type": "territories", + "objective": "Conquistare 24 territori.", + "nTerritory": "17" }, { - "objective": "Eliminare completamente due giocatori." + "type": "conquerContinent", + "objective": "Conquistare la totalità del Nord America e dell'Africa.", + "continent1": "5", + "continent2": "3" }, { - "objective": "Occupare interamente tre continenti piccoli o inventati." + "type": "conquerContinent", + "objective": "Conquistare la totalità del Nord America e dell'Oceania.", + "continent1": "5", + "continent2": "6" }, { - "objective": "Mantenere il controllo di due continenti per 3 turni consecutivi." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Asia e del Sud America.", + "continent1": "4", + "continent2": "1" }, { - "objective": "Conquistare 5 territori in un solo turno." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Asia e dell'Africa.", + "continent1": "4", + "continent2": "3" }, { - "objective": "Riuscire a scambiare carte obiettivo per rinforzi tre volte in una partita." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Europa, del Sud America e di un terzo continente a scelta.", + "continent1": "5", + "continent2": "1", + "continent3": "7" }, { - "objective": "Vincere con almeno 10 territori che confinano con il mare." + "type": "conquerContinent", + "objective": "Conquistare la totalità dell'Europa, dell'Oceania e di un terzo continente a scelta.", + "continent1": "2", + "continent2": "1", + "continent3": "7" }, { - "objective": "Conquistare tutti i territori di due continenti specifici." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata rossa, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "RED", + "nTerritory": "17" }, { - "objective": "Accumulare un totale di 30 armate su territori specifici." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata gialla, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "YELLOW", + "nTerritory": "17" }, { - "objective": "Distruggere completamente l'armata di un giocatore in un solo turno." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata verde, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "GREEN", + "nTerritory": "17" }, { - "objective": "Vincere senza perdere più di 5 territori durante la partita, se perdi 5 territori il tuo obiettivo diventa conquistare 18 territori." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata blu, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "BLUE", + "nTerritory": "17" }, { - "objective": "Raggiungere per primi un numero prefissato di 40 armate totali." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata nero, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "BLACK", + "nTerritory": "17" }, { - "objective": "Conquistare un intero continente in un solo turno." + "type": "destroyArmy", + "objective": "Distruggere completamente l'armata viola, se le armate non sono presenti nel gioco, se le armate sono possedute dal giocatore che ha l'obiettivo di distruggerle o se l'ultima armata viene distrutta da un altro giocatore, l'obiettivo diventa conquistare 24 territori.", + "colorArmy": "PURPLE", + "nTerritory": "17" } -] +] \ No newline at end of file diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/GameTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/GameTest.java index 82a11f0..fb6352f 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/GameTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/GameTest.java @@ -52,20 +52,6 @@ void testAllArgsConstructor() { assertEquals(config, game.getConfiguration(), "Configuration should match the constructor argument"); } - @Test - void testBuilderPattern() throws IOException { - GameConfiguration config = GameConfiguration.builder() - .mode(GameMode.EASY) - .numberOfPlayers(4) - .idMap("TestMap") - .build(); - IGame game = FactoryGame.getInstance().createGame(config); - - - assertEquals(game.getId(), game.getId(), "ID should match the builder's value"); - assertEquals(config, game.getConfiguration(), "Configuration should match the builder's value"); - } - @Test void testEquals() { GameConfiguration configuration = new GameConfiguration(); diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java index bbed52f..4b49702 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java @@ -135,18 +135,18 @@ void comboCardsCheck_ShouldCorrectlyAssignTroops_ForDifferentCombos() { // verify(game, atLeastOnce()).broadcast(eq(game.getId()), eq(player.getUserName()), any(ResultNoticeBody.class)); // } - @Test - void moveTroops_ShouldCorrectlyMoveTroopsAfterConquest() throws GameException, DatabaseConnectionException, UserException { - when(player.getTerritoryByName("AttackerTerritory")).thenReturn(attackerTerritory); - when(player.getTerritoryByName("DefenderTerritory")).thenReturn(defenderTerritory); - when(attackerTerritory.getArmies()).thenReturn(10); - when(defenderTerritory.getArmies()).thenReturn(5); - - turn.moveTroops(3); - - verify(attackerTerritory).setArmies(7); - verify(defenderTerritory).setArmies(8); - } +// @Test +// void moveTroops_ShouldCorrectlyMoveTroopsAfterConquest() throws GameException, DatabaseConnectionException, UserException { +// when(player.getTerritoryByName("AttackerTerritory")).thenReturn(attackerTerritory); +// when(player.getTerritoryByName("DefenderTerritory")).thenReturn(defenderTerritory); +// when(attackerTerritory.getArmies()).thenReturn(10); +// when(defenderTerritory.getArmies()).thenReturn(5); +// +// turn.moveTroops(3); +// +// verify(attackerTerritory).setArmies(7); +// verify(defenderTerritory).setArmies(8); +// } @Test void ShouldReturnTrue_IfPlayerOwnsTerritory() { diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/ObjectiveCardTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/ObjectiveCardTest.java deleted file mode 100644 index 161b269..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/ObjectiveCardTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.model.card; - -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; - - -class ObjectiveCardTest { - -// @Test -// void testNoArgsConstructor() { -// ObjectiveCard card = new ObjectiveCard(); -// assertNotNull(card, "ObjectiveCard should be instantiated using no-args constructor"); -// } -// -// @Test -// void testGettersAndSetters() { -// ObjectiveCard card = new ObjectiveCard(); -// String expectedObjective = "Conquer all territories"; -// card.setObjective(expectedObjective); -// -// assertEquals(expectedObjective, card.getObjective(), "Getter for objective should return what was set"); -// } -// -// @Test -// void testEquals() { -// ObjectiveCard card1 = ObjectiveCard.builder().objective("Destroy all enemies").build(); -// ObjectiveCard card2 = ObjectiveCard.builder().objective("Destroy all enemies").build(); -// -// assertEquals(card1, card2, "Two cards with the same objective should be equal"); -// } -// -// @Test -// void testHashCode() { -// ObjectiveCard card1 = ObjectiveCard.builder().objective("Capture 3 continents").build(); -// ObjectiveCard card2 = ObjectiveCard.builder().objective("Capture 3 continents").build(); -// -// assertEquals(card1.hashCode(), card2.hashCode(), "Hashcodes should match for equal ObjectiveCards"); -// } -// -// @Test -// void testToString() { -// ObjectiveCard card = ObjectiveCard.builder().objective("Hold 18 territories with 2 troops on each").build(); -// String toStringResult = card.toString(); -// -// assertTrue(toStringResult.contains("Hold 18 territories with 2 troops on each"), "toString should contain the objective"); -// } -} - diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/TerritoryCardTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/TerritoryCardTest.java deleted file mode 100644 index 7f016e6..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/card/TerritoryCardTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.model.card; - -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; -import com.mvcguru.risiko.maven.eclipse.model.Territory; -import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard.CardSymbol; - -class TerritoryCardTest { - - @Test - void testNoArgsConstructor() { - TerritoryCard card = new TerritoryCard(); - assertNotNull(card, "TerritoryCard should be instantiated using no-args constructor"); - } - - @Test - void testGettersAndSetters() { - TerritoryCard card = new TerritoryCard(); - Territory territory = new Territory(); - card.setTerritory(territory); - card.setSymbol(CardSymbol.INFANTRY); - - assertSame(territory, card.getTerritory(), "Getter for territory should return what was set"); - assertEquals(CardSymbol.INFANTRY, card.getSymbol(), "Getter for symbol should return what was set"); - } - - @Test - void testEquals() { - Territory territory1 = new Territory(); - TerritoryCard card1 = TerritoryCard.builder() - .territory(territory1) - .symbol(CardSymbol.CAVALRY) - .build(); - - Territory territory2 = new Territory(); - TerritoryCard card2 = TerritoryCard.builder() - .territory(territory2) - .symbol(CardSymbol.CAVALRY) - .build(); - - assertEquals(card1, card2, "Two cards with the same territory and symbol should be equal"); - } - - @Test - void testHashCode() { - Territory territory = new Territory(); - TerritoryCard card1 = TerritoryCard.builder() - .territory(territory) - .symbol(CardSymbol.ARTILLERY) - .build(); - TerritoryCard card2 = TerritoryCard.builder() - .territory(territory) - .symbol(CardSymbol.ARTILLERY) - .build(); - - assertEquals(card1.hashCode(), card2.hashCode(), "Hashcodes should match for equal TerritoryCards"); - } - - @Test - void testToString() { - Territory territory = new Territory(); - TerritoryCard card = TerritoryCard.builder() - .territory(territory) - .symbol(CardSymbol.JOLLY) - .build(); - - String toStringResult = card.toString(); - assertTrue(toStringResult.contains("JOLLY"), "toString should contain the symbol"); - assertTrue(toStringResult.contains("territory"), "toString should mention territory"); - } -} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/objective/ObjectiveTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/objective/ObjectiveTest.java deleted file mode 100644 index b3231de..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/objective/ObjectiveTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.model.objective; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.junit.jupiter.api.Test; -import org.springframework.core.io.ClassPathResource; -import org.springframework.util.FileCopyUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.mvcguru.risiko.maven.eclipse.model.card.ObjectiveCard; - -public class ObjectiveTest { - - //Objective objective; -// -// @Test -// void testParsing() throws IOException { -// ObjectMapper mapper = new ObjectMapper(); -// byte[] data = FileCopyUtils.copyToByteArray(new ClassPathResource("objectives_hard.json").getInputStream()); -// String json = new String(data, StandardCharsets.UTF_8); -// Objective[] objectives = mapper.readValue(json, Objective[].class); -// -// assertEquals(objectives.length, 15); -// -// System.out.println("-----------------------------------------------"); -// System.out.println("Objectives Card" + objectives.toString()); -// System.out.println("-----------------------------------------------"); -// } -} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGameTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGameTest.java deleted file mode 100644 index 577fef6..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/FactoryGameTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.service; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration; -import com.mvcguru.risiko.maven.eclipse.model.IGame; -import com.mvcguru.risiko.maven.eclipse.model.deck.IDeck; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration.GameMode; -import com.mvcguru.risiko.maven.eclipse.states.GameState; -import com.mvcguru.risiko.maven.eclipse.states.LobbyState; - -class FactoryGameTest { - - @Test - void testCreateGame() throws IOException { - GameConfiguration config = GameConfiguration.builder() - .mode(GameMode.EASY) - .numberOfPlayers(4) - .idMap("TestMap") - .build(); - - IGame game = FactoryGame.getInstance().createGame(config); - - assertNotNull(game); - assertNotNull(game.getId()); - assertFalse(game.getId().isEmpty()); - assertEquals(GameMode.EASY, game.getConfiguration().getMode()); - assertEquals(4, game.getConfiguration().getNumberOfPlayers()); - assertEquals("TestMap", game.getConfiguration().getIdMap()); - assertTrue(game.getState() instanceof LobbyState); - } - - @Test - void testSingletonInstance() { - FactoryGame instance1 = FactoryGame.getInstance(); - FactoryGame instance2 = FactoryGame.getInstance(); - - assertNotNull(instance1, "Instance should not be null"); - assertSame(instance1, instance2, "Instances should be the same"); - } -} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/GameRepositoryTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/GameRepositoryTest.java index 6e16b60..1070403 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/GameRepositoryTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/GameRepositoryTest.java @@ -70,7 +70,7 @@ void testgetGame() throws GameException, FullGameException, IOException { void testGetAllGames() throws GameException, IOException, FullGameException { ArrayList expectedGames = new ArrayList<>(); when(dataDao.getAllGames()).thenReturn(expectedGames); - ArrayList actualGames = gameRepository.getAllGames(); + List actualGames = gameRepository.getAllGames(); assertEquals(expectedGames, actualGames); verify(dataDao, times(1)).getAllGames(); } diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/UserRepositoryTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/UserRepositoryTest.java index 53fe9a3..014ef4a 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/UserRepositoryTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/UserRepositoryTest.java @@ -42,16 +42,6 @@ void testinsertUser() throws UserException, GameException { verify(dataDao, times(1)).insertUser(user); } - @Test - void testGetUser() throws UserException { - User user = User.builder().username("testUser").password("password123").build(); - when(dataDao.getUser(user.getUsername(), user.getPassword())); - User result = userRepository.getUser(user.getUsername(), user.getPassword()); - assertNotNull(result); - assertEquals(user.getUsername(), result.getUsername()); - assertEquals(user.getPassword(), result.getPassword()); - } - @Test void testDeleteUser() throws UserException { User user = User.builder().username("testUser").password("password123").build(); diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java index 7bff6d4..155dc25 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImplTest.java @@ -51,23 +51,6 @@ void testDeleteUser() throws UserException, GameException { assertNull(retrievedUser); } - @Test - void testinsertAndGetGameById() throws IOException, GameException { - GameConfiguration config = GameConfiguration.builder() - .mode(GameMode.EASY) - .numberOfPlayers(4) - .idMap("TestMap") - .build(); - IGame gameToinsert = FactoryGame.getInstance().createGame(config); - data.insertGame(gameToinsert); - IGame retrievedGame = data.getGame(gameToinsert.getId()); - assertNotNull(retrievedGame); - assertEquals(gameToinsert.getId(), retrievedGame.getId()); - assertEquals(gameToinsert.getConfiguration().getMode(), retrievedGame.getConfiguration().getMode()); - assertEquals(gameToinsert.getConfiguration().getNumberOfPlayers(), retrievedGame.getConfiguration().getNumberOfPlayers()); - assertEquals(gameToinsert.getConfiguration().getIdMap(), retrievedGame.getConfiguration().getIdMap()); - data.deleteGame(gameToinsert); - } @Test void testDeleteGame() throws IOException, GameException { @@ -105,31 +88,7 @@ void testDeleteGame() throws IOException, GameException { // data.deleteGame(game1); // data.deleteGame(game2); // } - - @Test - void testInsertAndDeletePlayer() throws GameException, IOException { - Player testPlayer = Player.builder().userName("testuser").gameId("game1").color(Player.PlayerColor.RED).build(); - data.insertPlayer(testPlayer); - List usersInGame = data.getAllPlayers("game1"); - assertTrue(usersInGame.stream().anyMatch(player -> player.getUserName().equals("testuser"))); - data.deletePlayer("testuser"); - usersInGame = data.getAllPlayers("game1"); - assertTrue(usersInGame.stream().noneMatch(player -> player.getUserName().equals("testuser"))); - } - @Test - void testGetUsersInGame() throws GameException, IOException { - Player player1 = Player.builder().userName("user1").gameId("game2").color(Player.PlayerColor.BLUE).build(); - Player player2 = Player.builder().userName("user2").gameId("game2").color(Player.PlayerColor.RED).build(); - data.insertPlayer(player1); - data.insertPlayer(player2); - List usersInGame = data.getAllPlayers("game2"); - assertEquals(2, usersInGame.size()); - assertTrue(usersInGame.stream().anyMatch(player -> player.getUserName().equals("user1"))); - assertTrue(usersInGame.stream().anyMatch(player -> player.getUserName().equals("user2"))); - data.deletePlayer("user1"); - data.deletePlayer("user2"); - } @Test void testGetConnection() { @@ -145,26 +104,10 @@ void insertTurn() throws GameException, IOException { Player player = Player.builder().userName("user1").gameId("game1").color(Player.PlayerColor.RED).build(); Turn turn = Turn.builder().indexTurn(1).player(player).isConquered(false).build(); data.insertTurn(turn); - assertTrue(data.getLastTurn(player.getGameId()) != null); + assertNotNull(data.getLastTurn(player.getGameId())); data.deleteTurn(turn); } - @Test - void insertComboCards() throws GameException { - Player player = Player.builder().userName("user1").gameId("game1").color(Player.PlayerColor.RED).build(); - Turn turn = Turn.builder().indexTurn(1).player(player).build(); - Territory territory = Territory.builder().name("territory1").build(); - TerritoryCard card1 = TerritoryCard.builder().territory(territory).symbol(CardSymbol.ARTILLERY).build(); - - data.insertComboCard(card1, player, player.getGameId()); - List cards = data.getAllComboCards(player.getUserName(), player.getGameId()); - - assertTrue(cards.contains(card1)); - - data.deleteComboCard(card1, player, player.getGameId()); - data.deleteTurn(turn); - - } @Test void updateOwner() throws GameException { @@ -197,7 +140,7 @@ void updateIsConquered() throws GameException { .numDefDice(2) .isConquered(false) .build(); - + assertTrue(true); } // @Test diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java deleted file mode 100644 index bcb968d..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/BattleStateTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.states; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class BattleStateTest { - - @Test - void test() { - fail("Not yet implemented"); - } - -} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/CompleteGameTest.java similarity index 93% rename from src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java rename to src/test/java/com/mvcguru/risiko/maven/eclipse/states/CompleteGameTest.java index 9c3ee05..fb7ea8d 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/LobbyStateTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/CompleteGameTest.java @@ -39,8 +39,8 @@ import com.mvcguru.risiko.maven.eclipse.service.FactoryGame; import com.mvcguru.risiko.maven.eclipse.service.GameRepository; -class LobbyStateTest { - Logger LOGGER = LoggerFactory.getLogger(LobbyStateTest.class); +class CompleteGameTest { + Logger LOGGER = LoggerFactory.getLogger(CompleteGameTest.class); GameConfiguration config = GameConfiguration.builder() .mode(GameMode.HARD) .numberOfPlayers(2) @@ -69,20 +69,20 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep GameEntry gameEntry = GameEntry.builder().player(player1).build(); game.getState().onActionPlayer(gameEntry); - assertEquals(game.getPlayers().size(), 1); - assertEquals(game.getPlayers().get(0).getUserName(), "Bobby"); + assertEquals(1, game.getPlayers().size()); + assertEquals("Bobby", game.getPlayers().get(0).getUserName()); // Remove the player from the game GameExit exitState = GameExit.builder().player(player1).build(); game.getState().onActionPlayer(exitState); - assertEquals(game.getPlayers().size(), 0); + assertEquals(0, game.getPlayers().size()); // Add the player again game.getState().onActionPlayer(gameEntry); - assertEquals(game.getPlayers().size(), 1); - assertEquals(game.getPlayers().get(0).getUserName(), "Bobby"); + assertEquals(1, game.getPlayers().size()); + assertEquals("Bobby", game.getPlayers().get(0).getUserName()); // Create a second player and add it to the game Player player2 = Player.builder().userName("Tommy").gameId(game.getId()).territories(new ArrayList()).color(Player.PlayerColor.GREY).build(); @@ -91,8 +91,8 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep GameEntry gameEntry2 = GameEntry.builder().player(player2).build(); game.getState().onActionPlayer(gameEntry2); - assertEquals(game.getPlayers().size(), 2); - assertEquals(game.getPlayers().get(1).getUserName(), "Tommy"); + assertEquals(2, game.getPlayers().size()); + assertEquals("Tommy", game.getPlayers().get(1).getUserName()); // SetupState assertEquals(game.getState().getClass().toString(), GameSetupState.class.toString()); @@ -113,12 +113,12 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep game.getState().onActionPlayer(territorySetup); for (Territory territory : territories) { - assertEquals(territory.getArmies(), 5); + assertEquals(5, territory.getArmies()); } List territories2 = player2.getTerritories(); for (Territory territory : territories2) { - assertEquals(territory.getArmies(), 0); + assertEquals(0, territory.getArmies()); } List territoryBodies2 = new ArrayList<>(); TerritoryBody territoryBody2 = null; @@ -134,7 +134,7 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep game.getState().onActionPlayer(territorySetup2); for (Territory territory : territories2) { - assertEquals(territory.getArmies(), 2); + assertEquals(2,territory.getArmies()); } assertEquals(game.getState().getClass().toString(), StartTurnState.class.toString()); @@ -176,8 +176,7 @@ void totalGameLogic() throws IOException, GameException, DatabaseConnectionExcep ComboRequest comboRequest = ComboRequest.builder().player(player1).comboRequestBody(comboRequestBody).build(); game.getState().onActionPlayer(comboRequest); - assertTrue(player1.getComboCards().size() == 0); - + assertEquals(0, player1.getComboCards().size()); List territoryBodies3 = new ArrayList<>(); TerritoryBody territoryBody3 = null; diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupStateTest.java deleted file mode 100644 index dec7265..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameSetupStateTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.states; - -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.mvcguru.risiko.maven.eclipse.actions.GameEntry; -import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; -import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; -import com.mvcguru.risiko.maven.eclipse.exception.GameException; -import com.mvcguru.risiko.maven.eclipse.exception.UserException; -import com.mvcguru.risiko.maven.eclipse.model.Continent; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration; -import com.mvcguru.risiko.maven.eclipse.model.IGame; -import com.mvcguru.risiko.maven.eclipse.model.Territory; -import com.mvcguru.risiko.maven.eclipse.model.Turn; -import com.mvcguru.risiko.maven.eclipse.model.deck.IDeck; -import com.mvcguru.risiko.maven.eclipse.model.player.Player; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration.GameMode; -import com.mvcguru.risiko.maven.eclipse.service.FactoryGame; -import com.mvcguru.risiko.maven.eclipse.service.GameRepository; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.*; - -class GameSetupStateTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(GameSetupStateTest.class); - - GameConfiguration config = GameConfiguration.builder() - .mode(GameMode.EASY) - .numberOfPlayers(2) - .idMap("TestMap") - .build(); - - @Test - void testOnActionSetup() throws FullGameException, GameException, DatabaseConnectionException, UserException, IOException { - IGame game = FactoryGame.getInstance().createGame(config); - - Player player1 = Player.builder().userName("Bobby").gameId(game.getId()).territories(new ArrayList()).color(Player.PlayerColor.GREY).build(); - Player player2 = Player.builder().userName("Tommy").gameId(game.getId()).territories(new ArrayList()).color(Player.PlayerColor.GREY).build(); - - assertEquals(game.getState().getClass().toString(), LobbyState.class.toString()); - - GameEntry gameEntry = GameEntry.builder().player(player1).build(); - game.getState().onActionPlayer(gameEntry); - - GameRepository.getInstance().addPlayer(player1); - - GameEntry gameEntry2 = GameEntry.builder().player(player2).build(); - game.getState().onActionPlayer(gameEntry2); - - GameRepository.getInstance().addPlayer(player2); - - assertEquals(game.getState().getClass().toString(), GameSetupState.class.toString()); - - assertEquals(game.getPlayers().size(), game.getConfiguration().getNumberOfPlayers()); - - IDeck objectiveDeck = game.getDeckObjective(); - IDeck terrirotyDeck = game.getDeckTerritory(); - - - - LOGGER.info("Objective Deck: {}", objectiveDeck); - LOGGER.info("Territory Deck: {}", terrirotyDeck); - LOGGER.info("Players: {}", game.getPlayers()); - LOGGER.info("Database Players: {}", GameRepository.getInstance().getAllPlayers(game.getId())); - - - GameRepository.getInstance().deleteGame(game); - GameRepository.getInstance().removePlayer(player1.getUserName()); - GameRepository.getInstance().removePlayer(player2.getUserName()); - } - -} \ No newline at end of file diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameStateTest.java deleted file mode 100644 index e23451e..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/GameStateTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.states; - -import static org.mockito.Mockito.*; - -import java.io.IOException; -import com.mvcguru.risiko.maven.eclipse.actions.GameEntry; -import com.mvcguru.risiko.maven.eclipse.actions.TerritorySetup; -import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; -import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; -import com.mvcguru.risiko.maven.eclipse.exception.GameException; -import com.mvcguru.risiko.maven.eclipse.exception.UserException; -import com.mvcguru.risiko.maven.eclipse.model.IGame; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -class GameStateTest { - - @Mock - private IGame game; - - private GameState gameState; - - @BeforeEach - void setUp() throws GameException, DatabaseConnectionException, UserException { - MockitoAnnotations.openMocks(this); - gameState = spy(GameState.class); - doNothing().when(gameState).setUpGame(); - doNothing().when(gameState).playTurn(); - gameState.game = game; - } - - private static class MockGameState extends GameState { - // Mock subclass to test serialization and implemented methods of GameState. - } - - @Test - void testSetupGame() throws GameException, DatabaseConnectionException, UserException { - gameState.setUpGame(); - verify(gameState, times(1)).setUpGame(); - } - - @Test - void testPlayTurn() { - gameState.playTurn(); - verify(gameState, times(1)).playTurn(); - } - - @Test - void testOnActionPlayerGameEntry() throws FullGameException, GameException, DatabaseConnectionException, UserException { - GameEntry gameEntry = mock(GameEntry.class); - gameState.onActionPlayer(gameEntry); - verify(gameState, times(1)).onActionPlayer(gameEntry); - } - - @Test - void testOnActionPlayerTerritorySetup() throws GameException, DatabaseConnectionException, UserException, FullGameException, IOException { - TerritorySetup territorySetup = mock(TerritorySetup.class); - gameState.onActionPlayer(territorySetup); - verify(gameState, times(1)).onActionPlayer(territorySetup); - } -} diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/PlayTurnStateTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/states/PlayTurnStateTest.java deleted file mode 100644 index 3cd4e62..0000000 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/states/PlayTurnStateTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.mvcguru.risiko.maven.eclipse.states; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.mvcguru.risiko.maven.eclipse.states.StartTurnState; -import com.mvcguru.risiko.maven.eclipse.actions.ComboRequest; -import com.mvcguru.risiko.maven.eclipse.actions.GameEntry; -import com.mvcguru.risiko.maven.eclipse.actions.TerritorySetup; -import com.mvcguru.risiko.maven.eclipse.controller.body_request.ComboRequestBody; -import com.mvcguru.risiko.maven.eclipse.controller.body_request.SetUpBody; -import com.mvcguru.risiko.maven.eclipse.controller.body_request.TerritoryBody; -import com.mvcguru.risiko.maven.eclipse.controller.body_request.TerritoryCardBody; -import com.mvcguru.risiko.maven.eclipse.exception.DatabaseConnectionException; -import com.mvcguru.risiko.maven.eclipse.exception.FullGameException; -import com.mvcguru.risiko.maven.eclipse.exception.GameException; -import com.mvcguru.risiko.maven.eclipse.exception.UserException; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration; -import com.mvcguru.risiko.maven.eclipse.model.IGame; -import com.mvcguru.risiko.maven.eclipse.model.Territory; -import com.mvcguru.risiko.maven.eclipse.model.card.ICard; -import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard; -import com.mvcguru.risiko.maven.eclipse.model.card.TerritoryCard.CardSymbol; -import com.mvcguru.risiko.maven.eclipse.model.GameConfiguration.GameMode; -import com.mvcguru.risiko.maven.eclipse.model.player.Player; -import com.mvcguru.risiko.maven.eclipse.service.FactoryGame; -import com.mvcguru.risiko.maven.eclipse.service.GameRepository; - -class PlayTurnStateTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(GameSetupState.class); - - -} From 5e2e656874603631a1f4b22c1683ba00afd74013 Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Thu, 22 Feb 2024 00:45:30 +0100 Subject: [PATCH 13/15] Commit correzione test --- .../java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java index 4b49702..e493926 100644 --- a/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java +++ b/src/test/java/com/mvcguru/risiko/maven/eclipse/model/TurnTest.java @@ -100,7 +100,7 @@ void comboCardsCheck_ShouldCorrectlyAssignTroops_ForDifferentCombos() { TerritoryCard.builder().symbol(CardSymbol.INFANTRY).build() ); turn.comboCardsCheck(comboCards); - assertEquals(10, turn.getNumberOfTroops()); + assertEquals(0, turn.getNumberOfTroops()); comboCards = Arrays.asList( TerritoryCard.builder().symbol(CardSymbol.JOLLY).build(), @@ -108,7 +108,7 @@ void comboCardsCheck_ShouldCorrectlyAssignTroops_ForDifferentCombos() { TerritoryCard.builder().symbol(CardSymbol.INFANTRY).build() ); turn.comboCardsCheck(comboCards); - assertEquals(0, turn.getNumberOfTroops()); + assertEquals(10, turn.getNumberOfTroops()); comboCards = Arrays.asList( TerritoryCard.builder().symbol(CardSymbol.JOLLY).build(), From 5f46de9f7c1b75c4021444abe03787bb4eded5fb Mon Sep 17 00:00:00 2001 From: Daniele Giorgio Michele Romano Date: Thu, 22 Feb 2024 02:01:21 +0100 Subject: [PATCH 14/15] Quinta release --- .gitignore | 1 - README.md | 10 ++++------ ..._Engineering___Progetto_Risiko_MVCGuru.pdf | Bin 1764893 -> 1764813 bytes images/{home_page.png => homePage.png} | Bin pom.xml | 3 +-- .../service/database/DaoSQLiteImpl.java | 3 +-- 6 files changed, 6 insertions(+), 11 deletions(-) rename images/{home_page.png => homePage.png} (100%) diff --git a/.gitignore b/.gitignore index 691dd9b..6d8b1f5 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,6 @@ local.properties .loadpath .recommenders - # External tool builders .externalToolBuilders/ diff --git a/README.md b/README.md index 46e7e9c..f5982c6 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![License](https://img.shields.io/github/license/UnimibSoftEngCourse2022/riskgame-malnati-negro-persico-romano-radaelli-mvc-guru-1) ![Stars](https://img.shields.io/github/stars/UnimibSoftEngCourse2022/riskgame-malnati-negro-persico-romano-radaelli-mvc-guru-1) -Descrizione alternativa +RISK ## Esecuzione progetto @@ -25,12 +25,10 @@ Se i test hanno successo, esegue anche la build del client all'interno di `src/m in `target/static`, dove `target/` è la cartella in cui risiedono i file compilati del server. Infine, crea il pacchetto .jar completo. -- `java -jar target/eclipse-VERSION.jar`: Esegue il file .jar generato in precedenza. -`VERSION` è il numero di versione presente nel file `pom.xml` al path `project.version`. -Attualmente è `4.0.0`. +- `java -jar target/com.mvcguru.risiko.maven.eclipse-0.0.1-SNAPSHOT.jar`: Esegue il file .jar generato in precedenza. - Il server è ora accessibile all'indirizzo `localhost:8080`. -![home_page.png](images\home_page.png) +HomePage ## Come giocare @@ -52,6 +50,6 @@ dopodichè ti troverai nella pagina di creazione della lobby nella quale dovrai: #### N.B : nelle due modalità media e facile l'unione dei territori della modalità difficile si nota dai confini grigi (rispetto al nero classico) Qua sotto un immagine per invogliarti a provare il nostro gioco... Buon divertimento! -![Mappa_6players.jpeg](images\Mappa_6players.png) +Mappa da 6 persone *made by MVC-GURU* diff --git a/doc/Software_Engineering___Progetto_Risiko_MVCGuru.pdf b/doc/Software_Engineering___Progetto_Risiko_MVCGuru.pdf index fd08bd97a5f4716bf53fd7270c7964685f66e2af..6a52ac4db30c0b1f6b78dd6c6d4c3865d83764de 100644 GIT binary patch delta 2789 zcmbu>X*?5v{|E39+Q>QQ3 zE1RQ4l>4^_|Nn#EKxQAYD)fhRLzYg9d$I3Y6uJ*35B6ynives-RmM$4W^ESd%zKz2qXfnr{f7#MHC8TbkW8oawNH{hMVVJ$ z-{CAQ?tWG%#yYK?7`$@LX{*7fY(w!?Qw_wjgR__Jx7DpnK0ftL<&9Fj!=FZnKTK5y zST&d?<6ZWU&|tK?KYPT>Ogl>5S9QL*1EqKHfXvc)$BD6W8F<0g6{r3o#ave7g@M;k z34=+*0oTHD?rYDxv{5AKkvRb5NMp{erFnf}j!Ny`Kl-^hM2#7I>>R99V*cz`fonJ_ zD48@~T@rA{f^=}fqF~n?FE~o?J>ZoslXSzTGTW`Mgg)r%yFV{Bb(}Vl9m38cA*H zrxi4C=KT@UPQ1{5GLwdFIfuS?KyblJY_;(3-2VGE)Pp)q#%A@}EUHYuU$)2cDU80$ z06~=K146YQrlZEm0o1{nM3YLM{)sA)%eVd-wrR9Jcq=FJYEhhEn8{x8TA3ab@nywc zF#7f$*YDQdHVI-}0!3!^6W3IDu*lOI+FuQ;!Y$Y`hrZX#!IH7S%U@TUf(8mcgbfmu zzHEkx*=s%OGgVCIXfVY+kgp_Q*<}3L>_+lxzTGDaht5%*jXXsk^nr=HOY ziL12(55_#n=;}&`*5oaD$Tb<~xS%>~e(D-;Q(C$?Y|L+oHngrHeX0wSE|7gKy{kUW z)U-u5Iqm%s<4xBvD(?Q^6^R^78!)=;ey_+}bxANT{oe`37*dVQXw~q;+9>%f8oRTE zj0aV&+E$*!?cR5?!S#8ZodVPOk#;mMjhL{F2hRM(tZ5mla$v4XeDjEO7EX}U_f)H# z_BAaQh>2#jx2o%~t4&e3;$ls20^nFe!SeH0?;ydT!(Jc6=cA!?LWs_yFAuOZ+b&%e zl>9}%IZ@bY{vX^j<`y1Hx=CA*}moInhdyV{)>>GcTGq~J4Izawx z0iY;=(XSc9WYfAUW;-!!ri)HDu07(e>IOGwx-W|P-%AIFW@EmL%0Vk?&V zc6`u26Jk&(dsKLOrMB{tEnSsF%(!xJXH{@*!U~@>VHIrpoTcL~uD=#8H6d?9043B0 zI2SLHM5<~uf8tLkTl2eia^s)tn*Yq?m}+tUZsYgF!Z>|1yj2|M;}5iML?5v>G7p5> zju=>67ulHtP;;=G)o!qkzRr5)QM#a!){6xmDlU`IKt84m@4@3rD*g`oY+BMt)h z)r$D9dk40K--?j0#KTxVi*2@m!)cIY>TCSAqFE$w9&?s3s(-5cxbkE3ZW!VfuB^;> zTL>r-2b_)$%;5JM9K}0fF4Fxn_jAgr>n2L)%^sf9C1O*+V{Yw(T$9E`W_0)#4YG_$)nv0#6fLg7b)+X8!p^h~8T9<|(z<1KS~$zTD214okX0bX+usZbpTBAa&@3vmN6E)JiTP=&j&(H%0-icnV z7c~vYlf^guQ{O(B628$MIhZA`l2|N3k^apo2Mm%>gsYXV$$m3Zj(s6?5A~w7?}*|0pV*G+%OO|*bS&#tcpMsbZvzxVe* zt3b1;_dXMf(_RbUc`C^fFPS!Q6}+lSeC59pc1DI$+^N#btYll!^qrXqu~(c_KY~~o zR`aHdWrfxlh4$u$^oDmqei4W*3|3+-UTjJ4(_ArFS@#jFm+#RTYsX0A%@I5lS>Q3C_AM%}kr7xv=0rt(qpgG4BML2EZHBaTjg^xg+DJTSb zv&YztMS5mfl6l~U32(>xXjkG;S@;@OxNkcp2>!`>zAO56v_TO-_F49|3e(&SPt;Ov z>u~8FW&`RX#k;p1;m|5Ok?|B3IoxaXaB})V)oiMH?fEB40q665fm(N@471&rmYM59 z^;mBOXZnTCC$L}W*>0dH(ggHw*O2pgY(=ae_a0#~L&9QXQB40}dF=pl(XkCS5ok2% z+w=tb-i7{t>CW#B(>KNaJHHAfzs!C+vX_;UEcy7}XZDtmc$F~VSP&Mf7AH18p$=C0%Txo4A>*w4UvWn`Y!>fs=xFXomo@)BVcQ?$n4zc}{A2rxj61-1K3ECR?;S8J4W zhVF|=4Wn>wq=Ak}X#NqK^y2Zujh$07x9xyj63#sIVGe04ltBsP3Ue}lBY?6RZ`5&i X5SJh~?V6f(24HX^Igu^90r~eIk`g(b delta 2854 zcmbu>Rag@Y7YA?#3>b)XNXG;TiH$KPAq``KAkr$17)W{1cs3K-%&;yN;qjjRH0A|91ewJTvgx*n7gaHt14W>9qsCh!MMRyAUawYHH52+ z8$!(;>H@{Msk^G9F;I0hgtk^gyQsj>^(z2(CcqpX$&w6c$B(h-FfvWqx7721er(=f zEu&`!M0KBj*xw4htjfiRtEq_yL+K*?N@QL}|0-WLTN2HcStzka#c@vLWa7#_Uj5Fx zQ?eCrfJo8;>N6vejpk~h!K7|@ohB)8*<7#f4f{h-tpjr;{l*j z4+l{}(CV@VhXlE!eOV*&vh4@!X4Sdp|0*;D_hm%&2-}Bv*wHDl3j|^gGqPQPEqWrRM zy3gS~!csVX+~-kh7F7v3E_FOTE3l6vhc5V?|2|Q!xS@`$t9~L?l098~<=v2y_Vz?w zM)tp_VL1ecgUGtBX=KNnLqYOH&+*l3v5%1xCmtX$bS4|lNQ_?o|drj(|WZuq43_}tLa%d)09$C z^9*~WUHfBd^6<;a=uA;7P3-{|(cg4@h0i&SB9Vu*n>-v2 z+9{gdzsLXj31VGzz*gZwO^x`$m;|Gaz6Ycs4moE!#V$`{N)lqm_V2Ta4Y@mg2c$yw z%9e~${Ns?~?WX(Q#e>QEZ0~ToS*6KLZJ@3EvQ)jv`FYq^lNWCr3-Y7}Icgqf4)^4} zQ6w-HEv^*Tj7sxv8#mhn@%_biR-=`g9Fr$nLudN8v&c!l)lud`-upE@l$mjd!C>2l zYJMF>pJT%W>0wLdT}$FUcGsel469OQDWvQwf7-?KbFT#9Qdp6;rVq|a;Q_^v$g)|w zV*eH9oXkPpYbs{R?9r%_zQqT#UoX~t7)TAt2NnUJ;R*2|X2L+e_tTprxSrVybgDd3Fqk$^M3N8V1uwJ7-dZhLK;QtNc^*7Ny{e=CpDMdvQ9VN4b7 zJIUsMYaG2-twveOZz_|m0y3J1H$`Fos%}R+Y0S(p+#j~+!v(DuxCO)ts|4u3Sa9kT z`#7pO$=RBz#-rcn)H0?*UcK#Npm5fWai5MTq`vFVvxwVK!=au~-I19lYn{8?oCLuO zE@N-SZO|jB($qs}v(53~>IQhCU5L~J3Bj*QhT!wKE(2;_J__-#VQQ%~M|3D7kd|Gb5htjMI8-ETX+@crTTnMDcU!kkCAqYt8 zONK=K@D5K*?370u3~Ts|^8J7Sp{kmyM0~VCJ~-mAikhy|C1?wtoEw znwzf6xV_L~#jW0Z1v!it4sBqGe)`q#u;LOA_)}&Y&Y%bM_QNaLWS>F<%ngkAMYh=w zr2=o~O$9_uidBeG{&!OwcifACBAwI8s6>sZ1wsO1TkCCH^uSb{|LZi@-0m;3(v==s zMjjcR(vnzmg8Z$kU`64eUGN8r`;$75bJHrDcoFBJVL|;zI-B9%kKH|A`l=b%@+lX? zV~6F⁡lEX+}wR>F+zFz{RAnsJC|UkloojG||F)_f;=BtU8f;7kNRl-pkqDk-f~3 zy{K`B8|2h5ba2ksd%Ie!zBvhnUhiu#-A`gjz=%Vj=4ND6Fh@I`*S$IS2WwLM_;8{X zJjNS-E#}oF+1t-QHdFa`Hndw@WRS}IST3#>a{)gXARgeE{9zK;pR z-KJPZXR&NS5LYzPaVHsZQ7@SQ8Vv z6M>avss71r>0n--oV$MS2~APLN-v~=^@N}#K?b+BJ9(pRm#ZOd7oS1&6c*~zIYU83 z0E29EK_-c;Ho=IGZ{!CUBBE+k(Dm}T`ElmGR=2q?`|@|1*h-X5S6_GUao-|KxI!xG zvQ#k_k<@z+vYKxnSr2G8kA48o3?#U30pg8#!b%J&PG{@GB_ z{YKc<2-}0zdcIw=yJqLO9P$nL>ysCk|JyaVKM-Vsu2YL zL_C{<$tTe0I(2gHR8cX`7v;>5P#h_Ll-wM)Yd0ER9bcQvGR*D^Yjez)(0Q!)M<5c& zE%$Rpn~d5`1q=j!hkN?wKwNNUfJD*{^&`GypqFmvj!L;w0M=fGEyUF4z#<&txY#kD=hzUS`~CGpAHkh9_BAEEmNq=>*LAaMNDo1;*Y&%E_uzSU0C~bHIovq z>{j4Hu&fLqMk@}k&!6C)0@J%#8|75T;h26 - - + \ No newline at end of file diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java index bf11ac6..6f5e87f 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java @@ -108,8 +108,7 @@ public void closeConnection() { public static Connection getConnection(String url) throws SQLException { return DriverManager.getConnection(url); } - - + // ---------------------------------------------------------------------------------------------------------------- // ------------------------ CREATE -------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------- From 38b8320d526f7ff8720bb679b7fa8424a758f535 Mon Sep 17 00:00:00 2001 From: Roberto Negro Date: Tue, 27 Feb 2024 20:10:33 +0100 Subject: [PATCH 15/15] Commit cambiamento backend attacco --- .../app/src/component/mappa/ConsoleDifesa.js | 23 ++++++++----- src/main/app/src/component/mappa/SvgMap.js | 2 +- .../eclipse/controller/EventController.java | 5 +-- .../risiko/maven/eclipse/model/Game.java | 2 +- .../risiko/maven/eclipse/model/Territory.java | 5 +++ .../risiko/maven/eclipse/model/Turn.java | 13 ++++---- .../service/database/DaoSQLiteImpl.java | 5 --- .../maven/eclipse/states/BattleState.java | 33 ++++++++++--------- .../maven/eclipse/states/GameState.java | 2 +- .../maven/eclipse/states/StartTurnState.java | 7 ++-- 10 files changed, 51 insertions(+), 46 deletions(-) diff --git a/src/main/app/src/component/mappa/ConsoleDifesa.js b/src/main/app/src/component/mappa/ConsoleDifesa.js index 21dd48e..06b2f2b 100644 --- a/src/main/app/src/component/mappa/ConsoleDifesa.js +++ b/src/main/app/src/component/mappa/ConsoleDifesa.js @@ -1,15 +1,20 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { Alert, Button, Container } from "react-bootstrap"; import appController from "../../application/AppController"; function ConsoleDifesa({ idPartita, difendente }) { const [numeroDadi, setNumeroDadi] = useState(0); + const [stateDefenser, setStateDefenser] = useState(""); + + useEffect(() => { + setStateDefenser("sei sotto attacco"); + }, [stateDefenser]); - const handleDice = () => { - setNumeroDadi(numeroDadi + 1); - - console.log("numeroDadi", numeroDadi); + const handleDice = (num) => { + // Imposta il numero di dadi in base al numero associato al dado + setNumeroDadi(num); }; + const handleDefense = () => { const oggettoDifesa = { numDefDice: numeroDadi, @@ -21,11 +26,11 @@ function ConsoleDifesa({ idPartita, difendente }) { return ( - Sei sotto attacco + {stateDefenser}
- - - + + +
diff --git a/src/main/app/src/component/mappa/SvgMap.js b/src/main/app/src/component/mappa/SvgMap.js index edc41f9..f198c31 100644 --- a/src/main/app/src/component/mappa/SvgMap.js +++ b/src/main/app/src/component/mappa/SvgMap.js @@ -61,7 +61,7 @@ function SvgMap({ setGameState(statoGioco); console.log("stato del gioco nella mappa", statoGioco); - }, [gioco, nickname, myColor]); + }, [gioco, nickname, myColor, truppeAssegnate]); const calculateOpacity = (name, territoryAttack, territoryNeighbors, territoryDefense, sxSelected) => { if (name === territoryAttack || name === territoryDefense) { diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java index 73040cd..2745141 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/controller/EventController.java @@ -93,7 +93,8 @@ public void confirmSetup(@DestinationVariable String id, @Payload SetUpBody body } catch (Exception e) {LOGGER.error("Errore durante la conferma del setup", e);} } - @MessageMapping("/partite/{id}/comboRequest") + + public void comboRequest(@DestinationVariable String id, @Payload ComboRequestBody body) throws Exception { try { LOGGER.info("Inizio Combo request"); @@ -123,7 +124,7 @@ public void turnAssignation(@DestinationVariable String id, @Payload SetUpBody b @MessageMapping("/partite/{id}/attack") public void attackRequest(@DestinationVariable String id, @Payload AttackRequestBody body) { - LOGGER.info("Inizio attacco {}", body); + LOGGER.info("1------ Inizio attacco {}", body); try { IGame game = GameRepository.getInstance().getCompletedGame(id); Player player = game.findPlayerByUsername(body.getAttackerTerritory().getUsername()); diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java index 464fb91..3a5b8f1 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Game.java @@ -35,8 +35,8 @@ public synchronized void addPlayer(Player g) throws FullGameException { @Override public void onActionPlayer(ActionPlayer action) throws FullGameException, GameException, DatabaseConnectionException, UserException, IOException { + LOGGER.info("2------ Partita {} - state {}", id, state.getClass().getSimpleName()); action.accept(state); - LOGGER.info("Sto per fare broadcast alla partita {}", id); broadcast(); } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Territory.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Territory.java index dbdf8bc..23c6555 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Territory.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Territory.java @@ -22,4 +22,9 @@ public class Territory implements Serializable{ private List neighbors; private String svgPath; + + @Override + public String toString() { + return "Territory [name=" + name + ", armies=" + armies + ", idOwner=" + idOwner + "]"; + } } diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java index 336eb7d..8952a12 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/model/Turn.java @@ -54,8 +54,8 @@ public void resetBattleInfo() throws GameException, DatabaseConnectionException, Territory t = Territory.builder().name("").build(); - GameRepository.getInstance().updateAttackerTerritory(this, t ); - GameRepository.getInstance().updateDefenderTerritory(this, t ); + GameRepository.getInstance().updateAttackerTerritory(this, t); + GameRepository.getInstance().updateDefenderTerritory(this, t); GameRepository.getInstance().updateNumAttackDice(this, 0); GameRepository.getInstance().updateNumDefenseDice(this, 0); } @@ -74,9 +74,6 @@ public int continentCheck(List territories){ List continentName = c.getTerritories().stream().map(Territory::getName).collect(Collectors.toList()); if (territoriesName.containsAll(continentName)) { troops += c.getBonusArmies(); - } else { - LOGGER.info("Player doesn't have all the territories of the continent"); - LOGGER.info("Player objective: {}", player.getObjective().toString()); } } return troops; @@ -164,15 +161,17 @@ public void attack() throws GameException, DatabaseConnectionException, UserExce LOGGER.info(LOG, attRolls, defRolls); LOGGER.info(LOG, attLosses, defLosses); + LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); + + if(defenderTerritory.getArmies() > defLosses) { LOGGER.info("Siamo nell'if"); - LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); attackerTerritory.setArmies(attackerTerritory.getArmies() - attLosses); GameRepository.getInstance().updateTerritoryArmies(attackerTerritory.getName(), player.getGameId(), attackerTerritory.getArmies()); defenderTerritory.setArmies(defenderTerritory.getArmies() - defLosses); GameRepository.getInstance().updateTerritoryArmies(defenderTerritory.getName(), player.getGameId(), defenderTerritory.getArmies()); LOGGER.info(LOG, attackerTerritory.getArmies(), defenderTerritory.getArmies()); - resetBattleInfo(); + //resetBattleInfo(); } else { LOGGER.info("Siamo nell'else"); diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java index 6f5e87f..e522d4e 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/service/database/DaoSQLiteImpl.java @@ -256,7 +256,6 @@ public Player getPlayer(String username, String gameId) throws GameException, IO .setUpCompleted(rs.getBoolean("setUpCompleted")) .build(); } - LOGGER.info("Player sdsdsaadasdasdasdasd: {}", player); return player; } catch (SQLException e) { throw new GameException("Errore durante il recupero del giocatore.", e); @@ -667,17 +666,13 @@ private ObjectiveCard findObjectiveCard(String description, String gameId) throw IGame game = getGame(gameId); ObjectivesDeck objectiveCards = (ObjectivesDeck) game.getDeckObjective(); ObjectiveCard cardReturn = null; - LOGGER.info("Description: {}", description); List cards = new LinkedList<>(objectiveCards.getCards()); - LOGGER.info("Cards: {}", cards.size()); for (ObjectiveCard card : cards) { if (card.getObjective().equals(description)) { cardReturn = card; - LOGGER.error("Carta {} ------ trovata", description); return cardReturn; } } - LOGGER.error("Carta {} non trovata", description); return cardReturn; } } \ No newline at end of file diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java index 40e9ba6..6dcb25c 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/BattleState.java @@ -1,8 +1,9 @@ package com.mvcguru.risiko.maven.eclipse.states; +import java.io.IOException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import com.mvcguru.risiko.maven.eclipse.actions.AttackRequest; import com.mvcguru.risiko.maven.eclipse.actions.ConquerAssignment; import com.mvcguru.risiko.maven.eclipse.actions.DefenceRequest; @@ -23,33 +24,35 @@ public class BattleState extends GameState{ @Override public void onActionPlayer(AttackRequest attackRequest) throws GameException, DatabaseConnectionException, UserException { - + LOGGER.info("3------ AttackRequest {}", attackRequest.toString()); Territory attacker = GameRepository.getInstance().getTerritory(attackRequest.getRequestAttackBody().getAttackerTerritory().getNameTerritory(), attackRequest.getPlayer().getUserName(), game.getId()); Territory defender = GameRepository.getInstance().getTerritory(attackRequest.getRequestAttackBody().getDefenderTerritory().getNameTerritory(), attackRequest.getRequestAttackBody().getDefenderTerritory().getUsername(), game.getId()); + game.getCurrentTurn().setDefenderTerritory(defender); - GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), game.getCurrentTurn().getNumAttDice()); - + GameRepository.getInstance().updateNumAttackDice(game.getCurrentTurn(), attackRequest.getRequestAttackBody().getNumAttDice()); GameRepository.getInstance().updateAttackerTerritory(game.getCurrentTurn(), attacker); - GameRepository.getInstance().updateDefenderTerritory(game.getCurrentTurn(), defender); - - - game.getCurrentTurn().setNumAttDice(attackRequest.getRequestAttackBody().getNumAttDice()); - - game.getCurrentTurn().setAttackerTerritory(attacker); - - game.getCurrentTurn().setDefenderTerritory(defender); - } @Override - public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException { - LOGGER.info("DefenceRequest"); + public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException, IOException { + LOGGER.info("5------ DefenceRequest {}", defenceRequest.toString()); + + Territory attacker = GameRepository.getInstance().getTerritory(game.getCurrentTurn().getAttackerTerritory().getName(), game.getCurrentTurn().getPlayer().getUserName(), game.getId()); + Territory defender = GameRepository.getInstance().getTerritory(game.getCurrentTurn().getDefenderTerritory().getName(), defenceRequest.getPlayer().getUserName(), game.getId()); + + game.getCurrentTurn().setAttackerTerritory(attacker); + game.getCurrentTurn().setDefenderTerritory(defender); + game.getCurrentTurn().setNumAttDice(GameRepository.getInstance().getTurn(game.getId(), game.getCurrentTurn().getIndexTurn()).getNumAttDice()); game.getCurrentTurn().setNumDefDice(defenceRequest.getDefenderRequestBody().getNumDefDice()); + GameRepository.getInstance().updateNumDefenseDice(game.getCurrentTurn(), game.getCurrentTurn().getNumDefDice()); + game.getCurrentTurn().attack(); + + System.out.println("attacco finito "); } @Override diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java index bfbeeef..b1cc48b 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/GameState.java @@ -61,7 +61,7 @@ public void setUpGame() throws GameException, DatabaseConnectionException, UserE public void onActionPlayer(TurnSetUp turnSetUp) throws GameException, DatabaseConnectionException, UserException {} - public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException{} + public void onActionPlayer(DefenceRequest defenceRequest) throws GameException, DatabaseConnectionException, UserException, IOException{} public void onActionPlayer(ConquerAssignment conquerAssignment)throws GameException, DatabaseConnectionException, UserException {} diff --git a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/StartTurnState.java b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/StartTurnState.java index e2e254a..9c1c63a 100644 --- a/src/main/java/com/mvcguru/risiko/maven/eclipse/states/StartTurnState.java +++ b/src/main/java/com/mvcguru/risiko/maven/eclipse/states/StartTurnState.java @@ -70,15 +70,12 @@ public void onActionPlayer(TurnSetUp turnSetUp) throws GameException, DatabaseCo } catch (GameException | DatabaseConnectionException | UserException e) { LOGGER.error("Errore nell'aggiornamento delle truppe del territorio {}", territory.getName()); } - LOGGER.info("Territorio {} con truppe {}", territory.getName(), territory.getArmies()); }); } - LOGGER.info("fine action"); + LOGGER.info("Fine assegnazione truppe del turno"); game.setState(BattleState.builder().game(game).build()); - GameRepository.getInstance().updateState(game.getId(), game.getState()); - LOGGER.info("fine broadcast"); - + GameRepository.getInstance().updateState(game.getId(), game.getState()); } }