From bed8f7187929d1473d1530b2904e6ce4a5341e81 Mon Sep 17 00:00:00 2001 From: Lorenz Hohmann Date: Mon, 17 Jan 2022 15:32:58 +0100 Subject: [PATCH] Implemented gameOver() function in GUI with test case --- .../de/tims/fleetstorm/gui/GameLogic.java | 24 ++++++++++++++++--- .../de/tims/fleetstorm/gui/LogicTest.java | 10 ++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/tims/fleetstorm/gui/GameLogic.java b/src/main/java/de/tims/fleetstorm/gui/GameLogic.java index 865e59c..04c82ee 100644 --- a/src/main/java/de/tims/fleetstorm/gui/GameLogic.java +++ b/src/main/java/de/tims/fleetstorm/gui/GameLogic.java @@ -26,7 +26,7 @@ public class GameLogic extends JPanel { public static final int PREPARATION = 1; public static final int RUNNING = 2; - public static final int OVER = 3; + public static final int GAME_OVER = 3; // GUI stuff private ArrayList playerFields; @@ -38,13 +38,13 @@ public class GameLogic extends JPanel { setSize(640, 480); - JPanel fieldWrapper = new JPanel(); + fieldWrapper = new JPanel(); fieldWrapper.setBounds(10, 11, 305, 458); fieldWrapper.setLayout(null); setLayout(null); add(fieldWrapper); - JPanel enemyFieldWrapper = new JPanel(); + enemyFieldWrapper = new JPanel(); enemyFieldWrapper.setLayout(null); enemyFieldWrapper.setBounds(326, 11, 305, 458); add(enemyFieldWrapper); @@ -94,6 +94,12 @@ public class GameLogic extends JPanel { boolean shotSuccess = chosenField.shoot(); + boolean areAllShipsHit = enemyMatchfield.areAllShipsHit(); + if (areAllShipsHit) { + gameOver(true); + return; + } + if (shotSuccess && chosenField.getState() != Coordinate.HIT) { nextMove(false); } else { @@ -163,6 +169,8 @@ public class GameLogic extends JPanel { * This function is only for testing */ private static GameLogic gui; + private JPanel fieldWrapper; + private JPanel enemyFieldWrapper; public static void main(String[] args) { JFrame frame = new JFrame("Test GUI"); @@ -223,12 +231,22 @@ public class GameLogic extends JPanel { gui.updateFields(); + boolean areAllShipsHit = this.matchfield.areAllShipsHit(); + if (areAllShipsHit) { + this.gameOver(false); + return; + } + boolean aiHasNextMove = aiChosenField.getState() != Coordinate.HIT; this.nextMove(aiHasNextMove); } } + protected void gameOver(boolean playerWinner) { + this.gameState = GameLogic.GAME_OVER; + } + public int getGameState() { return gameState; } diff --git a/src/test/java/de/tims/fleetstorm/gui/LogicTest.java b/src/test/java/de/tims/fleetstorm/gui/LogicTest.java index 2b1e357..4b02637 100644 --- a/src/test/java/de/tims/fleetstorm/gui/LogicTest.java +++ b/src/test/java/de/tims/fleetstorm/gui/LogicTest.java @@ -23,4 +23,14 @@ class LogicTest { assertEquals(expectedState, calculatedState); } + @Test + void testIfGameStateIsGameOverAfterGameOverFunction() { + int expectedState = GameLogic.GAME_OVER; + + guiLogic.gameOver(true); + int calculatedState = guiLogic.getGameState(); + + assertEquals(expectedState, calculatedState); + } + }